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-bpe-size-structure.added.md b/changelog.d/1705-uk-firm-bpe-size-structure.added.md new file mode 100644 index 0000000000..f39088b5c4 --- /dev/null +++ b/changelog.d/1705-uk-firm-bpe-size-structure.added.md @@ -0,0 +1,5 @@ +Add opt-in BPE 2025 size-structure switches to the UK firm build (microcosm#1705), all needing `--bpe-dir`: +- `--bpe-mid-headcount` remaps headcount of ONS-frame rows inside the ONS 5-9 to 100-249 bands to BPE Table 1 shapes by weighted rank, keeping bands, ranks and weights. +- `--bpe-large-headcount` gives the top private 250+ firms BPE's 1000+ and 500-999 counts and shapes (a truncated Pareto on [1000, 500,000] for 1000+, an assumption). It raises paybill to about 1.28× ASHE annual jobs × mean, so it stays out of the reference build. +- `--out-of-frame-no-employees` gives the HMRC zero-turnover traders outside the ONS frame no headcount, an assumption with no published pin. +With `--bpe-dir` the receipt also adds a report-only ratio (`paybill_vs_bpe_employees_x_ashe_mean`) of paybill to BPE employees × ASHE all-employee mean beside the usual ASHE annual-jobs check. diff --git a/changelog.d/1705-uk-firm-bpe-turnover.added.md b/changelog.d/1705-uk-firm-bpe-turnover.added.md new file mode 100644 index 0000000000..b34644d8ee --- /dev/null +++ b/changelog.d/1705-uk-firm-bpe-turnover.added.md @@ -0,0 +1 @@ +Add an opt-in BPE turnover switch to the UK firm build (microcosm#1705), needing `--bpe-dir`: `--bpe-turnover` draws the open ONS turnover band on a truncated Pareto tail pinned to BPE whole-economy turnover instead of the log-uniform draw capped at £50m, and re-pairs employment with turnover inside each SIC division by a Gaussian copula fitted to BPE turnover by employment band. diff --git a/changelog.d/1705-uk-firm-capex-fixture.added.md b/changelog.d/1705-uk-firm-capex-fixture.added.md new file mode 100644 index 0000000000..25adbf49fc --- /dev/null +++ b/changelog.d/1705-uk-firm-capex-fixture.added.md @@ -0,0 +1 @@ +Add a UK firm capital expenditure fixture (ONS business investment by asset 2024; ABS 2024 capex by section) and a design note (`docs/uk-firm-capex-design.md`). No build reads it: taxable profit is drawn after allowances, so capex is not fed to policyengine-uk. diff --git a/changelog.d/1705-uk-firm-consumption.added.md b/changelog.d/1705-uk-firm-consumption.added.md new file mode 100644 index 0000000000..f1264a6a54 --- /dev/null +++ b/changelog.d/1705-uk-firm-consumption.added.md @@ -0,0 +1 @@ +Add opt-in consumption-link columns for UK firms (microcosm#1705): with `--consumption-dir`, turnover is split into `firm_household_sales`, `firm_intermediate_sales` and `firm_other_final_sales` by the firm's SIC division's shares of total demand in the ONS Supply and Use Tables 2024 (Blue Book 2026), with wholesale and retail weighted by distributors' margins. A SIC division × COICOP share table from the household final consumption bridge links firm household sales to household spending; the bridge's COICOP totals equal ONS Consumer Trends 2024. A diagnostic splits 2024 household purchases by source of supply (domestic output, imports, distributors' margins, taxes less subsidies) to show how much of Consumer Trends lies outside UK firms' output at basic prices; it is recorded in the receipt, never used as a target. diff --git a/changelog.d/1705-uk-firm-employment-allowance-takeup.added.md b/changelog.d/1705-uk-firm-employment-allowance-takeup.added.md new file mode 100644 index 0000000000..467b9780d1 --- /dev/null +++ b/changelog.d/1705-uk-firm-employment-allowance-takeup.added.md @@ -0,0 +1 @@ +Add an opt-in, assumed Employment Allowance claim draw for UK firms (microcosm#1705): eligible firms (rule flag, at least one employee, not a public body or single-director company, proxy employer NIC below £100,000) claim at HMRC's 2024-25 take-up by employee size band (1-9, 10-49, 50+ pooled; the suppressed 250+ count is ignored). HMRC's sector and region take-up tables (June 2025) are saved as held-out checks. The build draws it with `--employment-allowance-takeup-dir`, which needs `--bpe-dir` and `--employment-allowance-flags`, and keeps the rule flag as `firm_employment_allowance_rule_claims`. The pooled 50+ band falls short of HMRC's 7,000: at section-mean pay almost no firm that size passes the proxy £100,000 NIC limit, so drawn claimants total about 1.21 million rather than 1.223 million. diff --git a/changelog.d/1705-uk-firm-employment-allowance.added.md b/changelog.d/1705-uk-firm-employment-allowance.added.md new file mode 100644 index 0000000000..6219bdd96e --- /dev/null +++ b/changelog.d/1705-uk-firm-employment-allowance.added.md @@ -0,0 +1 @@ +Add opt-in assumed Employment Allowance flags to the UK firm export (microcosm#1705; `--employment-allowance-flags`): sole proprietors with employment of at most 1 and partnerships with employment of at most 2 do not claim, and companies with employment 1 are single-director companies. HMRC tax relief statistics (January 2026) for 2024-25 are saved as a held-out check, not a target. diff --git a/changelog.d/1705-uk-firm-empty-property.added.md b/changelog.d/1705-uk-firm-empty-property.added.md new file mode 100644 index 0000000000..d73fa36bcc --- /dev/null +++ b/changelog.d/1705-uk-firm-empty-property.added.md @@ -0,0 +1,5 @@ +Add MHCLG empty property figures for England as a standalone reader and diagnostics only; the build does not read them (microcosm#1705; `uk_firm_empty_property_published_figures`). The figures are hereditaments in receipt of empty premises relief on 31 December 2023 and 2024 by category, empty relief values for 2024-25 and 2025-26 (NNDR1 supplementary tables), and NNDR3 2024-25 outturn. `firm_property_occupied` and `firm_months_empty` stay unset for three reasons: + +- the count is a stock on one date, but policyengine-uk's flag covers the whole year; +- empty hereditaments are not trading firms; +- months empty could only be calibrated to a relief total. 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-labour-link.added.md b/changelog.d/1705-uk-firm-labour-link.added.md new file mode 100644 index 0000000000..6955b4a08f --- /dev/null +++ b/changelog.d/1705-uk-firm-labour-link.added.md @@ -0,0 +1 @@ +Add an opt-in BPE headcount source for UK firms (microcosm#1705): with `--bpe-dir`, headcount inside the ONS 0-4 employment band is redrawn by legal status from DBT Business Population Estimates 2025 Table 3, `firm_employees` becomes employment less assumed working proprietors (one per sole proprietor, up to two per partnership), the paybill and pay split are set on employees, and the export gains labour-link columns for matching with household data: `ons_employment`, `firm_employee_size_band`, `firm_mean_pay` and `firm_is_public_sector`. The build receipt reconciles employment and employees by size band with BPE. The redraw puts about 58% of 0-4 band companies at employment 1, which roughly doubles the single-director companies the Employment Allowance flags exclude. diff --git a/changelog.d/1705-uk-firm-large-employment-frame.changed.md b/changelog.d/1705-uk-firm-large-employment-frame.changed.md new file mode 100644 index 0000000000..91e9d4e437 --- /dev/null +++ b/changelog.d/1705-uk-firm-large-employment-frame.changed.md @@ -0,0 +1 @@ +With `UKFirmGenerationConfig.large_employment_mean` set (opt-in), only in-frame rows can reach the 250+ employment band: out-of-frame rows the draw would put at 250+ get 1 to 249 from their sector's sub-250 shares, so the Pareto tail covers in-frame 250+ firms only (microcosm#1705). The default build is unchanged. diff --git a/changelog.d/1705-uk-firm-large-employment.changed.md b/changelog.d/1705-uk-firm-large-employment.changed.md new file mode 100644 index 0000000000..75414ffd66 --- /dev/null +++ b/changelog.d/1705-uk-firm-large-employment.changed.md @@ -0,0 +1,15 @@ +`UKFirmGenerationConfig` gains `large_employment_mean` (microcosm#1705), which lifts the 2,000-staff cap on UK firms with 250 or more employees. By default (`None`) the open 250+ band keeps the paper's draw: a lognormal (median 400, log-sd 0.8) clamped to [250, 2000], whose weighted mean is about 620. With a mean set, `assign_employment` ranks the band's rows by that same lognormal draw, so torch's generator stream and every other column are unchanged, and gives them consecutive base-weight-sized slices of a truncated Pareto on [250, 500,000] (`LARGE_EMPLOYMENT_CAP`) with that mean. The band's base-weighted mean is then the chosen mean, with no sampling noise from the heavy tail. `LARGE_EMPLOYMENT_MEAN`, 1,347.3, is DBT's private-sector mean: Business population estimates 2024, Table 1 (UK private sector, start 2024), 11,115 thousand employment over 8,250 businesses with 250 or more employees. At that mean the fitted shape (about 1.14) puts 54% / 25% / 21% of the band in 250–499 / 500–999 / 1,000+, against DBT's 51% / 26% / 23%. The three DBT rows are fixtured, with the workbook's sha256, under `tests/fixtures/uk/firm_2024_25_size/`. + +The default is unchanged because the model's 250+ population is not DBT's. On the 20-iteration thinned 2024-25 test build (seed 42), the band holds 12,898 weighted firms: 11,387 in the ONS frame, close to BPE's whole-economy 11,265 (Table 2: private, government and non-profit), and 1,511 among the appended zero-turnover HMRC traders. DBT counts 8,250 private businesses. Measured on that build: + +| 250+ setting | 250+ employment | 250+ employment outside ONS statuses 5–6 | Total weighted paybill ÷ ASHE £1.007tn | Paybill in firms above £3m | +| --- | --- | --- | --- | --- | +| Default (clamped at 2,000) | 7.98m (mean 618) | 7.33m | 1.06 | £486bn | +| DBT mean, 1,347.3 | 17.85m (mean 1,384) | 16.15m | 1.48 | £901bn | +| DBT total, mean 839.8 | 11.01m (mean 854) | 10.01m | 1.19 | £618bn | + +The DBT mean overshoots DBT's 11.1 million private 250+ employment and falls outside the ASHE paybill guard in `test_uk_firm_extended_export.py` (0.85–1.25), which is why it is opt-in. + +The default stays the legacy draw. Changing it is blocked until public and non-profit 250+ firms are separated and out-of-frame zero-turnover traders stop drawing 250+ headcounts (1,511 weighted firms on the thinned build). Paybill is already 1.064× ASHE jobs × mean at 7.98m 250+ employment, so reaching DBT's 11.1m may also need sub-250 employment or per-head pay rebalanced. + +The "DBT total" row sets the mean to DBT's 11,115,000 divided by the thinned build's base-weighted 250+ count (13,235). It was measured on one local build and is not fixtured. A mean the Pareto cannot hit exactly, outside about 263 to 56,876 on [250, 500,000], is refused. 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-pay-distribution.added.md b/changelog.d/1705-uk-firm-pay-distribution.added.md new file mode 100644 index 0000000000..f1bedd0456 --- /dev/null +++ b/changelog.d/1705-uk-firm-pay-distribution.added.md @@ -0,0 +1 @@ +Add opt-in assumed `firm_employees_below_secondary_threshold` and `firm_paybill_below_secondary_threshold` for UK firms (microcosm#1705; `--pay-distribution-dir`, needs `--paybill-dir`): the share of each SIC section's ONS ASHE 2025 (tax year 2024-25) jobs at or below the £9,100 secondary threshold, from a piecewise-linear curve through the published annual pay percentiles, with a separate fixed-seed draw for the remainder. Below the tenth percentile the curve is an assumption (from £0), not data. diff --git a/changelog.d/1705-uk-firm-paybill-anchor.added.md b/changelog.d/1705-uk-firm-paybill-anchor.added.md new file mode 100644 index 0000000000..62d96bd922 --- /dev/null +++ b/changelog.d/1705-uk-firm-paybill-anchor.added.md @@ -0,0 +1 @@ +Add report-only UK paybill anchors (`firm_paybill_anchor.py`, `--paybill-anchor-dir`, needs `--paybill-dir`): ONS wages and salaries (D.11, DTWL) for 2024, and PAYE RTI aggregate pay and payrolled employees for 2024-25, pinned by sha256. The receipt divides the build's weighted paybill and employees by each anchor. The binding paybill guard (ASHE jobs times mean pay, 0.85-1.25) is unchanged. diff --git a/changelog.d/1705-uk-firm-paybill.added.md b/changelog.d/1705-uk-firm-paybill.added.md new file mode 100644 index 0000000000..8ce7f1b7f9 --- /dev/null +++ b/changelog.d/1705-uk-firm-paybill.added.md @@ -0,0 +1,5 @@ +UK firms can carry a paybill (microcosm#1705). `uk_runtime/firm_paybill.py` sets policyengine-uk's `firm_paybill` to the firm's headcount times the mean annual gross pay of its SIC 2007 section from ONS ASHE Table 4.7a (*Annual pay - Gross*), 2025 revised edition, sheet `All` (all employee jobs, full-time and part-time). ASHE annual pay covers the tax year ending 5 April of the reference year, so the 2025 edition is tax year 2024-25. The section means are committed under `tests/fixtures/uk/firm_paybill_2024/` with the zip's and workbook's sha256s, and `tools/extract_uk_firm_paybill_table.py --check` re-extracts them from the downloaded zip. ONS suppresses section U, which, like the `UNKNOWN` section, takes the table's all-employees mean; `uk_firm_paybill_fallback_counts` counts the firms that do (none in the 2024-25 test build). + +The export adds `firm_paybill` (`UK_FIRM_PAYBILL_TABLE_COLUMNS`) only when attributed rows carry it, and `firm_paybill` is now `assumed` in `UK_FIRM_POLICYENGINE_UK_INPUT_STATUS`: every firm pays its section's mean, and ONS employment, which counts working proprietors, stands in for employees. ASHE's annual figures leave out jobs held for under a year and youth rates, so the means lean high. `build_uk_firm_dataset(paybill_dir=...)` and `tools/build_uk_firms.py --paybill-dir` turn it on and record the CSV's hash, the weighted paybill and the fallback counts in the receipt; without them the table and receipt are unchanged. The receipt also records `uk_firm_paybill` (status `assumed`, the method and tax year 2024-25) and the weighted paybill and employees split by `in_frame`; a paybill source with any `data_vintage` other than 2024-25 raises `ValueError`. + +Measured on the 20-iteration thinned 2024-25 test build (seed 42), the weighted paybill is £1.071 trillion on 26.7 million weighted employees, 6% above ASHE's own 24.9 million jobs times £40,445. That excess is the out-of-frame stratum: zero-turnover traders outside the frame (`in_frame` false) carry about 2.43 million weighted employees and about £103.8 billion of paybill (about 9.7%), and in-frame paybill is about 4% below ASHE's jobs times mean. Their paybill is kept, not zeroed. No firm has a zero headcount, so working proprietors get a paybill too: sole traders carry about £123 billion and partnerships about £45 billion (about 16% together). On the full 2024-25 build (2,946,015 rows, 1,000 epochs) the weighted paybill is £1.0255 trillion and no firm falls back to the all-employees mean. diff --git a/changelog.d/1705-uk-firm-profit.added.md b/changelog.d/1705-uk-firm-profit.added.md new file mode 100644 index 0000000000..34186f946f --- /dev/null +++ b/changelog.d/1705-uk-firm-profit.added.md @@ -0,0 +1 @@ +Add an opt-in assumed `firm_taxable_trading_profit` for UK firm companies (microcosm#1705; `--profit-dir`): HMRC Corporation Tax statistics 2026 liability bands for 2024-25 are inverted through the CT rate schedule and allotted to companies by turnover rank within SIC section, with a separate fixed-seed generator for ties. Corporation tax on these profits is in-sample. The sector table is saved as a held-out check. diff --git a/changelog.d/1705-uk-firm-public-sector.added.md b/changelog.d/1705-uk-firm-public-sector.added.md new file mode 100644 index 0000000000..db5c2b8f73 --- /dev/null +++ b/changelog.d/1705-uk-firm-public-sector.added.md @@ -0,0 +1 @@ +Add an opt-in rescale of UK firm public authority headcounts (microcosm#1705; `--public-sector-dir`): rows with ONS legal status 5 and 6 are scaled to ONS public sector employment for March 2025 (central government G6NQ, local government G6NT, headcount, UK), keeping the row count. Public corporations are left out. The status is `assumed`; NHS and education staff may already sit under other legal statuses. diff --git a/changelog.d/1705-uk-firm-rateable-value.added.md b/changelog.d/1705-uk-firm-rateable-value.added.md new file mode 100644 index 0000000000..557c2578df --- /dev/null +++ b/changelog.d/1705-uk-firm-rateable-value.added.md @@ -0,0 +1 @@ +Add an opt-in assumed `firm_rateable_value` for UK firms in England (microcosm#1705; `--rateable-value-dir`): the VOA non-domestic rating stock of properties (March 2026, 2023 rating list) is allotted to firms by headcount rank, one hereditament per firm, never calibrated to NNDR receipts. diff --git a/changelog.d/1705-uk-firm-rd-tax-credits.added.md b/changelog.d/1705-uk-firm-rd-tax-credits.added.md new file mode 100644 index 0000000000..8335f3e19c --- /dev/null +++ b/changelog.d/1705-uk-firm-rd-tax-credits.added.md @@ -0,0 +1,9 @@ +Add an opt-in, assumed R&D tax credit allocation for UK firms (microcosm#1705; `assign_uk_firm_rd_tax_credits(firms, source, *, seed)`). It uses HMRC's *Research and Development Tax Credits Statistics: September 2026*, 2024-25 provisional figures. + +- **Claimant strata.** In each SIC section, RD6 claims are split into large companies (RDEC plus merged RDEC by large companies) and SMEs, then scaled by RD1 companies over claims (37,545 / 40,325). +- **Drawing claimants.** Large claimants are taken top-down by headcount. SME claimants are drawn uniformly from the remaining companies. +- **Qualifying expenditure.** A section by size table is raked to RD6 section totals and RD4's large and SME totals (£30,245m and £20,725m). Each cell is shared over its claimants by turnover and capped at turnover; any remainder is reported as unallocated. +- **`firm_is_sme`.** Claimants take it from their stratum. Every other firm gets the headcount limb on ONS employment, proprietors included (fewer than 500); the euro turnover and balance-sheet limbs are not applied. +- **Not set.** `firm_total_relevant_expenditure` stays unset, so under the merged scheme every claimant gets the expenditure credit. + +The build sets both with `--rd-tax-credits-dir` (an `rd_tax_credits` export group). The turnover cap leaves part of the expenditure unallocated where firm turnover is low; the receipt reports the remainder. 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/1705-uk-firm-vat-composition.added.md b/changelog.d/1705-uk-firm-vat-composition.added.md new file mode 100644 index 0000000000..de5e92f2aa --- /dev/null +++ b/changelog.d/1705-uk-firm-vat-composition.added.md @@ -0,0 +1 @@ +Add an opt-in, columns-only UK firm VAT composition (`firm_vat_composition.py`, `--vat-composition-dir`, needs `--consumption-dir`). It attaches Microcosm-only `firm_sut_*` columns by SIC section: the standard-, reduced- and zero-rated and exempt shares of turnover, the export share, the input VAT rate and the input ratio. These come from the ONS Supply and Use Tables 2024 (Blue Book 2026), read through the VAT Act 1994 Schedules 7A, 8 and 9, with ABS 2024 turnover as the gross-sales base for trade. No policyengine-uk input changes, so VAT is still scored on all-standard-rated supplies. The receipt reports the section shares and checks eight relief bases against HMRC tax relief statistics (January 2026); these are never targets. The calibration seam (`UKFirmVATCompositionRules`, `rescale_uk_firm_input_costs`) is kept as experimental code. It failed review: the VAT liability band accuracy was 0.998973 against a 0.999 bar, and the held-out error of VAT by section doubled. 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..4672f3c85e 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,106 @@ 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. + +`firm_paybill` is an opt-in assumed input (headcount × ONS ASHE section mean +pay, `uk_runtime/firm_paybill.py`). Further opt-in assumed labour inputs, +each from a saved source, are the Employment Allowance flags, public sector +headcounts and the pay split below the secondary threshold. The labour link +(`--bpe-dir`, `uk_runtime/firm_headcount.py`) prepares the firm table for +linking to household data later; no person-firm link exists yet. It redraws +headcount inside the ONS 0-4 band by legal status from DBT Business +Population Estimates 2025 Table 3, sets `firm_employees` to employment less +assumed working proprietors, and adds `firm_sic_division`, `ons_employment`, +`firm_employee_size_band`, `firm_mean_pay` and `firm_is_public_sector`. A +labour match should agree on jobs by SIC section and public/private, by +region and by size band, on paybill by section and on the share of pay below +the secondary threshold, each side calibrated to external totals, not to the +other. The concepts differ: APS size is by workplace and the firm table's by +enterprise; FRS and RTI regions are by residence and the firm table's by +enterprise location; ONS employment counts working proprietors. The opt-in +Employment Allowance take-up draw (`--employment-allowance-takeup-dir`) uses +HMRC's 2024-25 claimants by employee size band, which then become in-sample. + +Taxable profit (`--profit-dir`, HMRC Corporation Tax statistics, so CT is +in-sample) and R&D expenditure (`--rd-tax-credits-dir`, HMRC R&D tax credit +statistics) are opt-in assumed inputs. Both go to ONS status 1 companies +only, so public corporations pay no corporation tax. + +Rateable value (`--rateable-value-dir`, the VOA rating-list stock) is an +opt-in assumed input. `uk_runtime/firm_empty_property.py` reads the MHCLG +empty-property figures as a standalone diagnostic; the build does not set +the empty-property inputs. + +The consumption link (`--consumption-dir`, `uk_runtime/firm_consumption.py`) +splits turnover into household, intermediate and other final sales by SIC +division from the ONS Supply and Use Tables 2024, with a division × COICOP +share table from the household consumption bridge for matching to LCFS +spending levelled to Consumer Trends. Household spending is at purchasers' +prices, so trade margins sit with retail and wholesale. Firm household sales +therefore cannot equal Consumer Trends: split in proportion to supply (an +assumption, `uk_household_purchases_supply_decomposition`), 2024 household +purchases outside imputed rent are about £903bn of domestic output at basic +prices, £233bn of imports, £163bn of distributors' margins and £99bn of taxes +less subsidies (plus £21bn bought from the motor trade directly). Imports and +taxes are outside UK firms' output at basic prices, so outside the +share-allocated household sales (gross trade turnover still includes resold +imports, and turnover includes excise duties). Firm-side household sales also +fall short because the generator's turnover is capped at £50m (unless the +opt-in `--bpe-turnover` tail is used) and is drawn independently of +employment, and because much of real estate, finance, insurance and health +output is imputed, non-market or unincorporated. Trade turnover is gross, +while SUT trade output is the margin only. The SUT year (2024) is not BPE's +(2025). + +The other policyengine-uk firm inputs (capital expenditure, the other +pay-distribution inputs and several flags) wait for sources. + ## External Prerequisites The first integration should depend on these upstream artifacts: @@ -21,7 +125,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 +137,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 +184,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 +215,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 +255,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/docs/uk-firm-capex-design.md b/docs/uk-firm-capex-design.md new file mode 100644 index 0000000000..11a83d2479 --- /dev/null +++ b/docs/uk-firm-capex-design.md @@ -0,0 +1,34 @@ +# UK firm capital expenditure by asset class: design note + +Status: design only. Nothing is built and nothing is fed to policyengine-uk. + +## Why it is not fed to pe-uk + +`firm_taxable_trading_profit` is allotted from HMRC CT liability bands. Those are profits after capital allowances and after losses brought forward. pe-uk's capital allowance inputs (`firm_capex_main_pool`, `firm_capex_special_rate_pool`, full expensing and the AIA) deduct allowances again. So supplying capex while profit is drawn after allowances would deduct them twice. + +The capex columns become pe-uk inputs only when profit is drawn **before** allowances. That needs a source for profit before allowances, such as HMRC CT statistics Table 11 (capital allowances claimed), or a CT600 aggregate. Losses brought forward would be fixture-only for the same reason. + +## Sources (pinned 26 Nov 2026; fixture `tests/fixtures/uk/firm_capex_2024/`, tool `tools/extract_uk_firm_capex_tables.py`) + +| Source | Edition | Use | +|---|---|---| +| ONS Business investment by asset, CP (Annual) | 30 Sep 2026 | 2024 business totals: transport £30.8bn (EDRB), ICT and other M&E £56.6bn (EDWH), other buildings and structures £81.1bn (EDYP), IPP £140.5bn (EDYS); total £309.1bn (NPEK) | +| ONS Annual Business Survey | 2024 results (26 May 2026) | Capex acquisitions and disposals by section A–S (£243.9bn and £39.9bn); no asset split | + +## Proposed method (for a later PR) + +1. **Section totals:** ABS acquisitions by section, minus disposals, are the business total. They cover the non-financial business economy only, so K and public bodies are excluded. +2. **Asset split:** each section takes the Blue Book 2026 GFCF by industry and asset mix of its divisions (not pinned yet; pin it when the method is built). The mix is whole-economy, so it is an "assumed" proxy for private firms. Sector mixes are then raked so that the asset totals match ONS business investment by asset. +3. **Within section:** capex is shared across firms by turnover, in proportion. Firms with no turnover get 0. This is assumed. ABS publishes no size split, so the share by size band is an open question. +4. **Mapping to pe-uk pools:** + - Plant and machinery (ICT and other M&E) goes to the main pool or full expensing. + - Long-life items and integral features go to the special-rate pool. These have no source, so the split is assumed. + - Structures go to SBA (3%). + - IPP is not a capital allowance; it falls under intangible fixed assets (CTA 2009 Part 8) and R&D. + - Vehicles go by CO2 band, and nothing pins that. +5. **Held-out check:** HMRC CT statistics on capital allowances claimed, by type. + +## Open questions + +- The ABS (2024) and business investment (2024) concepts differ: the ABS counts acquisitions; business investment is national accounts GFCF. +- Lumpiness: a firm-year capex draw needs a zero mass. Most small firms have no capex in a year, and nothing pinned here gives the share. 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..ec471bb455 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,63 @@ validate_uk_firm_population, write_uk_firm_population, ) +from microcosm.build.uk_runtime.firm_paybill import ( + UK_FIRM_PAYBILL_ALL_EMPLOYEES, + UK_FIRM_PAYBILL_FILE, + UK_FIRM_PAYBILL_LEVELS, + UK_FIRM_PAYBILL_METHOD, + UK_FIRM_PAYBILL_SOURCE_COLUMNS, + UK_FIRM_PAYBILL_STATUS, + UK_FIRM_PAYBILL_TAX_YEAR, + UKFirmPaybillSource, + assign_uk_firm_paybill, + read_uk_firm_paybill_source, + uk_firm_paybill_fallback_counts, + uk_firm_paybill_mean_pay, +) +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_PAYBILL_EXTENDED_POLICYENGINE_UK_COLUMNS, + UK_FIRM_PAYBILL_POLICYENGINE_UK_COLUMNS, + UK_FIRM_PAYBILL_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 +886,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 +1042,57 @@ "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", + "UK_FIRM_PAYBILL_ALL_EMPLOYEES", + "UK_FIRM_PAYBILL_FILE", + "UK_FIRM_PAYBILL_LEVELS", + "UK_FIRM_PAYBILL_SOURCE_COLUMNS", + "UK_FIRM_PAYBILL_METHOD", + "UK_FIRM_PAYBILL_STATUS", + "UK_FIRM_PAYBILL_TAX_YEAR", + "UKFirmPaybillSource", + "assign_uk_firm_paybill", + "read_uk_firm_paybill_source", + "uk_firm_paybill_fallback_counts", + "uk_firm_paybill_mean_pay", + "UK_FIRM_PAYBILL_EXTENDED_POLICYENGINE_UK_COLUMNS", + "UK_FIRM_PAYBILL_POLICYENGINE_UK_COLUMNS", + "UK_FIRM_PAYBILL_TABLE_COLUMNS", + "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_bpe_turnover.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_bpe_turnover.py new file mode 100644 index 0000000000..d307a1abd2 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_bpe_turnover.py @@ -0,0 +1,752 @@ +"""UK firm turnover against DBT BPE 2025: employment re-pairing and open tail. + +The experimental UK firm generator draws turnover from ONS turnover bands and, +independently, employment from ONS employment bands. Two consequences show up +against the DBT *Business population estimates 2025* (BPE) turnover by size +band: turnover is spread evenly over employment bands (no firm-size gradient), +and the open ONS "5000+" turnover band, drawn log-uniform on [£5m, £50m), +cannot hold the turnover BPE attributes to large businesses. This module adds +three opt-in pieces; none runs by default. ``firm_generation`` runs them when +``UKFirmGenerationConfig.bpe_turnover`` is set (``build_uk_firm_dataset``'s +``bpe_turnover``). + +A. Re-pairing (``repair_uk_firm_employment_turnover``). After employment is + drawn, the drawn employment values are permuted among ONS-frame rows + *within each SIC division* by a Gaussian copula on turnover rank: for row + ``i`` of a division with ``n`` frame rows and turnover rank ``r_i`` + (0-based, ties broken by firm id), ``z_i = rho * Phi^-1((r_i + 0.5) / n) + + sqrt(1 - rho^2) * eps_i``, where ``eps`` is a standard normal drawn from + ``np.random.default_rng(SeedSequence([seed, tag]))`` in firm-id order. The + row with the k-th smallest ``z`` takes the k-th smallest employment value of + that division's frame rows. Each division's multiset of employment values + and every row's turnover are kept exactly; rows outside the frame are not + touched. ``rho = 0`` is a random permutation, ``rho = 1`` a monotone + pairing. The permutation is unweighted: with stratified thinning (unequal + base weights) it keeps each division's row multiset but not its + base-weighted employment-band totals. + +B. ``rho`` fit (``fit_uk_firm_employment_turnover_rho``). ``rho`` is the + value on [0, 0.99] (a 0.05 grid, then a 0.005 grid around the best point) + minimising the squared error between the base-weighted turnover shares of + the seven ONS employment bands (0-4 ... 250+, on the generator's + employment, i.e. ONS employment including working proprietors) and the BPE + shares. The fit and the re-pairing share the same ``eps`` stream, so + applying the fitted ``rho`` reproduces the fit table exactly. ``rho`` is + never fixed in code. + +C. Open turnover band tail (``uk_firm_open_band_tail_parameters`` and + ``draw_uk_firm_open_band_turnover``). ONS "5000+" rows draw from a + truncated Pareto on [£5m, C] instead of log-uniform [£5m, £50m). Rows are + ranked by the generator's own uniforms (no new random draws) and the row + of rank k among n takes the mean of the distribution over the quantile + slice [k/n, (k+1)/n], so every value lies in [£5m, C] and the sample mean + equals the distribution mean exactly for any n. + +D. Diagnostics: ``uk_firm_turnover_by_employment_band`` (model against BPE, + with any weights, so before or after the solve) and + ``uk_firm_bpe_turnover_pins`` (every pin with its source). + +Pins and sources: + +- BPE turnover by size band: DBT, *Business population estimates 2025*, + detailed tables, + https://assets.publishing.service.gov.uk/media/68dbccc9c487360cc70c9f4e/BPE_2025_detailed_tables.xlsx + (landing page https://www.gov.uk/government/statistics/business-population-estimates-2025), + Table 2 whole economy turnover by employee band, less Table 1's "With no employees + (unregistered)" private-sector turnover, taken off the 0-4 band (the ONS + frame holds VAT- or PAYE-registered enterprises only). Read from + ``tests/fixtures/uk/firm_bpe_2025/bpe_size_bands.csv``. +- Section K: BPE turnover already excludes SIC 2007 Section K (fixture + provenance note), so nothing is subtracted on the BPE side; on the model + side the Section K divisions 64-66 are left out of every turnover share and + of the tail mean. +- Tail shape: ``P(turnover > £10m | open band)`` is HMRC VAT registered + traders in the "Greater_than_£10m" band divided by ONS enterprises in the + "5000+" turnover band (all SIC rows), both read from the generator's source + tables; ``alpha = -ln(p) / ln(10m / 5m)``, the untruncated Pareto reading. + This mixes VAT traders with ONS enterprises (assumed), and with the cap the + model's truncated ``P(> £10m)`` lands slightly under ``p`` + (``UKFirmOpenBandTail.model_p_over_10m`` reports it). +- Tail cap: C is solved so the non-K open-band mean equals (BPE whole-economy + turnover less BPE unregistered turnover less the drawn, weighted non-K + closed-band turnover) divided by the weighted non-K open-band firm count. + Section K open-band rows use the same shape (assumed). + +Assumptions and caveats (status ``assumed``): + +- BPE bands are by *employees*; the model's bands are ONS *employment* + (employees plus working proprietors). The bands are matched across that + difference ("Zero or 1" and "2 to 4" to 0-4, "100 to 199" and "200 to 249" + to 100-249, 250 and above to 250+). +- BPE describes the start of 2025; the ONS frame is the generator's vintage. +- BPE turnover by band becomes an in-sample fact for the shares and the tail + mean: a later comparison with that table is not an independent check. +- The tail's mean is exact within each call (or each ``strata`` group): the + non-K and Section K open-band rows must be ranked separately, or the non-K + mean is exact only in expectation. + +Every number comes from the source tables passed in; none is written here +beyond band definitions (ONS and HMRC band edges, SIC 2007 Section K). +""" + +from __future__ import annotations + +import math +import zlib +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from types import MappingProxyType +from typing import Any + +import numpy as np +import pandas as pd +from scipy.optimize import brentq +from scipy.special import ndtri + +from microcosm.build.uk_runtime.firm_headcount import UKFirmBPESource + +UK_FIRM_BPE_TURNOVER_STATUS = "assumed" +UK_FIRM_BPE_TURNOVER_METHOD = ( + "ONS-frame employment permuted within SIC division by a Gaussian copula on " + "turnover rank (rho fitted so base-weighted non-Section-K turnover shares " + "by ONS employment band match DBT Business population estimates 2025 " + "Table 2 whole-economy turnover by employee band less Table 1 " + "unregistered turnover); ONS 5000+ turnover drawn as rank-slice means of a " + "truncated Pareto on [5m, C], shape from HMRC traders above 10m over ONS " + "5000+ enterprises, cap C matching the BPE registered turnover left after " + "drawn closed-band turnover" +) + +#: ONS employment bands, in the generator's ``EMPLOYMENT_BANDS`` order. +UK_FIRM_TURNOVER_EMPLOYMENT_BANDS: tuple[str, ...] = ( + "0-4", + "5-9", + "10-19", + "20-49", + "50-99", + "100-249", + "250+", +) +#: Upper edges of the closed ONS employment bands (the generator's +#: ``ONS_EMPLOYMENT_BANDS``), for ``searchsorted`` band lookup. +_EMPLOYMENT_BAND_UPPER_EDGES = np.asarray((4.0, 9.0, 19.0, 49.0, 99.0, 249.0)) +#: BPE 2025 Table 2 employee bands summed into each ONS employment band. +UK_FIRM_BPE_BANDS_BY_ONS_BAND: Mapping[str, tuple[str, ...]] = MappingProxyType( + { + "0-4": ("Zero or 1 employee", "2 to 4"), + "5-9": ("5 to 9",), + "10-19": ("10 to 19",), + "20-49": ("20 to 49",), + "50-99": ("50 to 99",), + "100-249": ("100 to 199", "200 to 249"), + "250+": ("250 to 499", "500 to 999", "1000 or more"), + } +) +#: SIC 2007 Section K (financial and insurance activities) divisions. +SIC_SECTION_K_DIVISIONS: tuple[int, ...] = (64, 65, 66) +#: The ONS open turnover band label and its lower edge in £ thousands. +ONS_OPEN_TURNOVER_BAND_LABEL = "5000+" +OPEN_BAND_LOWER_K = 5_000.0 +#: Upper edge of the generator's legacy log-uniform open-band draw (£k). +OPEN_BAND_LOG_UNIFORM_UPPER_K = 50_000.0 +#: HMRC's top VAT turnover band and its exclusive lower edge (£k). +HMRC_TOP_TURNOVER_BAND = "Greater_than_£10m" +HMRC_TOP_BAND_LOWER_K = 10_000.0 +#: BPE rows the pins read. +_BPE_WHOLE_ECONOMY = ("Table 2", "whole_economy") +_BPE_PRIVATE_TABLE_1 = ("Table 1", "private_sector") +_BPE_ALL = "All" +_BPE_UNREGISTERED = "With no employees (unregistered)" +#: ``rho`` search: coarse grid, then a fine grid around the coarse best. +RHO_UPPER = 0.99 +_RHO_COARSE_STEP = 0.05 +_RHO_FINE_STEP = 0.005 +#: Distinguishes the re-pairing's random stream from any other use of seed. +_REPAIR_SEED_TAG = zlib.crc32(b"microcosm.uk_firm_bpe_turnover.repair") + + +# -- shared helpers -------------------------------------------------------------- + + +def _array(values: Any, name: str, n: int | None = None) -> np.ndarray: + array = np.asarray(values) + if array.ndim != 1: + raise ValueError(f"{name} must be one-dimensional.") + if n is not None and len(array) != n: + raise ValueError(f"{name} must have one entry per firm ({n}).") + return array + + +def _firm_ids(firm_ids: Any, n: int) -> np.ndarray: + if firm_ids is None: + return np.arange(n, dtype=np.int64) + ids = _array(firm_ids, "firm_ids", n) + if ids.dtype.kind not in "iu": + raise ValueError("UK firm ids must be integers.") + ordered = np.sort(ids.astype(np.int64)) + if ordered.size and np.any(np.diff(ordered) == 0): + raise ValueError("UK firm ids repeat.") + return ids.astype(np.int64) + + +def uk_firm_employment_band_index(employment: Any) -> np.ndarray: + """ONS employment band index (0-6, ``UK_FIRM_TURNOVER_EMPLOYMENT_BANDS``).""" + + values = np.asarray(employment, dtype=np.float64) + return np.searchsorted(_EMPLOYMENT_BAND_UPPER_EDGES, values, side="left").astype( + np.int64 + ) + + +def _non_k(sic: np.ndarray) -> np.ndarray: + return ~np.isin(sic.astype(np.int64), SIC_SECTION_K_DIVISIONS) + + +def _bpe_row(source: UKFirmBPESource, key: tuple[str, str], band: str) -> float: + frame = source.size_bands + rows = frame[ + (frame["table"] == key[0]) + & (frame["sector"] == key[1]) + & (frame["size_band"] == band) + ] + if len(rows) != 1: + raise ValueError(f"UK firm BPE {key} {band!r} found {len(rows)}x.") + value = float(rows["turnover_million"].iloc[0]) + if not math.isfinite(value): + raise ValueError(f"UK firm BPE {key} {band!r} turnover is missing.") + return value + + +# -- BPE target ------------------------------------------------------------------ + + +def uk_firm_bpe_turnover_by_band(source: UKFirmBPESource) -> pd.DataFrame: + """BPE registered whole-economy turnover by ONS employment band. + + Columns ``band``, ``bpe_rows`` (the Table 2 employee bands summed), + ``table_2_turnover_million``, ``unregistered_turnover_million`` (Table 1 + unregistered, on 0-4 only), ``bpe_turnover_million`` and ``bpe_share``. + BPE turnover excludes Section K at source. + """ + + unregistered = _bpe_row(source, _BPE_PRIVATE_TABLE_1, _BPE_UNREGISTERED) + rows = [] + for band in UK_FIRM_TURNOVER_EMPLOYMENT_BANDS: + labels = UK_FIRM_BPE_BANDS_BY_ONS_BAND[band] + table_2 = sum(_bpe_row(source, _BPE_WHOLE_ECONOMY, label) for label in labels) + less = unregistered if band == UK_FIRM_TURNOVER_EMPLOYMENT_BANDS[0] else 0.0 + rows.append( + { + "band": band, + "bpe_rows": " + ".join(labels), + "table_2_turnover_million": table_2, + "unregistered_turnover_million": less, + "bpe_turnover_million": table_2 - less, + } + ) + table = pd.DataFrame(rows) + if (table["bpe_turnover_million"] <= 0).any(): + raise ValueError("UK firm BPE registered turnover by band must be positive.") + table["bpe_share"] = ( + table["bpe_turnover_million"] / table["bpe_turnover_million"].sum() + ) + return table + + +def _target_shares(source: UKFirmBPESource | Sequence[float]) -> np.ndarray: + if isinstance(source, UKFirmBPESource): + return uk_firm_bpe_turnover_by_band(source)["bpe_share"].to_numpy(np.float64) + shares = np.asarray(source, dtype=np.float64) + if shares.shape != (len(UK_FIRM_TURNOVER_EMPLOYMENT_BANDS),) or not ( + np.all(shares >= 0) and shares.sum() > 0 + ): + raise ValueError("Target shares must be seven non-negative band values.") + return shares / shares.sum() + + +# -- A. re-pairing --------------------------------------------------------------- + + +class _Pairing: + """Per-division turnover scores, noise and sorted employment, precomputed.""" + + def __init__( + self, + sic: Any, + turnover: Any, + employment: Any, + in_frame: Any, + seed: int, + firm_ids: Any, + ) -> None: + self.employment = _array(employment, "employment") + n = len(self.employment) + sic_codes = _array(sic, "sic", n).astype(np.int64) + values = _array(turnover, "turnover", n).astype(np.float64) + frame = _array(in_frame, "in_frame", n).astype(bool) + ids = _firm_ids(firm_ids, n) + rows = np.flatnonzero(frame) + # Frame rows ordered by (division, firm id): fixes segments and ties. + order = rows[np.lexsort((ids[rows], sic_codes[rows]))] + division = sic_codes[order] + noise = np.empty(n, dtype=np.float64) + by_id = rows[np.argsort(ids[rows], kind="stable")] + rng = np.random.default_rng( + np.random.SeedSequence([int(seed), _REPAIR_SEED_TAG]) + ) + noise[by_id] = rng.standard_normal(by_id.size) + starts = np.searchsorted(division, division, side="left") + sizes = np.searchsorted(division, division, side="right") - starts + by_turnover = np.lexsort((ids[order], values[order], division)) + rank = np.empty(order.size, dtype=np.float64) + rank[by_turnover] = np.arange(order.size) - starts[by_turnover] + self.n = n + self.order = order + self.division = division + self.ids = ids[order] + self.score = ndtri((rank + 0.5) / np.maximum(sizes, 1)) + self.noise = noise[order] + self.sorted_employment = self.employment[order][ + np.lexsort((self.employment[order], division)) + ] + + def repaired(self, rho: float) -> np.ndarray: + rho = float(rho) + if not 0.0 <= rho <= 1.0: + raise ValueError(f"rho must lie in [0, 1], got {rho}.") + z = rho * self.score + math.sqrt(1.0 - rho * rho) * self.noise + ranked = self.order[np.lexsort((self.ids, z, self.division))] + result = self.employment.copy() + result[ranked] = self.sorted_employment + return result + + +def repair_uk_firm_employment_turnover( + sic: Any, + turnover: Any, + employment: Any, + in_frame: Any, + *, + rho: float, + seed: int, + firm_ids: Any = None, +) -> np.ndarray: + """Employment re-paired with turnover inside each SIC division. + + Returns a copy of ``employment`` (same dtype) in which the ONS-frame rows + of each division hold a permutation of that division's frame values, + ordered by the Gaussian copula score described in the module docstring; + rows with ``in_frame`` False keep their value. ``firm_ids`` (integers, + unique; row position when omitted) key the noise and break ties, so the + result per firm does not depend on row order. + """ + + return _Pairing(sic, turnover, employment, in_frame, seed, firm_ids).repaired(rho) + + +# -- B. rho fit ------------------------------------------------------------------ + + +def _band_turnover( + employment: np.ndarray, + turnover: np.ndarray, + weights: np.ndarray, + mask: np.ndarray, +) -> np.ndarray: + bands = uk_firm_employment_band_index(employment[mask]) + return np.bincount( + bands, + weights=turnover[mask] * weights[mask], + minlength=len(UK_FIRM_TURNOVER_EMPLOYMENT_BANDS), + ) + + +@dataclass(frozen=True) +class UKFirmRhoFit: + """The fitted copula ``rho`` and how it was found. + + ``table`` is the per-band fit (model turnover and shares before + re-pairing, at ``rho``, and the target); ``search`` every ``rho`` + evaluated with its squared error. ``at_bound`` is True when the optimum + is an end of [0, ``RHO_UPPER``]. + """ + + rho: float + sse: float + at_bound: bool + table: pd.DataFrame + search: pd.DataFrame + + +def fit_uk_firm_employment_turnover_rho( + sic: Any, + turnover: Any, + employment: Any, + in_frame: Any, + base_weights: Any, + source: UKFirmBPESource | Sequence[float], + *, + seed: int, + firm_ids: Any = None, +) -> UKFirmRhoFit: + """Fit ``rho`` to BPE turnover shares by ONS employment band. + + Shares are base-weighted turnover over ONS-frame rows outside Section K + (divisions 64-66), by the band of the re-paired employment. ``source`` is + the BPE tables (target from :func:`uk_firm_bpe_turnover_by_band`) or + seven target values in band order. The search is a 0.05 grid on + [0, 0.99] (0.99 included), then a 0.005 grid within 0.05 of the coarse + best; ties go to the smaller ``rho``. ``seed`` and ``firm_ids`` must be + those later passed to :func:`repair_uk_firm_employment_turnover`. + """ + + pairing = _Pairing(sic, turnover, employment, in_frame, seed, firm_ids) + n = pairing.n + values = _array(turnover, "turnover", n).astype(np.float64) + weights = _array(base_weights, "base_weights", n).astype(np.float64) + mask = _array(in_frame, "in_frame", n).astype(bool) & _non_k(_array(sic, "sic", n)) + if not mask.any(): + raise ValueError("rho fit needs ONS-frame rows outside Section K.") + target = _target_shares(source) + + evaluated: dict[float, tuple[float, np.ndarray]] = {} + + def evaluate(rho: float) -> float: + rho = round(float(rho), 6) + if rho not in evaluated: + totals = _band_turnover(pairing.repaired(rho), values, weights, mask) + shares = totals / totals.sum() + evaluated[rho] = (float(((shares - target) ** 2).sum()), totals) + return evaluated[rho][0] + + coarse = np.append(np.arange(0.0, RHO_UPPER, _RHO_COARSE_STEP), RHO_UPPER) + best = min(coarse, key=lambda rho: (evaluate(rho), rho)) + fine = np.arange( + max(0.0, best - _RHO_COARSE_STEP), + min(RHO_UPPER, best + _RHO_COARSE_STEP) + _RHO_FINE_STEP / 2, + _RHO_FINE_STEP, + ) + fine = np.clip(fine, 0.0, RHO_UPPER) + best = min([*fine, best], key=lambda rho: (evaluate(rho), round(float(rho), 6))) + rho = round(float(best), 6) + sse, fitted = evaluated[rho] + before = _band_turnover(pairing.employment, values, weights, mask) + table = pd.DataFrame( + { + "band": UK_FIRM_TURNOVER_EMPLOYMENT_BANDS, + "model_turnover_k_before": before, + "model_share_before": before / before.sum(), + "model_turnover_k_fitted": fitted, + "model_share_fitted": fitted / fitted.sum(), + "target_share": target, + } + ) + search = pd.DataFrame( + sorted((r, s) for r, (s, _) in evaluated.items()), columns=["rho", "sse"] + ) + return UKFirmRhoFit( + rho=rho, + sse=sse, + at_bound=rho in (0.0, RHO_UPPER), + table=table, + search=search, + ) + + +# -- C. open-band tail ----------------------------------------------------------- + + +def _truncated_pareto_mean(alpha: float, lower: float, cap: float) -> float: + tail = (lower / cap) ** alpha + if abs(alpha - 1.0) < 1e-9: + return lower * math.log(cap / lower) / (1.0 - tail) + return ( + alpha + * lower**alpha + * (cap ** (1.0 - alpha) - lower ** (1.0 - alpha)) + / ((1.0 - alpha) * (1.0 - tail)) + ) + + +def truncated_pareto_exceedance( + threshold: float, alpha: float, lower: float, cap: float +) -> float: + """``P(X > threshold)`` for the Pareto(``alpha``) on [``lower``, ``cap``].""" + + if threshold <= lower: + return 1.0 + if threshold >= cap: + return 0.0 + tail = (lower / cap) ** alpha + return ((lower / threshold) ** alpha - tail) / (1.0 - tail) + + +def _slice_means(n: int, alpha: float, lower: float, cap: float) -> np.ndarray: + """Means of the truncated Pareto over the quantile slices [k/n, (k+1)/n].""" + + if n == 0: + return np.empty(0, dtype=np.float64) + span = 1.0 - (lower / cap) ** alpha + exponent = 1.0 - 1.0 / alpha + cumulative = np.arange(n + 1, dtype=np.float64) / n + edges = 1.0 - cumulative * span + if abs(exponent) < 1e-12: + integral = np.log(edges) / span + else: + integral = edges**exponent / (exponent * span) + means = lower * (integral[:-1] - integral[1:]) * n + return np.clip(means, lower, cap) + + +def uk_firm_open_band_uniforms( + turnover_k: Any, + lower_k: float = OPEN_BAND_LOWER_K, + upper_k: float = OPEN_BAND_LOG_UNIFORM_UPPER_K, +) -> np.ndarray: + """The uniforms behind the generator's log-uniform open-band draws.""" + + values = np.asarray(turnover_k, dtype=np.float64) + unit = np.log(values / lower_k) / math.log(upper_k / lower_k) + return np.clip(unit, 0.0, 1.0) + + +def draw_uk_firm_open_band_turnover( + uniforms: Any, + alpha: float, + cap_k: float, + lower_k: float = OPEN_BAND_LOWER_K, + *, + strata: Any = None, +) -> np.ndarray: + """Open-band turnover (£k) from the generator's uniforms. + + Within each stratum (all rows when ``strata`` is None) the rows are + ranked by ``uniforms`` (ties by position) and the row of rank k among n + takes the mean of the truncated Pareto(``alpha``) on [``lower_k``, + ``cap_k``] over the quantile slice [k/n, (k+1)/n]. Values lie in + [``lower_k``, ``cap_k``], their mean is the distribution's mean, and no + random number is drawn: only the ranks of ``uniforms`` matter. + """ + + unit = _array(uniforms, "uniforms").astype(np.float64) + if not np.all(np.isfinite(unit)): + raise ValueError("Open-band uniforms must be finite.") + if not (alpha > 0 and cap_k > lower_k > 0): + raise ValueError("Open-band tail needs alpha > 0 and cap > lower > 0.") + groups = np.zeros(unit.size, dtype=np.int64) + if strata is not None: + groups = np.unique(_array(strata, "strata", unit.size), return_inverse=True)[ + 1 + ].reshape(-1) + result = np.empty(unit.size, dtype=np.float64) + order = np.lexsort((np.arange(unit.size), unit, groups)) + sorted_groups = groups[order] + bounds = np.flatnonzero(np.diff(sorted_groups)) + 1 + for rows in np.split(order, bounds): + result[rows] = _slice_means(rows.size, float(alpha), float(lower_k), cap_k) + return result + + +@dataclass(frozen=True) +class UKFirmOpenBandTail: + """Open-band truncated Pareto parameters and the inputs behind them. + + Turnover in £ thousands, firm counts weighted. ``p_over_10m`` is HMRC's + count over ONS's; ``model_p_over_10m`` the truncated Pareto's + ``P(> £10m)`` at (``alpha``, ``cap_k``). + """ + + alpha: float + cap_k: float + lower_k: float + target_mean_k: float + p_over_10m: float + model_p_over_10m: float + hmrc_over_10m_traders: float + ons_open_band_enterprises: float + bpe_whole_economy_turnover_k: float + bpe_unregistered_turnover_k: float + closed_band_turnover_non_k_k: float + open_band_firms_non_k: float + + def as_dict(self) -> dict[str, float]: + return {name: float(getattr(self, name)) for name in self.__dataclass_fields__} + + +def _ons_open_band_enterprises(ons_turnover: pd.DataFrame) -> float: + if ONS_OPEN_TURNOVER_BAND_LABEL not in ons_turnover.columns: + raise ValueError("ONS turnover table has no 5000+ column.") + sic = ons_turnover["SIC Code"] + rows = ons_turnover[sic.notna() & ~sic.astype(str).isin(["", "Total"])] + return float(rows[ONS_OPEN_TURNOVER_BAND_LABEL].fillna(0).sum()) + + +def uk_firm_open_band_tail_parameters( + ons_turnover: pd.DataFrame, + hmrc_bands: Mapping[str, float], + source: UKFirmBPESource, + *, + sic: Any, + turnover_k: Any, + in_frame: Any, + open_band: Any, + weights: Any = None, +) -> UKFirmOpenBandTail: + """Shape, cap and target mean of the open-band truncated Pareto. + + ``ons_turnover`` is the generator's ONS SIC-by-turnover-band table and + ``hmrc_bands`` its HMRC registered traders by band for the build's + vintage. ``sic``, ``turnover_k``, ``in_frame``, ``open_band`` and + ``weights`` (one when omitted) describe the drawn rows; the closed-band + turnover is that of frame rows outside the open band and Section K. + Raises ``ValueError`` when the target mean cannot be reached by a cap. + """ + + n = len(_array(turnover_k, "turnover_k")) + sic_codes = _array(sic, "sic", n) + values = _array(turnover_k, "turnover_k", n).astype(np.float64) + frame = _array(in_frame, "in_frame", n).astype(bool) + open_rows = _array(open_band, "open_band", n).astype(bool) + mass = ( + np.ones(n, dtype=np.float64) + if weights is None + else _array(weights, "weights", n).astype(np.float64) + ) + non_k = frame & _non_k(sic_codes) + closed = float((values * mass)[non_k & ~open_rows].sum()) + open_firms = float(mass[non_k & open_rows].sum()) + if not open_firms > 0: + raise ValueError("No weighted non-Section-K open-band rows.") + + hmrc_top = float(hmrc_bands[HMRC_TOP_TURNOVER_BAND]) + ons_open = _ons_open_band_enterprises(ons_turnover) + p = hmrc_top / ons_open + if not 0.0 < p < 1.0: + raise ValueError(f"P(turnover > 10m | open band) = {p} is not in (0, 1).") + lower = OPEN_BAND_LOWER_K + alpha = -math.log(p) / math.log(HMRC_TOP_BAND_LOWER_K / lower) + + whole = _bpe_row(source, _BPE_WHOLE_ECONOMY, _BPE_ALL) * 1_000.0 + unregistered = _bpe_row(source, _BPE_PRIVATE_TABLE_1, _BPE_UNREGISTERED) * 1_000.0 + target = (whole - unregistered - closed) / open_firms + if not target > lower: + raise ValueError(f"Open-band target mean {target:,.1f}k is not above {lower}.") + if alpha > 1.0 and target >= lower * alpha / (alpha - 1.0): + raise ValueError( + f"Open-band target mean {target:,.1f}k is beyond any cap at alpha " + f"{alpha:.4f}." + ) + log_cap = brentq( + lambda x: _truncated_pareto_mean(alpha, lower, lower * math.exp(x)) - target, + 1e-9, + 200.0, + xtol=1e-14, + rtol=1e-15, + maxiter=500, + ) + cap = lower * math.exp(log_cap) + return UKFirmOpenBandTail( + alpha=alpha, + cap_k=cap, + lower_k=lower, + target_mean_k=target, + p_over_10m=p, + model_p_over_10m=truncated_pareto_exceedance( + HMRC_TOP_BAND_LOWER_K, alpha, lower, cap + ), + hmrc_over_10m_traders=hmrc_top, + ons_open_band_enterprises=ons_open, + bpe_whole_economy_turnover_k=whole, + bpe_unregistered_turnover_k=unregistered, + closed_band_turnover_non_k_k=closed, + open_band_firms_non_k=open_firms, + ) + + +# -- D. diagnostics -------------------------------------------------------------- + + +def uk_firm_turnover_by_employment_band( + sic: Any, + turnover_k: Any, + employment: Any, + in_frame: Any, + weights: Any, + source: UKFirmBPESource, +) -> pd.DataFrame: + """Model turnover by ONS employment band against BPE, Section K excluded. + + ``weights`` may be base weights (before the solve) or calibrated weights. + Columns ``band``, ``model_firms``, ``model_turnover_million``, + ``model_share``, ``bpe_turnover_million``, ``bpe_share``, ``share_gap``. + """ + + n = len(_array(turnover_k, "turnover_k")) + values = _array(turnover_k, "turnover_k", n).astype(np.float64) + staff = _array(employment, "employment", n) + mass = _array(weights, "weights", n).astype(np.float64) + mask = _array(in_frame, "in_frame", n).astype(bool) & _non_k(_array(sic, "sic", n)) + totals = _band_turnover(staff, values, mass, mask) / 1_000.0 + firms = np.bincount( + uk_firm_employment_band_index(staff[mask]), + weights=mass[mask], + minlength=len(UK_FIRM_TURNOVER_EMPLOYMENT_BANDS), + ) + bpe = uk_firm_bpe_turnover_by_band(source) + table = pd.DataFrame( + { + "band": UK_FIRM_TURNOVER_EMPLOYMENT_BANDS, + "model_firms": firms, + "model_turnover_million": totals, + "model_share": totals / totals.sum() if totals.sum() > 0 else 0.0, + "bpe_turnover_million": bpe["bpe_turnover_million"].to_numpy(), + "bpe_share": bpe["bpe_share"].to_numpy(), + } + ) + table["share_gap"] = table["model_share"] - table["bpe_share"] + return table + + +def uk_firm_bpe_turnover_pins( + source: UKFirmBPESource, + ons_turnover: pd.DataFrame, + hmrc_bands: Mapping[str, float], +) -> dict[str, dict[str, Any]]: + """Every source number this module reads, with its unit and source.""" + + bpe = "DBT Business population estimates 2025, detailed tables" + pins: dict[str, dict[str, Any]] = { + "bpe_whole_economy_turnover": { + "value": _bpe_row(source, _BPE_WHOLE_ECONOMY, _BPE_ALL), + "unit": "£ million", + "source": f"{bpe}, Table 2, whole economy, All (excludes Section K)", + }, + "bpe_unregistered_turnover": { + "value": _bpe_row(source, _BPE_PRIVATE_TABLE_1, _BPE_UNREGISTERED), + "unit": "£ million", + "source": f"{bpe}, Table 1, private sector, {_BPE_UNREGISTERED}", + }, + "hmrc_over_10m_traders": { + "value": float(hmrc_bands[HMRC_TOP_TURNOVER_BAND]), + "unit": "VAT registered traders", + "source": f"HMRC VAT population by turnover band, {HMRC_TOP_TURNOVER_BAND}", + }, + "ons_open_band_enterprises": { + "value": _ons_open_band_enterprises(ons_turnover), + "unit": "enterprises", + "source": "ONS UK business: activity, size and location, turnover " + "band 5000+, sum over SIC divisions", + }, + } + for row in uk_firm_bpe_turnover_by_band(source).itertuples(): + pins[f"bpe_registered_turnover_{row.band}"] = { + "value": float(row.bpe_turnover_million), + "unit": "£ million", + "source": f"{bpe}, Table 2 whole economy ({row.bpe_rows})" + + ( + ", less Table 1 unregistered" + if row.unregistered_turnover_million + else "" + ), + } + return pins 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..0ba1808a11 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_build.py @@ -0,0 +1,919 @@ +"""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. with a ``paybill_dir``, ``assign_uk_firm_paybill`` sets ``firm_paybill`` + to employees times the ONS ASHE section mean annual gross pay; + with ``employment_allowance``, ``assign_uk_firm_employment_allowance`` + sets the assumed Employment Allowance flags; +5. ``to_policyengine_uk_firm_table`` exports policyengine-uk firm columns; +6. ``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; with a ``paybill_dir``, also the paybill CSV's +hash (``inputs.paybill``), the paybill fallback counts, the weighted +paybill, its in-frame split (``uk_firm_paybill_in_frame``) and its status +(``uk_firm_paybill``). Without one, the receipt has no paybill key at all. +With ``employment_allowance``, it also holds the flags' status, method and +weighted counts of firms where each flag is true (``uk_firm_employment_allowance``). +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_consumption import ( + UK_FIRM_CONSUMPTION_COLUMNS, + UK_FIRM_CONSUMPTION_METHOD, + UK_FIRM_CONSUMPTION_STATUS, + check_uk_table3_consumer_trends, + read_uk_firm_supply_use_source, + uk_firm_consumption_sales, + uk_firm_division_coicop_shares, + uk_firm_household_sales_by_coicop, + uk_household_purchases_supply_decomposition, +) +from microcosm.build.uk_runtime.firm_employment_allowance import ( + UK_FIRM_EMPLOYMENT_ALLOWANCE_COLUMNS, + UK_FIRM_EMPLOYMENT_ALLOWANCE_METHOD, + UK_FIRM_EMPLOYMENT_ALLOWANCE_STATUS, + assign_uk_firm_employment_allowance, +) +from microcosm.build.uk_runtime.firm_employment_allowance_takeup import ( + UK_FIRM_EA_TAKEUP_METHOD, + UK_FIRM_EA_TAKEUP_STATUS, + assign_uk_firm_employment_allowance_takeup, + read_uk_firm_employment_allowance_takeup, + uk_firm_employment_allowance_takeup_held_out, +) +from microcosm.build.uk_runtime.firm_generation import ( + UKFirmGenerationConfig, + generate_uk_firm_population, + read_uk_firm_source_data, +) +from microcosm.build.uk_runtime.firm_headcount import ( + UK_FIRM_HEADCOUNT_METHOD, + UK_FIRM_HEADCOUNT_STATUS, + UK_FIRM_LARGE_HEADCOUNT_METHOD, + UK_FIRM_MID_HEADCOUNT_METHOD, + read_uk_firm_bpe_source, + redraw_uk_firm_small_headcount, + remap_uk_firm_large_headcount, + remap_uk_firm_mid_headcount, + uk_firm_bpe_size_band_reconciliation, + uk_firm_employees, + uk_firm_small_headcount_diagnostics, +) +from microcosm.build.uk_runtime.firm_pay_distribution import ( + UK_FIRM_PAY_DISTRIBUTION_METHOD, + UK_FIRM_PAY_DISTRIBUTION_STATUS, + assign_uk_firm_pay_below_secondary_threshold, + read_uk_firm_pay_distribution_source, +) +from microcosm.build.uk_runtime.firm_paybill import ( + UK_FIRM_PAYBILL_METHOD, + UK_FIRM_PAYBILL_STATUS, + UK_FIRM_PAYBILL_TAX_YEAR, + assign_uk_firm_paybill, + read_uk_firm_paybill_source, + uk_firm_paybill_fallback_counts, +) +from microcosm.build.uk_runtime.firm_paybill_anchor import ( + read_uk_firm_paybill_anchors, + uk_firm_paybill_anchor_ratios, +) +from microcosm.build.uk_runtime.firm_profit import ( + UK_FIRM_PROFIT_METHOD, + UK_FIRM_PROFIT_STATUS, + assign_uk_firm_taxable_profit, + read_uk_firm_profit_source, + uk_firm_profit_diagnostics, +) +from microcosm.build.uk_runtime.firm_public_sector import ( + UK_FIRM_PUBLIC_SECTOR_STATUS, + read_uk_firm_public_sector_source, + scale_uk_firm_public_sector_employment, + uk_firm_public_sector_diagnostics, +) +from microcosm.build.uk_runtime.firm_rateable_value import ( + UK_FIRM_RATEABLE_VALUE_METHOD, + UK_FIRM_RATEABLE_VALUE_STATUS, + assign_uk_firm_rateable_value, + read_uk_firm_rateable_value_source, +) +from microcosm.build.uk_runtime.firm_rd_tax_credits import ( + UK_FIRM_RD_METHOD, + UK_FIRM_RD_STATUS, + draw_uk_firm_rd_tax_credits, + read_uk_firm_rd_source, +) +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 ( + UK_FIRM_EA_RULE_CLAIMS_COLUMN, + UK_FIRM_ENGLISH_REGION_CODES, + to_policyengine_uk_firm_table, + uk_firm_sic_sections, + validate_uk_firm_table, +) +from microcosm.build.uk_runtime.firm_vat_composition import ( + UK_FIRM_VAT_COMPOSITION_STATUS, + add_uk_firm_vat_composition_columns, + read_uk_firm_vat_composition_source, + uk_firm_vat_relief_checks, + uk_firm_vat_section_shares, +) + +#: policyengine-uk's 2024-25 annual secondary threshold: £175 a week +#: (``gov.hmrc.national_insurance.class_1.employer_scale``, bracket 1) times +#: 52. +UK_FIRM_SECONDARY_THRESHOLD_GBP = 175.0 * 52 + +#: 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" +#: With consumption_dir: the SIC division x COICOP division shares of +#: household sales, written beside the table for the consumption match. +UK_FIRM_DIVISION_COICOP_SHARES_FILE = "uk_firm_division_coicop_shares.csv" + +#: 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)", + # ONS ASHE 2025 Table 4.7a: the tax year ending 5 April 2025. + "ashe_paybill": "2024-25", + "ashe_pay_distribution": "2024-25", + # ONS public sector employment, headcount at March 2025. + "ons_public_sector_employment": "Mar 2025", + # DBT Business Population Estimates 2025: start of 2025. + "dbt_bpe": "start of 2025", + # HMRC Employment Allowance take-up statistics, tax year 2024-25. + "hmrc_employment_allowance_takeup": "2024-25", + # HMRC Corporation Tax statistics 2026, Tables 9A/9B: FY 2024-25. + "hmrc_ct_statistics": "2024-25", + # HMRC R&D Tax Credits statistics, September 2026: 2024-25 provisional. + "hmrc_rd_statistics": "2024-25", + # VOA non-domestic rating stock at 31 March 2026, 2023 rating lists. + "voa_rating_list": "31 Mar 2026 (2023 list)", + # ONS Supply and Use Tables, Blue Book 2026: calendar year 2024. + "ons_supply_use": "2024", + # ONS Annual Business Survey 2024 results (VAT composition, section G). + "ons_abs": "2024", + # ONS D.11 wages and salaries, calendar 2024; PAYE RTI, 2024-25. + "paybill_anchor": "2024 (D.11); 2024-25 (PAYE RTI)", + } +) + + +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, + paybill_dir: str | Path | None = None, + employment_allowance: bool = False, + public_sector_dir: str | Path | None = None, + profit_dir: str | Path | None = None, + rateable_value_dir: str | Path | None = None, + pay_distribution_dir: str | Path | None = None, + bpe_dir: str | Path | None = None, + employment_allowance_takeup_dir: str | Path | None = None, + consumption_dir: str | Path | None = None, + vat_composition_dir: str | Path | None = None, + paybill_anchor_dir: str | Path | None = None, + bpe_mid_headcount: bool = False, + out_of_frame_no_employees: bool = False, + bpe_turnover: bool = False, + bpe_large_headcount: bool = False, + rd_tax_credits_dir: str | Path | None = None, +) -> 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``. ``paybill_dir``, when + given, holds the ONS ASHE section pay CSV + (``tests/fixtures/uk/firm_paybill_2024``) and adds ``firm_paybill`` to + the table; without it the table and receipt are as before. The paybill + table is for tax year ``UK_FIRM_PAYBILL_TAX_YEAR``; a ``paybill_dir`` + with any other ``config.data_vintage`` raises ``ValueError``. + ``employment_allowance`` adds the assumed Employment Allowance flags + (``firm_employment_allowance.py``); they read no random numbers. + ``public_sector_dir`` (``tests/fixtures/uk/firm_public_sector_2025``) + scales the headcount of central government and local authority rows to + ONS public sector employment before the paybill is set; + ``profit_dir`` (``tests/fixtures/uk/firm_ct_2024``) adds the assumed + ``firm_taxable_trading_profit``; ``rateable_value_dir`` + (``tests/fixtures/uk/firm_rateable_value_2024``) the assumed + ``firm_rateable_value``. Each is opt-in, reads its own fixed-seed + generator if any, and leaves the table and receipt unchanged when + omitted. ``pay_distribution_dir`` + (``tests/fixtures/uk/firm_pay_distribution_2024``), which needs a + ``paybill_dir``, adds the assumed count and pay of employees at or below + the secondary threshold (``UK_FIRM_SECONDARY_THRESHOLD_GBP``). + ``bpe_dir`` (``tests/fixtures/uk/firm_bpe_2025``), which needs a + ``paybill_dir``, redraws headcount inside the ONS 0-4 employment band by + legal status from DBT Business Population Estimates 2025 Table 3 + (``firm_headcount.py``) before the public sector rescale, and switches on + the labour link group: ``firm_employees`` becomes employment less the + assumed working proprietors, and the paybill and pay split are set on + employees. ``employment_allowance_takeup_dir`` + (``tests/fixtures/uk/firm_employment_allowance_takeup_2024_25``), which + needs ``bpe_dir`` and ``employment_allowance``, draws each rule claimant's + claim at HMRC's 2024-25 take-up by employee size band + (``firm_employment_allowance_takeup.py``). ``consumption_dir`` + (``tests/fixtures/uk/firm_supply_use_2024``) splits turnover into + household, intermediate and other final sales by SIC division from the + ONS Supply and Use Tables 2024 (``firm_consumption.py``). + ``bpe_mid_headcount`` (needs ``bpe_dir``) remaps headcount inside the + ONS bands 5-9 to 100-249 to BPE 2025 Table 1 shapes by weighted rank; + ``out_of_frame_no_employees`` (needs ``bpe_dir``) gives the rows outside + the ONS frame no headcount, an assumption with no published pin. + ``bpe_turnover`` (needs ``bpe_dir``) runs the generator with the BPE + turnover fix (``UKFirmGenerationConfig.bpe_turnover``): an open-band + turnover tail pinned to BPE 2025 and employment re-paired with turnover. + ``bpe_large_headcount`` (needs ``bpe_dir``) remaps 250+ headcounts to + BPE 2025 Table 1's large rows. ``rd_tax_credits_dir`` + (``tests/fixtures/uk/firm_rd_tax_credits_2024_25``) adds the assumed + ``firm_qualifying_rd_expenditure`` and ``firm_is_sme`` from HMRC R&D tax + credit statistics (``firm_rd_tax_credits.py``). + 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." + ) + if paybill_dir is not None and config.data_vintage != UK_FIRM_PAYBILL_TAX_YEAR: + raise ValueError( + f"The UK firm paybill table is for tax year {UK_FIRM_PAYBILL_TAX_YEAR}; " + f"config.data_vintage is {config.data_vintage}." + ) + for name, directory in ( + ("public_sector_dir", public_sector_dir), + ("profit_dir", profit_dir), + ("rateable_value_dir", rateable_value_dir), + ("pay_distribution_dir", pay_distribution_dir), + ("bpe_dir", bpe_dir), + ("employment_allowance_takeup_dir", employment_allowance_takeup_dir), + ("consumption_dir", consumption_dir), + ("vat_composition_dir", vat_composition_dir), + ("paybill_anchor_dir", paybill_anchor_dir), + ("rd_tax_credits_dir", rd_tax_credits_dir), + ): + if directory is not None and config.data_vintage != "2024-25": + raise ValueError( + f"The UK firm {name} source is for tax year 2024-25; " + f"config.data_vintage is {config.data_vintage}." + ) + if pay_distribution_dir is not None and paybill_dir is None: + raise ValueError("pay_distribution_dir needs paybill_dir.") + if vat_composition_dir is not None and consumption_dir is None: + raise ValueError("vat_composition_dir needs consumption_dir.") + if paybill_anchor_dir is not None and paybill_dir is None: + raise ValueError("paybill_anchor_dir needs paybill_dir.") + if bpe_dir is not None and paybill_dir is None: + raise ValueError("bpe_dir needs paybill_dir.") + if ( + bpe_mid_headcount + or out_of_frame_no_employees + or bpe_turnover + or bpe_large_headcount + ) and bpe_dir is None: + raise ValueError( + "bpe_mid_headcount, out_of_frame_no_employees, bpe_turnover and " + "bpe_large_headcount need bpe_dir." + ) + if employment_allowance_takeup_dir is not None and ( + bpe_dir is None or not employment_allowance + ): + raise ValueError( + "employment_allowance_takeup_dir needs bpe_dir and employment_allowance." + ) + processed = Path(processed_dir) + attributes = Path(attributes_dir) + output = Path(output_dir) + + recorder = _RecordingRules(rules) + run_config = dataclasses.replace(config, firm_rules=recorder) + if bpe_turnover: + run_config = dataclasses.replace( + run_config, bpe_turnover=read_uk_firm_bpe_source(bpe_dir) + ) + 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 + ) + bpe_source = None + headcount = None + if bpe_dir is not None: + bpe_source = read_uk_firm_bpe_source(bpe_dir) + redrawn = redraw_uk_firm_small_headcount( + firms, bpe_source, seed=result.config.seed + ) + headcount = uk_firm_small_headcount_diagnostics(firms, redrawn, bpe_source) + firms = redrawn + out_of_frame_employment = None + if out_of_frame_no_employees: + outside = ~firms["in_frame"].to_numpy(bool) + out_of_frame_employment = float( + (firms["firm_weight"].to_numpy(np.float64) * firms["employment"])[ + outside + ].sum() + ) + employment = firms["employment"].to_numpy().copy() + employment[outside] = 0 + firms = firms.assign(employment=employment) + mid_headcount = None + if bpe_mid_headcount: + remapped = remap_uk_firm_mid_headcount( + firms, bpe_source, seed=result.config.seed + ) + mid_headcount = _mid_headcount_record(firms, remapped) + firms = remapped + large_headcount = None + if bpe_large_headcount: + remapped = remap_uk_firm_large_headcount( + firms, bpe_source, seed=result.config.seed + ) + large_headcount = _mid_headcount_record(firms, remapped) + large_headcount["method"] = UK_FIRM_LARGE_HEADCOUNT_METHOD + firms = remapped + public_sector = None + if public_sector_dir is not None: + public_sector_source = read_uk_firm_public_sector_source(public_sector_dir) + public_sector = uk_firm_public_sector_diagnostics(firms, public_sector_source) + firms = scale_uk_firm_public_sector_employment(firms, public_sector_source) + # The rows the paybill and pay split read: with bpe_dir their headcount + # is employees (employment less the assumed working proprietors). + pay_rows = firms + if bpe_source is not None: + firms = firms.assign( + employees=uk_firm_employees( + firms["ons_legal_status"].to_numpy(), firms["employment"].to_numpy() + ) + ) + pay_rows = firms.assign(employment=firms["employees"]) + paybill_source = None + if paybill_dir is not None: + paybill_source = read_uk_firm_paybill_source(paybill_dir) + firms = firms.assign( + firm_paybill=assign_uk_firm_paybill(pay_rows, paybill_source) + ) + pay_distribution_source = None + if pay_distribution_dir is not None: + pay_distribution_source = read_uk_firm_pay_distribution_source( + pay_distribution_dir + ) + firms = firms.assign( + **assign_uk_firm_pay_below_secondary_threshold( + pay_rows.assign(firm_paybill=firms["firm_paybill"]), + pay_distribution_source, + threshold_gbp=UK_FIRM_SECONDARY_THRESHOLD_GBP, + ) + ) + if employment_allowance: + firms = assign_uk_firm_employment_allowance(firms) + profit_source = None + if profit_dir is not None: + profit_source = read_uk_firm_profit_source(profit_dir) + firms = firms.assign( + firm_taxable_trading_profit=assign_uk_firm_taxable_profit( + firms, profit_source + ) + ) + rd_source = None + rd_draw = None + if rd_tax_credits_dir is not None: + rd_source = read_uk_firm_rd_source(rd_tax_credits_dir) + rd_draw = draw_uk_firm_rd_tax_credits(firms, rd_source, seed=result.config.seed) + firms = firms.assign( + firm_qualifying_rd_expenditure=rd_draw.qualifying_rd_expenditure, + firm_is_sme=rd_draw.is_sme, + ) + rateable_value_source = None + if rateable_value_dir is not None: + rateable_value_source = read_uk_firm_rateable_value_source(rateable_value_dir) + in_england = firms.assign( + firm_in_england=firms["ons_region_code"].isin( + list(UK_FIRM_ENGLISH_REGION_CODES) + ) + ) + firms = firms.assign( + firm_rateable_value=assign_uk_firm_rateable_value( + in_england, rateable_value_source + ) + ) + if bpe_source is not None or consumption_dir is not None: + firms = firms.assign( + firm_sic_division=pd.to_numeric(firms["sic_code"]) + .to_numpy() + .astype(np.int64) + ) + consumption_source = None + consumption = None + consumption_check = None + if consumption_dir is not None: + consumption_source = read_uk_firm_supply_use_source(consumption_dir) + # Source consistency (Table 3 totals equal Consumer Trends), checked + # before anything is written. + consumption_check = check_uk_table3_consumer_trends(consumption_source) + consumption = uk_firm_consumption_sales( + firms["sic_code"].to_numpy(), + firms["annual_turnover_k"].to_numpy(np.float64) * 1_000.0, + consumption_source, + ) + firms = firms.assign( + **{ + column: consumption.columns[column].to_numpy(np.float64) + for column in UK_FIRM_CONSUMPTION_COLUMNS + } + ) + vat_source = None + vat_shares = None + if vat_composition_dir is not None: + vat_source = read_uk_firm_vat_composition_source( + vat_composition_dir, consumption_dir + ) + vat_shares = uk_firm_vat_section_shares(vat_source) + firms = add_uk_firm_vat_composition_columns( + firms.assign(firm_sic_section=uk_firm_sic_sections(firms["sic_code"])), + vat_shares, + ).drop(columns="firm_sic_section") + takeup_source = None + takeup = None + if employment_allowance_takeup_dir is not None: + takeup_source = read_uk_firm_employment_allowance_takeup( + employment_allowance_takeup_dir + ) + rule_table = to_policyengine_uk_firm_table( + firms, threshold_k=float(result.config.vat_threshold) + ) + drawn, takeup_diagnostics = assign_uk_firm_employment_allowance_takeup( + rule_table, takeup_source, seed=result.config.seed + ) + claims = pd.Series( + drawn["firm_claims_employment_allowance"].to_numpy(bool), + index=drawn["firm_id"].to_numpy(), + ) + takeup = { + **takeup_diagnostics, + "held_out": uk_firm_employment_allowance_takeup_held_out( + drawn, + drawn["firm_claims_employment_allowance"].to_numpy(bool), + takeup_source, + ), + } + drawn_claims = claims.reindex(firms["firm_id"].to_numpy()) + if drawn_claims.isna().any(): + raise RuntimeError("The take-up draw missed some UK firm ids.") + firms = firms.assign( + **{ + UK_FIRM_EA_RULE_CLAIMS_COLUMN: firms[ + "firm_claims_employment_allowance" + ].to_numpy(bool), + "firm_claims_employment_allowance": drawn_claims.to_numpy(bool), + } + ) + 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, + "ashe_paybill": paybill_dir is not None, + "ashe_pay_distribution": pay_distribution_dir is not None, + "ons_public_sector_employment": public_sector_dir is not None, + "dbt_bpe": bpe_dir is not None, + "hmrc_employment_allowance_takeup": ( + employment_allowance_takeup_dir is not None + ), + "hmrc_ct_statistics": profit_dir is not None, + "hmrc_rd_statistics": rd_tax_credits_dir is not None, + "voa_rating_list": rateable_value_dir is not None, + "ons_supply_use": consumption_dir is not None, + "ons_abs": vat_composition_dir is not None, + "paybill_anchor": paybill_anchor_dir is not None, + } + ), + }, + "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, + } + if paybill_source is not None: + receipt["inputs"]["paybill"] = {paybill_source.file: paybill_source.sha256} + receipt["output"]["weighted_paybill_gbp"] = float( + (table["firm_weight"] * table["firm_paybill"]).sum() + ) + receipt["uk_firm_paybill_fallback_counts"] = _records( + uk_firm_paybill_fallback_counts(table, paybill_source) + ) + in_frame = table["in_frame"].to_numpy(bool) + weight = table["firm_weight"].to_numpy(np.float64) + receipt["uk_firm_paybill_in_frame"] = [ + { + "in_frame": flag, + "weighted_employees": float( + (weight * table["firm_employees"].to_numpy(np.float64))[ + in_frame == flag + ].sum() + ), + "weighted_paybill_gbp": float( + (weight * table["firm_paybill"].to_numpy(np.float64))[ + in_frame == flag + ].sum() + ), + } + for flag in (True, False) + ] + receipt["uk_firm_paybill"] = { + "status": UK_FIRM_PAYBILL_STATUS, + "method": UK_FIRM_PAYBILL_METHOD, + "tax_year": UK_FIRM_PAYBILL_TAX_YEAR, + } + if employment_allowance: + weight = table["firm_weight"].to_numpy(np.float64) + receipt["uk_firm_employment_allowance"] = { + "status": UK_FIRM_EMPLOYMENT_ALLOWANCE_STATUS, + "method": UK_FIRM_EMPLOYMENT_ALLOWANCE_METHOD, + "weighted_firms_where_true": { + column: float(weight[table[column].to_numpy(bool)].sum()) + for column in UK_FIRM_EMPLOYMENT_ALLOWANCE_COLUMNS + }, + } + weight = table["firm_weight"].to_numpy(np.float64) + if public_sector is not None: + receipt["inputs"]["public_sector"] = { + public_sector_source.file: public_sector_source.sha256 + } + receipt["uk_firm_public_sector"] = { + "status": UK_FIRM_PUBLIC_SECTOR_STATUS, + **public_sector, + } + if pay_distribution_source is not None: + receipt["inputs"]["pay_distribution"] = { + pay_distribution_source.file: pay_distribution_source.sha256 + } + receipt["uk_firm_pay_distribution"] = { + "status": UK_FIRM_PAY_DISTRIBUTION_STATUS, + "method": UK_FIRM_PAY_DISTRIBUTION_METHOD, + "threshold_gbp": UK_FIRM_SECONDARY_THRESHOLD_GBP, + "weighted_employees_below": float( + (weight * table["firm_employees_below_secondary_threshold"]).sum() + ), + "weighted_paybill_below_gbp": float( + (weight * table["firm_paybill_below_secondary_threshold"]).sum() + ), + } + if profit_source is not None: + receipt["inputs"]["profit"] = {profit_source.file: profit_source.sha256} + receipt["uk_firm_profit"] = { + "status": UK_FIRM_PROFIT_STATUS, + "method": UK_FIRM_PROFIT_METHOD, + "weighted_profit_gbp": float( + (weight * table["firm_taxable_trading_profit"]).sum() + ), + "bands": _records(uk_firm_profit_diagnostics(firms, profit_source)), + } + if bpe_source is not None: + receipt["inputs"]["bpe"] = dict(bpe_source.sha256) + receipt["uk_firm_headcount"] = { + "status": UK_FIRM_HEADCOUNT_STATUS, + "method": UK_FIRM_HEADCOUNT_METHOD, + "small_band_redraw": _records(headcount), + # Report-only: paybill over BPE 2025 whole-economy employees times + # ASHE's all-employee mean pay. ASHE annual jobs (the usual + # check's base) cover only jobs held a full year. + "paybill_vs_bpe_employees_x_ashe_mean": float( + (weight * table["firm_paybill"]).sum() + / ( + _bpe_whole_economy_employees(bpe_source) + * paybill_source.all_employees_mean + ) + ), + "weighted_employees": float((weight * table["firm_employees"]).sum()), + "weighted_ons_employment": float((weight * table["ons_employment"]).sum()), + "bpe_reconciliation": _records( + uk_firm_bpe_size_band_reconciliation( + table.assign(employment=table["ons_employment"]), bpe_source + ) + ), + } + if bpe_source is not None: + # Opt-in switches appear only when set. + for key, value in ( + ("mid_band_remap", mid_headcount), + ("large_band_remap", large_headcount), + ("bpe_turnover", result.bpe_turnover), + ("out_of_frame_employment_removed", out_of_frame_employment), + ): + if value is not None: + receipt["uk_firm_headcount"][key] = value + if consumption_source is not None: + receipt["inputs"]["consumption"] = dict(consumption_source.sha256) + receipt["uk_firm_consumption"] = { + "status": UK_FIRM_CONSUMPTION_STATUS, + "method": UK_FIRM_CONSUMPTION_METHOD, + "fallback_counts": dict(consumption.fallback_counts), + "weighted_sales_gbp": { + column: float((weight * table[column]).sum()) + for column in UK_FIRM_CONSUMPTION_COLUMNS + }, + "table3_consumer_trends": _records(consumption_check.reset_index()), + "division_coicop_shares_file": UK_FIRM_DIVISION_COICOP_SHARES_FILE, + # Diagnostic only: Table 2 household purchases split by source + # of supply (pounds million), a supply-proportionality + # assumption, never a target. + "household_purchases_by_supply_gbp_million": { + column: float(value) + for column, value in uk_household_purchases_supply_decomposition( + consumption_source + ) + .sum() + .items() + }, + "household_sales_by_coicop": _records( + uk_firm_household_sales_by_coicop( + table["firm_sic_division"].to_numpy(), + table["firm_household_sales"].to_numpy(np.float64), + weight, + consumption_source, + ).reset_index() + ), + } + if vat_source is not None: + receipt["inputs"]["vat_composition"] = dict(vat_source.sha256) + receipt["uk_firm_vat_composition"] = { + "status": UK_FIRM_VAT_COMPOSITION_STATUS, + "mode": "columns_only", + "method": ( + "SIC section shares of standard-, reduced-, zero-rated and " + "exempt supplies, export share, input VAT rate and input ratio " + "from the ONS Supply and Use Tables 2024 read through the VAT " + "Act 1994 schedules (firm_vat_composition.py); attached as " + "Microcosm-only columns; no policyengine-uk input changes" + ), + "section_shares": _records(vat_shares.reset_index()), + # Checks only: modelled relief bases against HMRC tax relief + # statistics (January 2026) cost / rate; never targets. + "relief_checks": _records( + uk_firm_vat_relief_checks(vat_source) + .rename_axis("relief") + .reset_index() + ), + } + if paybill_anchor_dir is not None: + anchors = read_uk_firm_paybill_anchors(paybill_anchor_dir) + receipt["inputs"]["paybill_anchor"] = {"paybill_anchors.csv": anchors.sha256} + receipt["uk_firm_paybill_anchor"] = uk_firm_paybill_anchor_ratios( + table["firm_paybill"].to_numpy(np.float64), + table["firm_employees"].to_numpy(np.float64), + weight, + anchors, + ) + if takeup_source is not None: + receipt["inputs"]["employment_allowance_takeup"] = dict(takeup_source.sha256) + receipt["uk_firm_employment_allowance_takeup"] = { + "status": UK_FIRM_EA_TAKEUP_STATUS, + "method": UK_FIRM_EA_TAKEUP_METHOD, + **takeup, + } + if rd_source is not None: + receipt["inputs"]["rd_tax_credits"] = dict(rd_source.sha256) + receipt["uk_firm_rd_tax_credits"] = { + "status": UK_FIRM_RD_STATUS, + "method": UK_FIRM_RD_METHOD, + "weighted_expenditure_gbp": float( + (weight * table["firm_qualifying_rd_expenditure"]).sum() + ), + **dict(rd_draw.diagnostics), + } + if rateable_value_source is not None: + receipt["inputs"]["rateable_value"] = { + rateable_value_source.file: rateable_value_source.sha256 + } + receipt["uk_firm_rateable_value"] = { + "status": UK_FIRM_RATEABLE_VALUE_STATUS, + "method": UK_FIRM_RATEABLE_VALUE_METHOD, + "weighted_rateable_value_gbp": float( + (weight * table["firm_rateable_value"]).sum() + ), + } + if consumption_source is not None: + uk_firm_division_coicop_shares(consumption_source).to_csv( + output / UK_FIRM_DIVISION_COICOP_SHARES_FILE, float_format="%.12g" + ) + 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 _bpe_whole_economy_employees(source: Any) -> float: + rows = source.size_bands + row = rows[ + (rows["table"] == "Table 2") + & (rows["sector"] == "whole_economy") + & (rows["size_band"] == "All") + ] + return float(row["employees_thousand"].iloc[0]) * 1_000.0 + + +def _mid_headcount_record(before: pd.DataFrame, after: pd.DataFrame) -> dict[str, Any]: + weight = before["firm_weight"].to_numpy(np.float64) + return { + "method": UK_FIRM_MID_HEADCOUNT_METHOD, + "weighted_employment_before": float( + (weight * before["employment"].to_numpy(np.float64)).sum() + ), + "weighted_employment_after": float( + (weight * after["employment"].to_numpy(np.float64)).sum() + ), + "weighted_rows_changed": float( + weight[ + before["employment"].to_numpy() != after["employment"].to_numpy() + ].sum() + ), + } + + +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 item.name == "bpe_turnover": + # Opt-in: absent from the default receipt; the source's hashes + # stand for it. + if value is None: + continue + value = dict(value.sha256) + 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_consumption.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_consumption.py new file mode 100644 index 0000000000..8d65e794fc --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_consumption.py @@ -0,0 +1,840 @@ +"""UK firm consumption links: who buys each firm's output, from the ONS Supply and Use Tables. + +The columns here let the firm table be matched later to household +consumption (LCFS, COICOP). Each firm's turnover is split into sales to +households, sales to other industries (intermediate consumption) and other +final demand (NPISH, central and local government, gross fixed capital +formation, valuables, changes in inventories and exports) by the shares of +its SIC 2007 division in the ONS *Supply and Use Tables, 1997 - 2024* +(consistent with Blue Book 2026), year 2024. The extracted CSVs sit in +``tests/fixtures/uk/firm_supply_use_2024/`` +(``tools/extract_uk_firm_supply_use_tables.py`` re-creates them). + +The columns are Microcosm-only (not policyengine-uk inputs) and their status +is ``"assumed"``: they are a split by published industry averages, not an +observation of any firm. The assumptions, stated once: + +- **product = industry.** Each CPA product is made by its own SIC division, + so a division's sales mix is the demand mix of its products. The tables + are product-by-product (the 'Combined Use' matrix); secondary production + is ignored. +- **imports used like domestic output.** The demand of a product (at + purchasers' prices, domestic output and imports together) is split in the + same proportions for both, so a division's shares are the product's + demand shares. +- **aggregation by sums.** A division with several products (division 10 + has eight) takes the sum of each demand column over its products divided + by the sum of their total demand, not an average of product shares. A + product that spans several divisions (``CPA_B05 & B06``, ``CPA_B07 & + B08``, ``CPA_C11.01-6 & C12``, ``CPA_F41, F42 & F43``, ``CPA_J59 & J60``, + ``CPA_Q87 & Q88``) counts whole in each, since the tables give no split. +- **purchasers' prices.** Demand is valued at purchasers' prices, so trade + margins and product taxes on a good count in its maker's household share, + which leans high for goods sold mostly to households through retail + (division 14, clothing, is about 0.84). +- **denominator = total demand** (intermediate consumption + total final + demand = total supply at purchasers' prices). Household demand is Table + 2's national-concept households column. A negative demand component (a + drawdown of inventories) is floored at zero in numerator and denominator + alike, so shares stay in [0, 1]. Changes in inventories are negative on + 32 of the 103 products (6,275 million pounds in all); without the floor + divisions 18 (printing) and 37 (sewerage) would get a small negative other + final share (about -1.2 and -0.1 percent). +- **imputed rent is not a firm product.** ``CPA_L68A`` (imputed rents of + owner-occupied dwellings: 284,071 million pounds of domestic output; + 288,906 of its 289,717 million pounds of demand from households, 811 + exports) is produced by owner-occupiers, not firms, so it is left out of + division 68 and every aggregate here; division 68 is real estate on own + account (``CPA_L68BXL683``) and on a fee basis (``CPA_L683``). + +**Wholesale and retail (divisions 45, 46, 47).** Table 1's distributors' +trading margins column is negative on exactly the three trade products +(``CPA_G45`` -38,934, ``CPA_G46`` -202,054, ``CPA_G47`` -182,703 million +pounds) and positive on goods products (and the publishing products ``J58`` +and ``J59 & J60``); it sums to zero. The trade output is therefore +redistributed onto the goods it is a margin on, and the trade products' own +rows hold almost no demand (``CPA_G47`` total demand 0, ``CPA_G46`` 276), so +their own-row shares are undefined. A trade division's shares are instead +margin-weighted over the products with a positive margin: +``s_trade = sum_p m_p s_p / sum_p m_p`` where ``s_p`` is product ``p``'s +demand share. Limitations, stated rather than fixed: the margins column is +one combined column (wholesale, retail and motor trade together), so 45, 46 +and 47 get identical shares, although retail margins sit mostly on household +purchases and wholesale margins on intermediate ones; and ``CPA_G45``'s own +direct (non-margin) demand (21,469 of its 33,460 million pounds from +households) is not used. + +**Fallback.** A division with no product (98, 99, or a code that is not a +SIC 2007 division) takes its section's aggregate (sums over the section's +products; the trade margin weighting for section G), and a section with no +product (U) or an unreadable code takes the economy-wide aggregate (sums +over every product but imputed rent). The fallbacks are counted. + +COICOP shares of household sales (:func:`uk_firm_division_coicop_shares`) +use Table 3 (household final consumption, domestic concept, product by +COICOP class) aggregated to COICOP divisions 01-12 and to SIC divisions the +same way; for 45-47 each product's household purchases by COICOP division +are weighted by its margin per pound of total demand +(``sum_p m_p T3_pk / D_p``, normalised), so a trade division's household +sales follow the goods households buy, in proportion to the margin they +carry. Table 3 prints ``CPA_C27`` and ``CPA_C28`` as one row; it counts +whole in divisions 27 and 28. + +Table 3's COICOP totals equal ONS Consumer Trends 2024 (the vendored 30 +September 2026 release, the same Blue Book 2026 vintage) in every division: +:func:`check_uk_table3_consumer_trends` is a source-consistency check of the +extraction and the vintage, not a validation of the shares, which it never +reads. It will fail once Consumer Trends is re-vendored at a later vintage. +""" + +from __future__ import annotations + +import hashlib +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +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.occupation_constants import ( + UK_SIC2007_SECTION_DIVISIONS, + uk_sic2007_sections, +) + +#: The extracted CSVs' file names in a supply and use source directory. +UK_FIRM_SUT_USES_FILE = "sut_product_uses.csv" +UK_FIRM_SUT_HHFCE_FILE = "sut_hhfce_product_coicop.csv" +UK_FIRM_SUT_DIVISION_FILE = "sut_product_sic_division.csv" +UK_FIRM_SUT_FILES = ( + UK_FIRM_SUT_USES_FILE, + UK_FIRM_SUT_HHFCE_FILE, + UK_FIRM_SUT_DIVISION_FILE, +) +UK_FIRM_SUT_USES_COLUMNS = ( + "product_code", + "product_label", + "intermediate_consumption", + "households", + "npish", + "central_government", + "local_government", + "gfcf", + "valuables", + "changes_in_inventories", + "exports", + "total_demand", + "domestic_output", + "imports", + "distributors_margins", + "taxes_less_subsidies", + "total_supply", +) +UK_FIRM_SUT_HHFCE_COLUMNS = ("product_code", "coicop", "value_gbp_million") +UK_FIRM_SUT_DIVISION_COLUMNS = ( + "product_code", + "sic_division", + "sic_section", + "map_sic_codes", + "map_a103_codes", +) +#: The supply and use year the shares describe. +UK_FIRM_SUT_YEAR = 2024 +#: Final demand other than households. +UK_FIRM_OTHER_FINAL_DEMAND = ( + "npish", + "central_government", + "local_government", + "gfcf", + "valuables", + "changes_in_inventories", + "exports", +) +#: Products left out of every firm aggregate (owner-occupiers' imputed rent). +UK_FIRM_SUT_EXCLUDED_PRODUCTS = ("CPA_L68A",) +#: SIC divisions whose shares are margin-weighted over goods products. +UK_FIRM_TRADE_DIVISIONS = (45, 46, 47) +#: The firm columns, in order; they sum to turnover. +UK_FIRM_CONSUMPTION_COLUMNS = ( + "firm_household_sales", + "firm_intermediate_sales", + "firm_other_final_sales", +) +UK_FIRM_CONSUMPTION_STATUS = "assumed" +UK_FIRM_CONSUMPTION_METHOD = ( + "firm turnover split by its SIC 2007 division's shares of total demand " + "(households; intermediate consumption; NPISH, government, capital " + "formation and exports) in the ONS Supply and Use Tables 2024 (Blue Book " + "2026), product = industry, imports used like domestic output, divisions " + "45-47 margin-weighted over goods products" +) +#: COICOP divisions, as Consumer Trends and Table 3 code them. +UK_COICOP_DIVISIONS = tuple(f"{k:02d}" for k in range(1, 13)) +#: Classes both Table 3 and Consumer Trends publish that household surveys +#: do not record: narcotics and imputed rentals. Table 3 has no 12.6.1 +#: (FISIM) class, so that one is excluded on neither side. +UK_COICOP_GATE_EXCLUSIONS = ("02.3", "04.2") +#: The Table 3 vs Consumer Trends consistency check's tolerance per COICOP division, in +#: pounds million (both are published in whole pounds million). +UK_FIRM_TABLE3_GATE_TOLERANCE_GBP_MILLION = 0.5 + +#: The highest SIC 2007 division (99, extra-territorial organisations). +_LAST_SIC_DIVISION = max(last for _, last in UK_SIC2007_SECTION_DIVISIONS.values()) +_SHARE_COLUMNS = ("household_share", "intermediate_share", "other_final_share") + + +@dataclass(frozen=True) +class UKFirmSupplyUseSource: + """The extracted supply and use tables. + + ``uses`` is indexed by product code with the numeric columns of + ``UK_FIRM_SUT_USES_COLUMNS``; ``hhfce`` is Table 3 in long form (Table 3 + row code, COICOP column, pounds million); ``divisions`` maps each product + to its SIC divisions (int). ``sha256`` maps each file name to its hash. + """ + + uses: pd.DataFrame + hhfce: pd.DataFrame + divisions: pd.DataFrame + sha256: Mapping[str, str] + + +def _read_csv(path: Path, columns: Sequence[str]) -> tuple[pd.DataFrame, str]: + payload = path.read_bytes() + frame = pd.read_csv(path, dtype=str, keep_default_na=False) + if tuple(frame.columns) != tuple(columns): + raise ValueError( + f"{path.name} columns {list(frame.columns)} are not {list(columns)}." + ) + return frame, hashlib.sha256(payload).hexdigest() + + +def read_uk_firm_supply_use_source(path: str | Path) -> UKFirmSupplyUseSource: + """Read the three supply and use CSVs from their directory. + + Raises ``ValueError`` on wrong columns, a non-numeric value, a product + whose demand components do not add up to its total demand, or a product + without a SIC division. + """ + + directory = Path(path) + uses, uses_hash = _read_csv( + directory / UK_FIRM_SUT_USES_FILE, UK_FIRM_SUT_USES_COLUMNS + ) + hhfce, hhfce_hash = _read_csv( + directory / UK_FIRM_SUT_HHFCE_FILE, UK_FIRM_SUT_HHFCE_COLUMNS + ) + divisions, divisions_hash = _read_csv( + directory / UK_FIRM_SUT_DIVISION_FILE, UK_FIRM_SUT_DIVISION_COLUMNS + ) + if uses["product_code"].duplicated().any(): + raise ValueError(f"{UK_FIRM_SUT_USES_FILE} repeats a product.") + uses = uses.set_index("product_code") + numeric = [c for c in UK_FIRM_SUT_USES_COLUMNS[2:]] + try: + uses[numeric] = uses[numeric].astype(np.float64) + hhfce["value_gbp_million"] = hhfce["value_gbp_million"].astype(np.float64) + divisions["sic_division"] = divisions["sic_division"].astype(np.int64) + except ValueError: + raise ValueError("UK supply and use values must be numbers.") from None + demand = uses["intermediate_consumption"] + uses[ + ["households", *UK_FIRM_OTHER_FINAL_DEMAND] + ].sum(axis=1) + if not np.allclose(demand, uses["total_demand"], rtol=0, atol=0.5): + raise ValueError("UK supply and use demand components != total demand.") + if set(divisions["product_code"]) != set(uses.index): + raise ValueError("Every UK supply and use product needs a SIC division.") + unknown = set(hhfce["coicop"].str[:2]) - set(UK_COICOP_DIVISIONS) + if unknown: + raise ValueError(f"Table 3 COICOP columns {sorted(unknown)} are not 01-12.") + for code in hhfce["product_code"].unique(): + _table3_products(code, uses.index) + return UKFirmSupplyUseSource( + uses=uses, + hhfce=hhfce, + divisions=divisions, + sha256=MappingProxyType( + { + UK_FIRM_SUT_USES_FILE: uses_hash, + UK_FIRM_SUT_HHFCE_FILE: hhfce_hash, + UK_FIRM_SUT_DIVISION_FILE: divisions_hash, + } + ), + ) + + +def _table3_products(code: str, products: Sequence[str] | pd.Index) -> list[str]: + """The Table 1 products a Table 3 row covers (``CPA_C27 & C28`` -> two).""" + + if code in products: + return [code] + parts = ["CPA_" + part.strip() for part in code[len("CPA_") :].split("&")] + if len(parts) < 2 or any(part not in products for part in parts): + raise ValueError(f"Table 3 row {code} is not a union of Table 1 products.") + return parts + + +def _firm_products(source: UKFirmSupplyUseSource) -> pd.DataFrame: + return source.uses.drop( + index=[p for p in UK_FIRM_SUT_EXCLUDED_PRODUCTS if p in source.uses.index] + ) + + +def _components(uses: pd.DataFrame) -> np.ndarray: + """Household, intermediate, other final and total demand per product. + + Negative components (changes in inventories, a drawdown of stocks, on + some products) are floored at zero and the total is the sum of the + floored components, so every share is in [0, 1]. + """ + + other = uses[list(UK_FIRM_OTHER_FINAL_DEMAND)].clip(lower=0).sum(axis=1) + parts = np.stack( + [ + uses["households"].clip(lower=0).to_numpy(dtype=np.float64), + uses["intermediate_consumption"].clip(lower=0).to_numpy(dtype=np.float64), + other.to_numpy(dtype=np.float64), + ] + ) + return np.vstack([parts, parts.sum(axis=0)]) + + +def _demand_sums(uses: pd.DataFrame) -> np.ndarray: + """Household, intermediate, other final and total demand, summed.""" + + return _components(uses).sum(axis=1) + + +def _trade_sums(uses: pd.DataFrame) -> np.ndarray: + """Margin-weighted demand over products with a positive margin. + + Each product's demand is scaled by ``margin / total demand``, so the + totals are ``sum_p m_p s_p`` and their sum ``sum_p m_p``. + """ + + goods = uses[uses["distributors_margins"] > 0] + parts = _components(goods) + scale = goods["distributors_margins"].to_numpy(dtype=np.float64) / parts[3] + return (parts * scale).sum(axis=1) + + +def _row(sums: np.ndarray, basis: str) -> dict[str, Any]: + household, intermediate, other, total = (float(v) for v in sums) + return { + "household_share": household / total, + "intermediate_share": intermediate / total, + "other_final_share": other / total, + "household_gbp_million": household, + "intermediate_gbp_million": intermediate, + "other_final_gbp_million": other, + "total_demand_gbp_million": total, + "basis": basis, + } + + +def _division_products(source: UKFirmSupplyUseSource) -> dict[int, list[str]]: + kept = set(_firm_products(source).index) + out: dict[int, list[str]] = {} + for code, division in zip( + source.divisions["product_code"], + source.divisions["sic_division"], + strict=True, + ): + if code in kept: + out.setdefault(int(division), []).append(code) + return out + + +def uk_firm_division_use_shares(source: UKFirmSupplyUseSource) -> pd.DataFrame: + """Each SIC division's household, intermediate and other final shares. + + Indexed by division (int). The ``*_gbp_million`` columns are the summed + numerators and denominator, the denominator being total demand with + negative components floored at zero (for 45-47 the margin-weighted + sums, whose total is the goods products' margins); ``basis`` is ``"products"`` or + ``"trade_margin"``. + """ + + uses = _firm_products(source) + trade = _trade_sums(uses) + rows = {} + for division, products in sorted(_division_products(source).items()): + if division in UK_FIRM_TRADE_DIVISIONS: + rows[division] = _row(trade, "trade_margin") + else: + rows[division] = _row(_demand_sums(uses.loc[products]), "products") + frame = pd.DataFrame.from_dict(rows, orient="index") + frame.index.name = "sic_division" + return frame + + +def _section_use_shares(source: UKFirmSupplyUseSource) -> pd.DataFrame: + """Each section's aggregate over its products (each product once).""" + + uses = _firm_products(source) + by_division = _division_products(source) + rows = {} + for section, (first, last) in UK_SIC2007_SECTION_DIVISIONS.items(): + divisions = [d for d in by_division if first <= d <= last] + if not divisions: + continue + if all(d in UK_FIRM_TRADE_DIVISIONS for d in divisions): + rows[section] = _row(_trade_sums(uses), "section") + continue + products = sorted({p for d in divisions for p in by_division[d]}) + rows[section] = _row(_demand_sums(uses.loc[products]), "section") + return pd.DataFrame.from_dict(rows, orient="index") + + +def _economy_use_shares(source: UKFirmSupplyUseSource) -> dict[str, Any]: + return _row(_demand_sums(_firm_products(source)), "economy") + + +def _divisions(division: Any) -> np.ndarray: + """SIC divisions as int, -1 where a value is missing or not 1-99.""" + + raw = pd.to_numeric(pd.Series(np.asarray(division, dtype=object)), errors="coerce") + values = raw.to_numpy(dtype=np.float64) + ok = np.isfinite(values) & (values == np.round(values)) + ok &= (values >= 1) & (values <= _LAST_SIC_DIVISION) + return np.where(ok, values, -1).astype(np.int64) + + +def _lookup( + division: Any, + by_division: pd.DataFrame, + by_section: pd.DataFrame, + economy: Mapping[str, Any], + columns: Sequence[str], +) -> tuple[np.ndarray, dict[str, int]]: + """Rows of ``columns`` for each division, with section and economy fallback.""" + + divisions = _divisions(division) + out = np.empty((len(divisions), len(columns)), dtype=np.float64) + counts = {"division": 0, "section": 0, "economy": 0} + sections = uk_sic2007_sections(np.where(divisions < 0, 0, divisions)) + economy_row = np.array([economy[c] for c in columns], dtype=np.float64) + division_table = by_division[list(columns)].to_numpy(dtype=np.float64) + division_position = {int(d): i for i, d in enumerate(by_division.index)} + section_table = by_section[list(columns)].to_numpy(dtype=np.float64) + section_position = {str(s): i for i, s in enumerate(by_section.index)} + for value in np.unique(divisions): + mask = divisions == value + if int(value) in division_position: + out[mask] = division_table[division_position[int(value)]] + counts["division"] += int(mask.sum()) + continue + section = str(sections[mask][0]) if value > 0 else "" + if section in section_position: + out[mask] = section_table[section_position[section]] + counts["section"] += int(mask.sum()) + else: + out[mask] = economy_row + counts["economy"] += int(mask.sum()) + return out, counts + + +@dataclass(frozen=True) +class UKFirmConsumptionSales: + """The firm columns and how many rows each share level supplied.""" + + columns: pd.DataFrame + fallback_counts: Mapping[str, int] + status: str = UK_FIRM_CONSUMPTION_STATUS + method: str = UK_FIRM_CONSUMPTION_METHOD + + +def uk_firm_consumption_sales( + division: Any, turnover: Any, source: UKFirmSupplyUseSource +) -> UKFirmConsumptionSales: + """Split each firm's turnover into household, intermediate and other final sales. + + ``division`` is each firm's SIC 2007 division (the firm frame's + ``sic_code``); ``turnover`` its turnover in any unit (the export's + ``firm_turnover``, pounds), returned in the same unit. Household and + intermediate sales are turnover times the division's shares; other final + sales is the remainder, so the three columns sum to turnover up to one + floating-point rounding (zero and negative turnover split the same way). + ``fallback_counts`` counts rows by the level whose shares they took + (``division``, ``section``, ``economy``). + """ + + values = np.asarray(turnover, dtype=np.float64) + if values.ndim != 1 or len(values) != len(np.asarray(division, dtype=object)): + raise ValueError("UK firm division and turnover must be equal-length 1-d.") + if not np.all(np.isfinite(values)): + raise ValueError("UK firm turnover must be finite.") + shares, counts = _lookup( + division, + uk_firm_division_use_shares(source), + _section_use_shares(source), + _economy_use_shares(source), + _SHARE_COLUMNS, + ) + household = values * shares[:, 0] + intermediate = values * shares[:, 1] + other = values - household - intermediate + columns = pd.DataFrame( + { + "firm_household_sales": household, + "firm_intermediate_sales": intermediate, + "firm_other_final_sales": other, + } + ) + return UKFirmConsumptionSales( + columns=columns, fallback_counts=MappingProxyType(counts) + ) + + +def _table3_by_row(source: UKFirmSupplyUseSource) -> pd.DataFrame: + """Table 3 rows (row code) x COICOP division, pounds million.""" + + frame = source.hhfce.assign(division=source.hhfce["coicop"].str[:2]) + wide = frame.pivot_table( + index="product_code", + columns="division", + values="value_gbp_million", + aggfunc="sum", + fill_value=0.0, + ) + return wide.reindex(columns=list(UK_COICOP_DIVISIONS), fill_value=0.0) + + +def _coicop_row(sums: np.ndarray, basis: str) -> dict[str, Any] | None: + total = float(sums.sum()) + if total <= 0: + return None + return { + **{k: float(v) / total for k, v in zip(UK_COICOP_DIVISIONS, sums, strict=True)}, + "household_gbp_million": total, + "basis": basis, + } + + +def _coicop_parts( + source: UKFirmSupplyUseSource, +) -> tuple[pd.DataFrame, dict[str, list[str]], np.ndarray]: + """Table 3 rows of firm products, the products each covers, trade sums.""" + + kept = set(_firm_products(source).index) + table3 = _table3_by_row(source) + covers = {code: _table3_products(code, source.uses.index) for code in table3.index} + table3 = table3.loc[[c for c in table3.index if set(covers[c]) & kept]] + uses = source.uses + trade = np.zeros(len(UK_COICOP_DIVISIONS)) + for code, row in table3.iterrows(): + products = covers[code] + margin = float(uses.loc[products, "distributors_margins"].sum()) + if margin > 0: + demand = float(_components(uses.loc[products])[3].sum()) + trade += margin / demand * row.to_numpy(dtype=np.float64) + return table3, covers, trade + + +def _coicop_tables( + source: UKFirmSupplyUseSource, +) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]: + table3, covers, trade = _coicop_parts(source) + by_division = _division_products(source) + + def rows_for(divisions: Sequence[int]) -> np.ndarray: + wanted = {p for d in divisions for p in by_division[d]} + codes = [c for c in table3.index if set(covers[c]) & wanted] + return table3.loc[codes].to_numpy(dtype=np.float64).sum(axis=0) + + divisions = {} + for division in sorted(by_division): + if division in UK_FIRM_TRADE_DIVISIONS: + row = _coicop_row(trade, "trade_margin") + else: + row = _coicop_row(rows_for([division]), "products") + if row is not None: + divisions[division] = row + sections = {} + for section, (first, last) in UK_SIC2007_SECTION_DIVISIONS.items(): + members = [d for d in by_division if first <= d <= last] + if not members: + continue + if all(d in UK_FIRM_TRADE_DIVISIONS for d in members): + row = _coicop_row(trade, "section") + else: + row = _coicop_row(rows_for(members), "section") + if row is not None: + sections[section] = row + economy = _coicop_row(rows_for(sorted(by_division)), "economy") + assert economy is not None + division_frame = pd.DataFrame.from_dict(divisions, orient="index") + division_frame.index.name = "sic_division" + return division_frame, pd.DataFrame.from_dict(sections, orient="index"), economy + + +def uk_firm_division_coicop_shares(source: UKFirmSupplyUseSource) -> pd.DataFrame: + """SIC division x COICOP division (``"01"``..``"12"``) shares of household sales. + + From Table 3 (domestic concept), summed over each division's products; + divisions 45-47 margin-weighted over goods products. A division with + products but no Table 3 household purchases takes its section's shares + (``basis`` ``"section"``) or the economy-wide ones (``"economy"``); + ``household_gbp_million`` is the summed Table 3 purchases behind the + row's own shares (the fallback level's for a fallback row). + """ + + divisions, sections, economy = _coicop_tables(source) + all_divisions = sorted(_division_products(source)) + columns = [*UK_COICOP_DIVISIONS, "household_gbp_million"] + values, _ = _lookup(all_divisions, divisions, sections, economy, columns) + frame = pd.DataFrame(values, index=pd.Index(all_divisions), columns=columns) + frame.index.name = "sic_division" + basis = [] + for division in all_divisions: + if division in divisions.index: + basis.append(divisions.loc[division, "basis"]) + else: + section = str(uk_sic2007_sections([division])[0]) + basis.append("section" if section in sections.index else "economy") + frame["basis"] = basis + return frame + + +def _consumer_trends(year: int) -> dict[str, float]: + """Consumer Trends domestic HFCE by COICOP division and gate class, £ million.""" + + from microcosm.build.uk_runtime.energy_pricing import ( + UK_ONS_HFCE_ROW_DIMENSIONS, + UK_ONS_HOUSEHOLD_EXPENDITURE_RESOURCE, + ) + from microcosm.build.uk_runtime.ledger_fact_vendoring import vendored_rows + + rows = vendored_rows( + UK_ONS_HOUSEHOLD_EXPENDITURE_RESOURCE, + concept="ons.household_final_consumption_expenditure", + period_type="calendar_year", + period_value=year, + dimensions={"consumption_concept": "domestic", **UK_ONS_HFCE_ROW_DIMENSIONS}, + ) + wanted = {*UK_COICOP_DIVISIONS, *UK_COICOP_GATE_EXCLUSIONS} + out: dict[str, float] = {} + for row in rows: + code = str(row["dimensions"]["coicop"]) + if code in wanted: + if code in out: + raise ValueError(f"Consumer Trends {year} COICOP {code} appears twice.") + out[code] = float(row["value"]) / 1e6 + missing = sorted(wanted - set(out)) + if missing: + raise ValueError(f"Consumer Trends {year} lacks COICOP {missing}.") + return out + + +def uk_table3_consumer_trends_comparison( + source: UKFirmSupplyUseSource, year: int = UK_FIRM_SUT_YEAR +) -> pd.DataFrame: + """Table 3 COICOP-division totals vs ONS Consumer Trends (domestic concept). + + Indexed by COICOP division. ``table3`` and ``consumer_trends`` are pounds + million less the classes in ``UK_COICOP_GATE_EXCLUSIONS`` (both sides + publish them; 12.6.1 FISIM is in neither exclusion because Table 3 has no + such class). ``difference`` is Table 3 minus Consumer Trends. + """ + + trends = _consumer_trends(year) + hhfce = source.hhfce + table3 = hhfce.groupby(hhfce["coicop"].str[:2])["value_gbp_million"].sum() + rows = {} + for division in UK_COICOP_DIVISIONS: + t3 = float(table3.get(division, 0.0)) + ct = trends[division] + excluded = [c for c in UK_COICOP_GATE_EXCLUSIONS if c[:2] == division] + for code in excluded: + t3 -= float(hhfce.loc[hhfce["coicop"] == code, "value_gbp_million"].sum()) + ct -= trends[code] + rows[division] = { + "table3": t3, + "consumer_trends": ct, + "difference": t3 - ct, + "excluded": ";".join(excluded), + } + frame = pd.DataFrame.from_dict(rows, orient="index") + frame.index.name = "coicop_division" + return frame + + +def check_uk_table3_consumer_trends( + source: UKFirmSupplyUseSource, + tolerance: float = UK_FIRM_TABLE3_GATE_TOLERANCE_GBP_MILLION, +) -> pd.DataFrame: + """Source consistency: every COICOP division within ``tolerance`` pounds million. + + Returns the comparison; raises ``ValueError`` naming the divisions + outside it. + """ + + frame = uk_table3_consumer_trends_comparison(source) + outside = frame.index[frame["difference"].abs() > tolerance].tolist() + if outside: + raise ValueError( + f"Table 3 differs from Consumer Trends by more than {tolerance} " + f"pounds million in COICOP divisions {outside}." + ) + return frame + + +def uk_firm_household_sales_by_coicop( + division: Any, + household_sales: Any, + weight: Any, + source: UKFirmSupplyUseSource, + year: int = UK_FIRM_SUT_YEAR, + unit: float = 1e6, +) -> pd.DataFrame: + """Diagnostic only: weighted firm household sales by COICOP division vs Consumer Trends. + + ``household_sales`` (in pounds over ``unit``; default pounds -> pounds + million) is spread over COICOP divisions by the firm's division shares, + weighted and summed. ``consumer_trends_excluded`` is Consumer Trends + less narcotics (02.3) and imputed rentals (04.2). No firm sells + narcotics or owner-occupiers' imputed rent, but Table 3 puts 7,544 + million pounds of 04.2 on ``CPA_L68BXL683`` (real estate services), a + firm product, so division 68's household sales carry it while this + comparison leaves it out; + ``ratio`` is against it. This cannot close to Consumer Trends and is not a + gate. Directions of the separate biases, not a net sign: + + - gross turnover counts goods twice along the chain (the maker's + household share and the retailer's whole turnover times the margin- + weighted share): upward; + - turnover is net of VAT and product taxes, Consumer Trends is at + purchasers' prices: downward (largest for 02 alcohol and tobacco and + 07 fuel); + - imported goods and services households buy are not UK firm output + except through retail turnover: downward; + - household shares are Table 2's national concept (residents' spending + abroad in, non-residents' spending in the UK out), Consumer Trends is + domestic: small, either way by product; + - the business population's turnover need not equal output (registered + firms only, government and non-market output largely absent): downward + for 06, 10 and 12 especially. + """ + + sales = np.asarray(household_sales, dtype=np.float64) / unit + weights = np.asarray(weight, dtype=np.float64) + columns = list(UK_COICOP_DIVISIONS) + divisions, sections, economy = _coicop_tables(source) + shares, _ = _lookup(division, divisions, sections, economy, columns) + firm = (shares * (sales * weights)[:, None]).sum(axis=0) + trends = _consumer_trends(year) + frame = pd.DataFrame( + { + "firm_household_sales": firm, + "consumer_trends": [trends[c] for c in columns], + "consumer_trends_excluded": [ + trends[c] + - sum(trends[e] for e in UK_COICOP_GATE_EXCLUSIONS if e[:2] == c) + for c in columns + ], + }, + index=pd.Index(columns, name="coicop_division"), + ) + frame["ratio"] = frame["firm_household_sales"] / frame["consumer_trends_excluded"] + return frame + + +#: Parts of household purchases in +#: :func:`uk_household_purchases_supply_decomposition`, in order. +UK_HOUSEHOLD_PURCHASE_PARTS = ( + "domestic_basic", + "imports", + "distributors_margins", + "taxes_less_subsidies", +) + + +def uk_household_purchases_supply_decomposition( + source: UKFirmSupplyUseSource, +) -> pd.DataFrame: + """Diagnostic only: Table 2 household purchases split by source of supply. + + Each product's household purchases (Table 2 households, purchasers' + prices, national concept) are split in proportion to its Table 1 supply: + domestic output at basic prices, imports, distributors' margins and + taxes less subsidies, which sum to total supply. This is a + supply-proportionality assumption, not a published statistic, and never + a target. Products in ``UK_FIRM_SUT_EXCLUDED_PRODUCTS`` (owner-occupiers' + imputed rent) are left out; the trade products of divisions 45-47, whose + margins column is negative, are not split and their own household + purchases are returned as ``trade_own_demand``. + + Only the domestic basic-price output and the margins (which belong to + trade output) are UK producers' output sold to households, and part of + that output (real estate, finance, insurance, health) is imputed, + non-market or unincorporated rather than firm turnover. Imports and + product taxes are in Consumer Trends but outside UK firms' output at + basic prices, so outside the share-allocated ``firm_household_sales``; + gross trade turnover still includes resold imports, and turnover + includes excise duties. Returns one row + per product with the parts in pounds million, the parts summing to + ``households`` on every non-trade row. + """ + + uses = source.uses.drop( + index=[p for p in UK_FIRM_SUT_EXCLUDED_PRODUCTS if p in source.uses.index] + ) + divisions = source.divisions.groupby("product_code")["sic_division"].apply( + lambda values: set(int(v) for v in values) + ) + trade = np.asarray( + [ + bool(divisions.get(code, set())) + and divisions.get(code, set()) <= set(UK_FIRM_TRADE_DIVISIONS) + for code in uses.index + ] + ) + households = uses["households"].to_numpy(np.float64) + supply = uses["total_supply"].to_numpy(np.float64) + out = pd.DataFrame(index=uses.index) + out["households"] = households + out["trade_own_demand"] = np.where(trade, households, 0.0) + for part, column in zip( + UK_HOUSEHOLD_PURCHASE_PARTS, + ("domestic_output", "imports", "distributors_margins", "taxes_less_subsidies"), + strict=True, + ): + values = uses[column].to_numpy(np.float64) + share = np.divide(values, supply, out=np.zeros_like(values), where=supply != 0) + out[part] = np.where(trade, 0.0, households * share) + out.index.name = "product_code" + return out + + +__all__ = [ + "UK_COICOP_DIVISIONS", + "UK_COICOP_GATE_EXCLUSIONS", + "UK_FIRM_CONSUMPTION_COLUMNS", + "UK_FIRM_CONSUMPTION_METHOD", + "UK_FIRM_CONSUMPTION_STATUS", + "UK_FIRM_OTHER_FINAL_DEMAND", + "UK_FIRM_SUT_DIVISION_COLUMNS", + "UK_FIRM_SUT_DIVISION_FILE", + "UK_FIRM_SUT_EXCLUDED_PRODUCTS", + "UK_FIRM_SUT_FILES", + "UK_FIRM_SUT_HHFCE_COLUMNS", + "UK_FIRM_SUT_HHFCE_FILE", + "UK_FIRM_SUT_USES_COLUMNS", + "UK_FIRM_SUT_USES_FILE", + "UK_FIRM_SUT_YEAR", + "UK_FIRM_TABLE3_GATE_TOLERANCE_GBP_MILLION", + "UK_FIRM_TRADE_DIVISIONS", + "UK_HOUSEHOLD_PURCHASE_PARTS", + "UKFirmConsumptionSales", + "UKFirmSupplyUseSource", + "check_uk_table3_consumer_trends", + "read_uk_firm_supply_use_source", + "uk_firm_consumption_sales", + "uk_firm_division_coicop_shares", + "uk_firm_division_use_shares", + "uk_firm_household_sales_by_coicop", + "uk_household_purchases_supply_decomposition", + "uk_table3_consumer_trends_comparison", +] diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_employment_allowance.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_employment_allowance.py new file mode 100644 index 0000000000..f3542deaf4 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_employment_allowance.py @@ -0,0 +1,194 @@ +"""UK firm Employment Allowance flags: assumed rules from legal status and size. + +policyengine-uk decides Employment Allowance eligibility +(``employment_allowance_eligible``) from four firm inputs. Two of them have +nothing to read in the experimental UK firm generator, and their defaults let +every employer claim: + +- ``firm_claims_employment_allowance`` (default true): false for a firm that + does not claim, including a connected company that is not its group's + claimant; +- ``firm_is_single_director_company`` (default false): true for a company + whose only employee paid Class 1 earnings is a director (NICA 2014 + s.2(4A)). + +This module sets both from the ONS legal status code and the ONS employment +headcount, which counts working proprietors as well as employees. The rules +are assumptions, not observations: + +- a sole proprietor (ONS status 2) with employment of at most 1 is the + proprietor alone: no employee, so no claim; +- a partnership (status 3) with employment of at most 2 is taken to be its + partners alone: no claim; +- a company (status 1) with employment 1 is taken to be a single-director + company: its one person is a director. A company whose director employs a + spouse below the secondary threshold is also excluded in law and is missed. + +policyengine-uk documents ``firm_claims_employment_allowance`` as "this firm +is its connected group's claimant"; this module reuses it for "has no +employees to claim for". Nothing else changes: every other firm keeps the +policyengine-uk defaults (claims, not a single-director company). Connected +groups and the de minimis state aid test are not modelled. The 2024-25 +£100,000 prior-year liability limit (s.2(4B)) is applied by policyengine-uk: +``firm_prior_year_secondary_class_1_liabilities`` is left unset, and its +formula falls back to the firm's current-year liabilities. + +The flags change only the allowance. Proprietor-only firms still carry an +assumed paybill (``firm_paybill.py``) and so employer NIC; with the flags +they lose the allowance against it, which raises modelled employer NIC. + +The rules read no random numbers, so the generator stream and every other +column are unchanged. HMRC's tax relief statistics (January 2026: 1,223,000 +claimants and a cost of £3,300 million in 2024-25) are a held-out check in +``tests/fixtures/uk/firm_employment_allowance_2024_25/``, never a target of +these flags. ``uk_firm_employment_allowance_comparison`` sets a +policyengine-uk run beside them; no build or tool calls it. The opt-in +take-up draw (``firm_employment_allowance_takeup.py``) reads HMRC's claimant +counts by size band, so with it the claimant total is in-sample and only the +cost stays held out. +""" + +from __future__ import annotations + +import csv +import hashlib +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path + +__all__ = [ + "UK_FIRM_EMPLOYMENT_ALLOWANCE_CHECK_FILE", + "UK_FIRM_EMPLOYMENT_ALLOWANCE_COLUMNS", + "UK_FIRM_EMPLOYMENT_ALLOWANCE_METHOD", + "UK_FIRM_EMPLOYMENT_ALLOWANCE_STATUS", + "UK_FIRM_PARTNERSHIP_PARTNERS_ONLY_MAX_EMPLOYMENT", + "UKFirmEmploymentAllowanceCheck", + "assign_uk_firm_employment_allowance", + "read_uk_firm_employment_allowance_check", + "uk_firm_employment_allowance_comparison", + "uk_firm_employment_allowance_flags", +] + +import numpy as np +import pandas as pd + +#: Status of the two flags, in ``UK_FIRM_POLICYENGINE_UK_INPUT_STATUS`` terms. +UK_FIRM_EMPLOYMENT_ALLOWANCE_STATUS = "assumed" + +#: The flags this module sets, in export order. +UK_FIRM_EMPLOYMENT_ALLOWANCE_COLUMNS = ( + "firm_claims_employment_allowance", + "firm_is_single_director_company", +) + +#: How the flags are set, for build receipts. +UK_FIRM_EMPLOYMENT_ALLOWANCE_METHOD = ( + "Assumed from ONS legal status and ONS employment (which counts working " + "proprietors): sole proprietors with employment of at most 1 and " + "partnerships with employment of at most 2 do not claim; companies with employment 1 are " + "single-director companies. Every other firm keeps the policyengine-uk " + "defaults." +) + +#: ONS legal status codes the rules read. +_COMPANY, _SOLE_PROPRIETOR, _PARTNERSHIP = 1, 2, 3 +#: Largest employment at which a partnership is taken to be its partners alone. +UK_FIRM_PARTNERSHIP_PARTNERS_ONLY_MAX_EMPLOYMENT = 2 + +#: The held-out HMRC figures' file name in the fixture directory. +UK_FIRM_EMPLOYMENT_ALLOWANCE_CHECK_FILE = "hmrc_employment_allowance.csv" +_CHECK_COLUMNS = ("tax_year", "claimants", "cost_gbp") + + +def uk_firm_employment_allowance_flags( + legal_status: np.ndarray | pd.Series, employment: np.ndarray | pd.Series +) -> dict[str, np.ndarray]: + """The two flags for ONS ``legal_status`` codes and ``employment`` counts.""" + + status = np.asarray(legal_status, dtype=np.int64) + headcount = np.asarray(employment, dtype=np.int64) + if status.shape != headcount.shape: + raise ValueError("legal_status and employment must have the same shape.") + if np.any(headcount < 0): + raise ValueError("UK firm employment must be non-negative.") + proprietor_alone = (status == _SOLE_PROPRIETOR) & (headcount <= 1) + partners_alone = (status == _PARTNERSHIP) & ( + headcount <= UK_FIRM_PARTNERSHIP_PARTNERS_ONLY_MAX_EMPLOYMENT + ) + return { + "firm_claims_employment_allowance": ~(proprietor_alone | partners_alone), + "firm_is_single_director_company": (status == _COMPANY) & (headcount == 1), + } + + +def assign_uk_firm_employment_allowance(firms: pd.DataFrame) -> pd.DataFrame: + """``firms`` with the two flags added from ``ons_legal_status`` and ``employment``.""" + + missing = [c for c in ("ons_legal_status", "employment") if c not in firms] + if missing: + raise ValueError( + f"UK firm Employment Allowance flags need {missing}; assign the ONS " + "attributes first." + ) + return firms.assign( + **uk_firm_employment_allowance_flags( + firms["ons_legal_status"].to_numpy(), firms["employment"].to_numpy() + ) + ) + + +@dataclass(frozen=True) +class UKFirmEmploymentAllowanceCheck: + """HMRC's Employment Allowance claimants and cost for one tax year.""" + + tax_year: str + claimants: float + cost_gbp: float + sha256: str + + +def read_uk_firm_employment_allowance_check( + directory: str | Path, +) -> UKFirmEmploymentAllowanceCheck: + """Read the held-out HMRC figures for 2024-25 from ``directory``.""" + + path = Path(directory) / UK_FIRM_EMPLOYMENT_ALLOWANCE_CHECK_FILE + data = path.read_bytes() + rows = list(csv.DictReader(data.decode("utf-8").splitlines())) + if not rows or tuple(rows[0]) != _CHECK_COLUMNS: + raise ValueError(f"{path} must have columns {list(_CHECK_COLUMNS)}.") + by_year = {row["tax_year"]: row for row in rows} + if "2024-25" not in by_year: + raise ValueError(f"{path} has no 2024-25 row.") + row = by_year["2024-25"] + return UKFirmEmploymentAllowanceCheck( + tax_year="2024-25", + claimants=float(row["claimants"]), + cost_gbp=float(row["cost_gbp"]), + sha256=hashlib.sha256(data).hexdigest(), + ) + + +def uk_firm_employment_allowance_comparison( + allowance: np.ndarray, weight: np.ndarray, check: UKFirmEmploymentAllowanceCheck +) -> Mapping[str, float]: + """Weighted model claimants and cost beside HMRC's, with ratios. + + ``allowance`` is policyengine-uk's ``employment_allowance`` per firm. A + diagnostic only: the HMRC figures are held out. + """ + + allowance = np.asarray(allowance, dtype=np.float64) + weight = np.asarray(weight, dtype=np.float64) + claimants = float(weight[allowance > 0].sum()) + cost = float((allowance * weight).sum()) + return { + "model_claimants": claimants, + "hmrc_claimants": check.claimants, + "claimants_ratio": claimants / check.claimants, + "model_cost_gbp": cost, + "hmrc_cost_gbp": check.cost_gbp, + "cost_ratio": cost / check.cost_gbp, + "model_cost_per_claimant_gbp": cost / claimants if claimants else 0.0, + "hmrc_cost_per_claimant_gbp": check.cost_gbp / check.claimants, + } diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_employment_allowance_takeup.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_employment_allowance_takeup.py new file mode 100644 index 0000000000..f2f5241aa0 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_employment_allowance_takeup.py @@ -0,0 +1,574 @@ +"""UK firm Employment Allowance claims: an opt-in draw at HMRC take-up by size. + +``firm_employment_allowance`` sets ``firm_claims_employment_allowance`` by +rule: every firm with an employee to claim for claims. HMRC counts 1,223,000 +employers benefitting in 2024-25 (*Employment Allowance take-up statistics: +2024 to 2025 tax year estimates*, published 25 June 2025, committed in +``tests/fixtures/uk/firm_employment_allowance_takeup_2024_25/``). A firm table +with more eligible employers than that over-claims. This module, opt-in +(``build_uk_firm_dataset``'s ``employment_allowance_takeup_dir``), thins the +rule flag towards HMRC's claimant count in each employee size band. It +reaches the count only in a band with at least as many weighted eligible +firms as HMRC claimants: see the shortfall below. + +Eligibility (all must hold; each is an assumption on the firm table): + +- the rule flag claims (``firm_claims_employment_allowance``); +- ``firm_employees`` (employees, not working proprietors) is at least one; +- not a public body (``firm_is_public_body``) and not a single-director + company (``firm_is_single_director_company``); +- a PROXY employer NIC before the allowance is below the £100,000 limit. + The proxy is ``UK_FIRM_EA_PROXY_SECONDARY_RATE`` times pay above the + secondary threshold, with every employee's pay taken above it unless + ``firm_paybill_below_secondary_threshold`` and + ``firm_employees_below_secondary_threshold`` are present, in which case + the pay of employees below the threshold is removed first. It is + current-year and paybill based; the law (NICA 2014 s.2(4B)) tests the + prior year's secondary Class 1 liabilities, which policyengine-uk + computes itself. A firm near the limit can be denied here and allowed + there, or the reverse. + +Size bands are HMRC's (PAYE employees at the end of the tax year), with +lower edges read from the fixture's labels. HMRC publishes 250+ as ``<500``, +a suppressed marker: no number is invented for it. Bands from +``UK_FIRM_EA_TAKEUP_POOLED_FROM`` up are pooled into one whose count is the +sum of their published numbers, so the pooled 50+ band takes the 50-249 +figure (7,000) and the 250+ claimants (fewer than 500) are folded in and +ignored. The bands' published counts sum to 1,222,000, not the 1,223,000 +total, from HMRC's rounding; neither is rescaled. + +Per band, propensity = min(1, HMRC claimants / weighted eligible firms); a +band with fewer weighted eligible firms than claimants is capped at one and +its shortfall reported. Each firm draws one uniform from its own stream, +``np.random.default_rng(SeedSequence([seed, UK_FIRM_EA_TAKEUP_SEED_TAG]))``, +in ``firm_id`` order, so the draw does not depend on row order and no other +stream moves. The new ``firm_claims_employment_allowance`` is +eligible-and-drawn, a subset of the rule flag. Ineligible firms that the +rule flag let claim are switched off; policyengine-uk would deny most of +them the allowance anyway, except those the proxy denies. + +Under this opt-in the band totals, and so the 1,223,000 total, are read +by the draw: they no longer test the firm table. They are not met exactly. +Every firm pays its section's mean (``firm_paybill.py``), so the proxy NIC +passes the £100,000 limit at a few dozen employees and almost no firm in +the pooled 50+ band is eligible: on the thinned 2024-25 test build that +band has about 10 weighted eligible firms against HMRC's 7,000, its +propensity is capped at one and its ``cap_shortfall`` is about 6,990, so +the drawn total is about 1.21 million. The proxy is kept rather than +dropped there because policyengine-uk applies the same limit and would deny +those claims anyway; HMRC's 50+ claimants are low-paying employers the +section-mean paybill cannot represent. HMRC's sector and region +tables stay held out (``uk_firm_employment_allowance_takeup_held_out``), as +does the £3.3bn 2024-25 cost in +``tests/fixtures/uk/firm_employment_allowance_2024_25/``. Status: assumed. +""" + +from __future__ import annotations + +import csv +import hashlib +import re +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd + +from microcosm.calibrate.geography_constants import ( + UK_LADDER_NATION_REGION_CODES, + UK_REGION_TIER_ENUM, +) + +__all__ = [ + "UK_FIRM_EA_LIABILITY_LIMIT_GBP", + "UK_FIRM_EA_PROXY_SECONDARY_RATE", + "UK_FIRM_EA_PROXY_SECONDARY_THRESHOLD_GBP", + "UK_FIRM_EA_TAKEUP_FILES", + "UK_FIRM_EA_TAKEUP_METHOD", + "UK_FIRM_EA_TAKEUP_POOLED_FROM", + "UK_FIRM_EA_TAKEUP_SEED_TAG", + "UK_FIRM_EA_TAKEUP_STATUS", + "UKFirmEATakeupBand", + "UKFirmEATakeupDraw", + "UKFirmEATakeupTables", + "assign_uk_firm_employment_allowance_takeup", + "draw_uk_firm_employment_allowance_takeup", + "read_uk_firm_employment_allowance_takeup", + "uk_firm_employer_nic_proxy", + "uk_firm_employment_allowance_eligible", + "uk_firm_employment_allowance_takeup_bands", + "uk_firm_employment_allowance_takeup_held_out", +] + +#: Status of the drawn flag, in ``UK_FIRM_POLICYENGINE_UK_INPUT_STATUS`` terms. +UK_FIRM_EA_TAKEUP_STATUS = "assumed" + +#: 2024-25 secondary Class 1 NIC rate (SSCBA 1992 s.9; HMRC rates and +#: thresholds for employers 2024 to 2025). Used only for the proxy below. +UK_FIRM_EA_PROXY_SECONDARY_RATE = 0.138 +#: 2024-25 secondary threshold, £175 a week, £9,100 a year (HMRC rates and +#: thresholds for employers 2024 to 2025). Used only for the proxy below. +UK_FIRM_EA_PROXY_SECONDARY_THRESHOLD_GBP = 9_100.0 +#: An employer whose secondary Class 1 liabilities reached £100,000 in the +#: prior tax year cannot claim (NICA 2014 s.2(4B), 2024-25). +UK_FIRM_EA_LIABILITY_LIMIT_GBP = 100_000.0 + +#: Lower edge (employees) from which HMRC's size bands are pooled into one. +UK_FIRM_EA_TAKEUP_POOLED_FROM = 50 + +#: Second word of the draw's ``SeedSequence``: ASCII "EATU". +UK_FIRM_EA_TAKEUP_SEED_TAG = 0x45415455 + +#: How the flag is set, for build receipts. +UK_FIRM_EA_TAKEUP_METHOD = ( + "Opt-in Bernoulli draw over firms eligible by rule flag, employees, public " + "body, single-director company and a proxy employer NIC below GBP 100,000; " + "propensity per HMRC size band (pooled from 50 employees; the suppressed " + "250+ count is ignored) = min(1, HMRC 2024-25 claimants / weighted " + "eligible firms)." +) + +#: The fixture's files, by table. +UK_FIRM_EA_TAKEUP_FILES = { + "size": "hmrc_ea_takeup_by_size.csv", + "sector": "hmrc_ea_takeup_by_sector.csv", + "region": "hmrc_ea_takeup_by_region.csv", +} +_COLUMNS = { + "size": ("business_size", "employers_benefitting", "share_percent"), + "sector": ( + "sic_section", + "sic_description", + "employers_benefitting", + "share_percent", + ), + "region": ( + "region_code", + "region_description", + "employers_benefitting", + "share_percent", + ), +} +_SUPPRESSED = re.compile(r"^<\d+$") +_BAND_LABEL = re.compile(r"^(\d+)(?:-(\d+)|\+)$") + + +def _count(value: str) -> float | None: + """A published count, or None for a suppressed marker such as ``<500``.""" + + if _SUPPRESSED.match(value): + return None + if not value.isdigit(): + raise ValueError(f"expected a count or a ' UKFirmEATakeupTables: + """Read the three HMRC take-up tables from ``directory``.""" + + tables: dict[str, tuple[tuple[str, str, float | None, str | None], ...]] = {} + totals: dict[str, float] = {} + hashes: dict[str, str] = {} + for key, name in UK_FIRM_EA_TAKEUP_FILES.items(): + path = Path(directory) / name + data = path.read_bytes() + rows = list(csv.DictReader(data.decode("utf-8").splitlines())) + if not rows or tuple(rows[0]) != _COLUMNS[key]: + raise ValueError(f"{path} must have columns {list(_COLUMNS[key])}.") + # The size table's label doubles as its description. + code, description = _COLUMNS[key][0], _COLUMNS[key][-3] + body = [] + for row in rows: + value = row["employers_benefitting"] + claimants = _count(value) + if row[code] == "Total": + if claimants is None: + raise ValueError(f"{path}: the Total is suppressed.") + totals[key] = claimants + continue + body.append( + ( + row[code], + row[description], + claimants, + value if claimants is None else None, + ) + ) + if key not in totals: + raise ValueError(f"{path} has no Total row.") + tables[key] = tuple(body) + hashes[name] = hashlib.sha256(data).hexdigest() + if len(set(totals.values())) != 1: + raise ValueError(f"The tables' totals differ: {totals}.") + return UKFirmEATakeupTables( + size=tables["size"], + sector=tables["sector"], + region=tables["region"], + total=totals["size"], + sha256=hashes, + ) + + +@dataclass(frozen=True) +class UKFirmEATakeupBand: + """One modelled size band: employees from ``lower`` up to the next band's.""" + + lower: int + label: str + hmrc_claimants: float + #: Published bands pooled into this one. + pooled: tuple[str, ...] + #: Pooled bands whose count is suppressed and so not in ``hmrc_claimants``, + #: with their markers. + ignored_suppressed: tuple[tuple[str, str], ...] + + +def uk_firm_employment_allowance_takeup_bands( + tables: UKFirmEATakeupTables, + pooled_from: int = UK_FIRM_EA_TAKEUP_POOLED_FROM, +) -> tuple[UKFirmEATakeupBand, ...]: + """Modelled size bands from the size table's labels, pooled from ``pooled_from``. + + A suppressed band may only sit inside the pooled top band, where its count + is left out and listed in ``ignored_suppressed``. + """ + + parsed = [] + for label, _, claimants, marker in tables.size: + match = _BAND_LABEL.match(label) + if match is None: + raise ValueError(f"Unexpected size band label {label!r}.") + parsed.append((int(match.group(1)), label, claimants, marker)) + lowers = [lower for lower, *_ in parsed] + if lowers != sorted(lowers) or len(set(lowers)) != len(lowers): + raise ValueError(f"Size bands are not in increasing order: {lowers}.") + if pooled_from not in lowers: + raise ValueError(f"{pooled_from} is not a published band edge {lowers}.") + bands = [] + for lower, label, claimants, marker in parsed: + if lower >= pooled_from: + continue + if claimants is None: + raise ValueError( + f"Size band {label!r} is suppressed ({marker}) below the pooled " + "band; no number is invented for it." + ) + bands.append(UKFirmEATakeupBand(lower, label, claimants, (label,), ())) + top = [row for row in parsed if row[0] >= pooled_from] + known = [row for row in top if row[2] is not None] + if not known: + raise ValueError("Every pooled size band is suppressed.") + bands.append( + UKFirmEATakeupBand( + lower=pooled_from, + label=f"{pooled_from}+", + hmrc_claimants=float(sum(row[2] for row in known)), + pooled=tuple(row[1] for row in top), + ignored_suppressed=tuple((row[1], row[3]) for row in top if row[2] is None), + ) + ) + return tuple(bands) + + +def uk_firm_employer_nic_proxy( + paybill: np.ndarray | pd.Series, + employees: np.ndarray | pd.Series, + paybill_below_threshold: np.ndarray | pd.Series | None = None, + employees_below_threshold: np.ndarray | pd.Series | None = None, +) -> np.ndarray: + """A PROXY for 2024-25 employer NIC before the allowance, in pounds. + + Rate times pay above the secondary threshold, summed over employees with + every employee's pay taken above it, or, given the below-threshold + columns, over the employees above it only. Floored at zero. Not + policyengine-uk's calculation. + """ + + pay = np.asarray(paybill, dtype=np.float64) + heads = np.asarray(employees, dtype=np.float64) + if (paybill_below_threshold is None) != (employees_below_threshold is None): + raise ValueError("Give both below-threshold columns or neither.") + if paybill_below_threshold is not None: + pay = pay - np.asarray(paybill_below_threshold, dtype=np.float64) + heads = heads - np.asarray(employees_below_threshold, dtype=np.float64) + above = np.maximum(pay - heads * UK_FIRM_EA_PROXY_SECONDARY_THRESHOLD_GBP, 0.0) + return UK_FIRM_EA_PROXY_SECONDARY_RATE * above + + +_REQUIRED = ( + "firm_employees", + "firm_claims_employment_allowance", + "firm_is_single_director_company", + "firm_is_public_body", + "firm_paybill", +) +_BELOW = ( + "firm_paybill_below_secondary_threshold", + "firm_employees_below_secondary_threshold", +) + + +def uk_firm_employment_allowance_eligible( + firms: pd.DataFrame, +) -> dict[str, np.ndarray]: + """Eligibility and its parts: ``eligible`` and one failing mask per reason. + + The reasons are ``no_rule_claim``, ``no_employees``, ``public_body``, + ``single_director_company`` and ``proxy_nic_over_limit``; they overlap. + """ + + missing = [column for column in _REQUIRED if column not in firms] + if missing: + raise ValueError(f"UK firm Employment Allowance take-up needs {missing}.") + employees = firms["firm_employees"].to_numpy(np.float64) + if np.any(employees < 0): + raise ValueError("UK firm firm_employees must be non-negative.") + below = ( + [firms[column].to_numpy() for column in _BELOW] + if all(column in firms for column in _BELOW) + else [None, None] + ) + nic = uk_firm_employer_nic_proxy( + firms["firm_paybill"].to_numpy(), employees, *below + ) + reasons = { + "no_rule_claim": ~firms["firm_claims_employment_allowance"].to_numpy(bool), + "no_employees": ~(employees >= 1), + "public_body": firms["firm_is_public_body"].to_numpy(bool), + "single_director_company": firms["firm_is_single_director_company"].to_numpy( + bool + ), + "proxy_nic_over_limit": ~(nic < UK_FIRM_EA_LIABILITY_LIMIT_GBP), + } + failing = np.zeros(len(firms), dtype=bool) + for mask in reasons.values(): + failing |= mask + return {"eligible": ~failing, "proxy_employer_nic_gbp": nic, **reasons} + + +@dataclass(frozen=True) +class UKFirmEATakeupDraw: + """The drawn flag, positional with the input frame, and diagnostics.""" + + claims: np.ndarray + eligible: np.ndarray + propensity: np.ndarray + diagnostics: Mapping[str, Any] + + +def _ordered_uniforms(ids: np.ndarray, seed: int) -> np.ndarray: + ordered = np.sort(ids, kind="stable") + if np.any(ordered[1:] == ordered[:-1]): + raise ValueError("UK firm ids must be unique for the take-up draw.") + rng = np.random.default_rng( + np.random.SeedSequence([int(seed), UK_FIRM_EA_TAKEUP_SEED_TAG]) + ) + uniforms = np.empty(len(ids), dtype=np.float64) + uniforms[np.argsort(ids, kind="stable")] = rng.random(len(ids)) + return uniforms + + +def draw_uk_firm_employment_allowance_takeup( + firms: pd.DataFrame, + tables: UKFirmEATakeupTables, + *, + seed: int, + id_column: str = "firm_id", + weight_column: str = "firm_weight", +) -> UKFirmEATakeupDraw: + """Draw each eligible firm's claim at its size band's propensity.""" + + for column in (id_column, weight_column): + if column not in firms: + raise ValueError(f"UK firm Employment Allowance take-up needs {column!r}.") + weight = firms[weight_column].to_numpy(np.float64) + if np.any(~np.isfinite(weight)) or np.any(weight < 0): + raise ValueError("UK firm weights must be finite and non-negative.") + parts = uk_firm_employment_allowance_eligible(firms) + eligible = parts["eligible"] + bands = uk_firm_employment_allowance_takeup_bands(tables) + edges = np.array([band.lower for band in bands], dtype=np.float64) + employees = firms["firm_employees"].to_numpy(np.float64) + band = np.searchsorted(edges, employees, side="right") - 1 + in_band = eligible & (band >= 0) + band_propensity = np.zeros(len(bands), dtype=np.float64) + band_rows = [] + for index, spec in enumerate(bands): + members = in_band & (band == index) + weighted = float(weight[members].sum()) + if weighted > 0: + band_propensity[index] = min(1.0, spec.hmrc_claimants / weighted) + band_rows.append( + { + "band": spec.label, + "lower_employees": spec.lower, + "pooled_hmrc_bands": list(spec.pooled), + "ignored_suppressed": [list(item) for item in spec.ignored_suppressed], + "hmrc_claimants": spec.hmrc_claimants, + "weighted_eligible": weighted, + "eligible_rows": int(members.sum()), + "propensity": float(band_propensity[index]), + "capped": weighted < spec.hmrc_claimants, + "cap_shortfall": max(0.0, spec.hmrc_claimants - weighted), + } + ) + propensity = np.where(in_band, band_propensity[np.clip(band, 0, None)], 0.0) + uniforms = _ordered_uniforms(firms[id_column].to_numpy(), seed) + claims = in_band & (uniforms < propensity) + for index, row in enumerate(band_rows): + row["weighted_claimants"] = float(weight[claims & (band == index)].sum()) + rule = ~parts["no_rule_claim"] + switched_off = { + reason: float(weight[rule & parts[reason]].sum()) + for reason in ( + "no_employees", + "public_body", + "single_director_company", + "proxy_nic_over_limit", + ) + } + diagnostics = { + "status": UK_FIRM_EA_TAKEUP_STATUS, + "seed": int(seed), + "seed_tag": UK_FIRM_EA_TAKEUP_SEED_TAG, + "proxy_nic_uses_below_threshold_columns": all(c in firms for c in _BELOW), + "bands": band_rows, + "hmrc_band_sum": float(sum(band.hmrc_claimants for band in bands)), + "hmrc_total": tables.total, + "weighted_rule_claimants": float(weight[rule].sum()), + "weighted_eligible": float(weight[in_band].sum()), + "weighted_claimants": float(weight[claims].sum()), + "rule_claimants_ineligible_weighted": switched_off, + "rule_claimants_ineligible_weighted_total": float( + weight[rule & ~eligible].sum() + ), + "sha256": dict(tables.sha256), + } + return UKFirmEATakeupDraw( + claims=claims, eligible=eligible, propensity=propensity, diagnostics=diagnostics + ) + + +def assign_uk_firm_employment_allowance_takeup( + firms: pd.DataFrame, + tables: UKFirmEATakeupTables, + *, + seed: int, + id_column: str = "firm_id", + weight_column: str = "firm_weight", +) -> tuple[pd.DataFrame, Mapping[str, Any]]: + """``firms`` with the drawn ``firm_claims_employment_allowance``, and diagnostics.""" + + draw = draw_uk_firm_employment_allowance_takeup( + firms, tables, seed=seed, id_column=id_column, weight_column=weight_column + ) + return firms.assign(firm_claims_employment_allowance=draw.claims), draw.diagnostics + + +def _region_names(code: str) -> str | None: + """policyengine-uk ``Region`` name for an HMRC region code, if any.""" + + return UK_REGION_TIER_ENUM.get(UK_LADDER_NATION_REGION_CODES.get(code, code)) + + +def _compare( + labels: np.ndarray, + weight: np.ndarray, + rows: Sequence[tuple[str, str, float | None, str | None]], + mapping: Mapping[str, str], +) -> dict[str, Any]: + by_code: dict[str, float] = {} + unmapped: dict[str, float] = {} + for label in pd.unique(labels): + mass = float(weight[labels == label].sum()) + code = mapping.get(str(label)) + if code is None: + unmapped[str(label)] = mass + else: + by_code[code] = by_code.get(code, 0.0) + mass + out = [] + for code, description, claimants, marker in rows: + model = by_code.get(code, 0.0) + out.append( + { + "hmrc_code": code, + "description": description, + "model_weighted_claimants": model, + "hmrc_claimants": claimants, + "hmrc_marker": marker, + "ratio": model / claimants if claimants else None, + } + ) + return { + "rows": out, + "unmapped_model_labels": unmapped, + "unmapped_hmrc_codes": sorted( + code for code, *_ in rows if code not in set(mapping.values()) + ), + } + + +def uk_firm_employment_allowance_takeup_held_out( + firms: pd.DataFrame, + claims: np.ndarray, + tables: UKFirmEATakeupTables, + *, + weight_column: str = "firm_weight", +) -> dict[str, Any]: + """Weighted drawn claimants by SIC section and region beside HMRC's. + + Held out: the draw never reads these tables. ``firm_sic_section`` letters + map to HMRC's sections, with B, D, E, O and U onto HMRC's pooled + ``B,D,E,O,U``; ``UNKNOWN`` is unmapped (HMRC apportioned its unknown + sectors). ``firm_region`` names map through the region's GSS code, with + HMRC's ``W99999999``, ``S99999999`` and ``N99999999`` taken as Wales, + Scotland and Northern Ireland. A table whose column is absent is skipped. + """ + + claims = np.asarray(claims, dtype=bool) + weight = np.where(claims, firms[weight_column].to_numpy(np.float64), 0.0) + out: dict[str, Any] = {"model_weighted_claimants": float(weight.sum())} + if "firm_sic_section" in firms: + sector_map = { + letter: code for code, *_ in tables.sector for letter in code.split(",") + } + out["sector"] = _compare( + firms["firm_sic_section"].astype(str).to_numpy(object), + weight, + tables.sector, + sector_map, + ) + if "firm_region" in firms: + region_map = { + name: code + for code, *_ in tables.region + if (name := _region_names(code)) is not None + } + out["region"] = _compare( + firms["firm_region"].astype(str).to_numpy(object), + weight, + tables.region, + region_map, + ) + return out diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_empty_property.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_empty_property.py new file mode 100644 index 0000000000..7b320447ea --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_empty_property.py @@ -0,0 +1,207 @@ +"""UK firm empty property: published MHCLG figures, read but not assigned. + +policyengine-uk reads two business rates inputs for empty property in +England: + +- ``firm_property_occupied`` (bool, default true): whether the firm's + property is occupied throughout the year. An unoccupied property is + treated as empty all year and gets the empty property exemption but no + other relief; +- ``firm_months_empty`` (int, default 0): months the property had already + been continuously empty at the start of the year. The exemption is gross + rates times ``max(3 - months, 0) / 12`` (6 months for + ``firm_is_industrial_property``), or the whole year when rateable value is + below the £2,900 small property threshold. + +Both stay unset (policyengine-uk's defaults: every property occupied). This +module only reads MHCLG's *National non-domestic rates collected by councils +in England* figures, extracted by +``tools/extract_uk_firm_empty_property_tables.py`` to +``tests/fixtures/uk/firm_empty_property_2024_25/``, and reports them through +``uk_firm_empty_property_published_figures``. The figures do not support an +assignment: + +- they are a point-in-time stock (hereditaments in receipt of empty premises + relief on 31 December), while policyengine-uk's flag makes a property + empty for the whole year; empties past their exemption pay full rates and + appear in no published count; +- an empty hereditament is not a trading firm: its ratepayer is the owner, + who may hold it outside any business the generator draws; +- no source gives empty durations, so ``firm_months_empty`` could only be + tuned to a relief total, not estimated; +- no source gives the rateable value of empty property or empty shares by + property type. +""" + +from __future__ import annotations + +import hashlib +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path +from types import MappingProxyType +from typing import Any + +import numpy as np +import pandas as pd + +UK_FIRM_EMPTY_HEREDITAMENTS_FILE = "mhclg_nndr1_empty_hereditaments.csv" +UK_FIRM_EMPTY_RELIEF_FILE = "mhclg_nndr1_empty_relief_value.csv" +UK_FIRM_EMPTY_NNDR3_FILE = "mhclg_nndr3_2024_25.csv" +UK_FIRM_EMPTY_FILES = ( + UK_FIRM_EMPTY_HEREDITAMENTS_FILE, + UK_FIRM_EMPTY_RELIEF_FILE, + UK_FIRM_EMPTY_NNDR3_FILE, +) +UK_FIRM_EMPTY_SNAPSHOT = "2024-12-31" +UK_FIRM_EMPTY_RELIEF_YEAR = "2024-25" +#: The relief categories policyengine-uk's exemption could represent: empty +#: property above the exemption threshold, industrial and non-industrial. +UK_FIRM_EMPTY_MODELLED_HEREDITAMENTS = ("hdit_mr_emptyind", "hdit_mr_emptyabove") +UK_FIRM_EMPTY_MODELLED_RELIEF = ("value_emptyind", "value_emptyabove") +#: Status of ``firm_property_occupied`` and ``firm_months_empty``. +UK_FIRM_EMPTY_STATUS = "not_set" +UK_FIRM_EMPTY_GAP = ( + "firm_property_occupied and firm_months_empty stay unset: MHCLG counts " + "hereditaments in receipt of empty relief on one date, policyengine-uk's " + "flag is for the whole year, empty hereditaments are not trading firms, " + "and months empty could only be calibrated to a relief total" +) + + +@dataclass(frozen=True) +class UKFirmEmptyPropertySource: + #: snapshot date -> variable -> England hereditaments. + hereditaments: Mapping[str, Mapping[str, float]] + #: forecast year -> variable -> England relief (£, positive). + relief_gbp: Mapping[str, Mapping[str, float]] + #: NNDR3 2024-25 item -> value in its published unit. + nndr3: Mapping[str, float] + sha256: Mapping[str, str] + + +def _csv(directory: Path, name: str) -> tuple[pd.DataFrame, str]: + path = directory / name + payload = path.read_bytes() + return pd.read_csv(path, dtype=str, keep_default_na=False), hashlib.sha256( + payload + ).hexdigest() + + +def _float(value: str, label: str) -> float: + try: + number = float(value) + except ValueError: + raise ValueError(f"MHCLG {label} {value!r} is not a number.") from None + if not np.isfinite(number): + raise ValueError(f"MHCLG {label} must be finite.") + return number + + +def read_uk_firm_empty_property_source( + path: str | Path, +) -> UKFirmEmptyPropertySource: + """Read the extracted MHCLG CSVs from a fixture directory.""" + + directory = Path(path) + counts, counts_sha = _csv(directory, UK_FIRM_EMPTY_HEREDITAMENTS_FILE) + relief, relief_sha = _csv(directory, UK_FIRM_EMPTY_RELIEF_FILE) + nndr3, nndr3_sha = _csv(directory, UK_FIRM_EMPTY_NNDR3_FILE) + hereditaments: dict[str, dict[str, float]] = {} + for record in counts.to_dict("records"): + value = _float(record["england_hereditaments"], record["variable"]) + if value < 0: + raise ValueError(f"MHCLG {record['variable']} must be non-negative.") + hereditaments.setdefault(record["snapshot_date"], {})[record["variable"]] = ( + value + ) + values: dict[str, dict[str, float]] = {} + for record in relief.to_dict("records"): + # The 2025-26 edition prints relief with a minus sign. + value = abs(_float(record["england_value_gbp"], record["variable"])) + values.setdefault(record["forecast_year"], {})[record["variable"]] = value + items = { + record["item"]: _float(record["value"], record["item"]) + for record in nndr3.to_dict("records") + } + if UK_FIRM_EMPTY_SNAPSHOT not in hereditaments: + raise ValueError(f"MHCLG counts lack the {UK_FIRM_EMPTY_SNAPSHOT} snapshot.") + if UK_FIRM_EMPTY_RELIEF_YEAR not in values: + raise ValueError(f"MHCLG relief lacks {UK_FIRM_EMPTY_RELIEF_YEAR}.") + for snapshot, row in hereditaments.items(): + parts = sum(v for k, v in row.items() if k != "hdit_mr_empty") + if parts != row.get("hdit_mr_empty"): + raise ValueError(f"MHCLG {snapshot} empty categories do not sum.") + return UKFirmEmptyPropertySource( + hereditaments=MappingProxyType( + {k: MappingProxyType(v) for k, v in hereditaments.items()} + ), + relief_gbp=MappingProxyType( + {k: MappingProxyType(v) for k, v in values.items()} + ), + nndr3=MappingProxyType(items), + sha256=MappingProxyType( + { + UK_FIRM_EMPTY_HEREDITAMENTS_FILE: counts_sha, + UK_FIRM_EMPTY_RELIEF_FILE: relief_sha, + UK_FIRM_EMPTY_NNDR3_FILE: nndr3_sha, + } + ), + ) + + +def uk_firm_empty_property_published_figures( + source: UKFirmEmptyPropertySource, +) -> dict[str, Any]: + """The published England stock and relief figures, with the gap stated. + + Hereditaments in receipt of empty relief on 31 December 2024 (total and + the two above-threshold categories) and their share of the list at 30 + September; empty relief in 2024-25 (NNDR1 forecast, total and the two + categories, and NNDR3 outturn) and its share of gross rates payable. + """ + + counts = source.hereditaments[UK_FIRM_EMPTY_SNAPSHOT] + relief = source.relief_gbp[UK_FIRM_EMPTY_RELIEF_YEAR] + on_list = 1000.0 * source.nndr3["hereditaments_30_sept"] + gross = 1e6 * source.nndr3["gross_rates_payable"] + outturn = 1e6 * source.nndr3["empty_premises_relief"] + above = float(sum(counts[v] for v in UK_FIRM_EMPTY_MODELLED_HEREDITAMENTS)) + return { + "status": UK_FIRM_EMPTY_STATUS, + "gap": UK_FIRM_EMPTY_GAP, + "snapshot": UK_FIRM_EMPTY_SNAPSHOT, + "empty_relief_hereditaments": counts["hdit_mr_empty"], + "empty_relief_hereditaments_above_threshold": above, + "hereditaments_on_list": on_list, + "empty_relief_share_of_hereditaments": counts["hdit_mr_empty"] / on_list, + "above_threshold_share_of_hereditaments": above / on_list, + "aggregate_rateable_value_gbp": 1e6 + * source.nndr3["aggregate_rateable_value_30_sept"], + "relief_year": UK_FIRM_EMPTY_RELIEF_YEAR, + "empty_relief_forecast_gbp": relief["value_empty"], + "empty_relief_above_threshold_forecast_gbp": float( + sum(relief[v] for v in UK_FIRM_EMPTY_MODELLED_RELIEF) + ), + "empty_relief_outturn_gbp": outturn, + "gross_rates_payable_gbp": gross, + "empty_relief_share_of_gross_rates": outturn / gross, + "sha256": dict(source.sha256), + } + + +__all__ = [ + "UK_FIRM_EMPTY_FILES", + "UK_FIRM_EMPTY_GAP", + "UK_FIRM_EMPTY_HEREDITAMENTS_FILE", + "UK_FIRM_EMPTY_MODELLED_HEREDITAMENTS", + "UK_FIRM_EMPTY_MODELLED_RELIEF", + "UK_FIRM_EMPTY_NNDR3_FILE", + "UK_FIRM_EMPTY_RELIEF_FILE", + "UK_FIRM_EMPTY_RELIEF_YEAR", + "UK_FIRM_EMPTY_SNAPSHOT", + "UK_FIRM_EMPTY_STATUS", + "UKFirmEmptyPropertySource", + "read_uk_firm_empty_property_source", + "uk_firm_empty_property_published_figures", +] 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..1153341682 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,15 +9,33 @@ 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 import json import logging +import math import subprocess from collections.abc import Iterable, Mapping from dataclasses import dataclass, field, replace @@ -31,15 +49,34 @@ 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_bpe_turnover import ( + OPEN_BAND_LOWER_K, + draw_uk_firm_open_band_turnover, + fit_uk_firm_employment_turnover_rho, + repair_uk_firm_employment_turnover, + uk_firm_open_band_tail_parameters, + uk_firm_open_band_uniforms, ) -from microcosm.calibrate.solve import ( - _torch_constraint_matrix as _calibrate_torch_constraint_matrix, +from microcosm.build.uk_runtime.firm_rules import ( + LegacyVATEvaluatorRules, + UKFirmRules, + align_rule_outputs, + rule_period_for_vintage, +) +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 +206,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 +226,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), @@ -209,6 +254,130 @@ class UKFirmLedgerTargetProfile: "250+": (250.0, 2000.0, 400.0), } +#: The legacy draw for the open 250+ band is the paper's lognormal (median +#: 400, log-sd 0.8) clamped to the band's ``[250, 2000]`` above, so no firm +#: exceeds 2,000 staff. Setting ``UKFirmGenerationConfig.large_employment_mean`` +#: (for example to :data:`LARGE_EMPLOYMENT_MEAN`) replaces the clamp with a +#: truncated Pareto on ``[250, LARGE_EMPLOYMENT_CAP]`` with that mean. +#: +#: Mean headcount of a private-sector business with 250 or more employees: +#: 11,115 thousand employment over 8,250 businesses, DBT "Business +#: population estimates 2024" detailed tables, Table 1 (UK private sector, +#: start 2024; rows 250-499, 500-999 and 1000 or more). The figures and their +#: provenance are fixtured in ``tests/fixtures/uk/firm_2024_25_size/``. +LARGE_EMPLOYMENT_MEAN = 11_115_000.0 / 8_250.0 +#: Upper limit of the Pareto 250+ headcount draw. It sits above the largest +#: UK private employers' headcounts, so it bounds the draw's variance without +#: acting as the legacy clamp at 2,000. +LARGE_EMPLOYMENT_CAP = 500_000.0 + + +#: Shape bracket of the Pareto bisection. The truncated mean falls as the +#: shape rises, so the bracket's ends bound the means a shape can reach. +LARGE_EMPLOYMENT_SHAPE_BRACKET = (0.05, 20.0) + + +def _large_employment_truncated_mean(shape: float, lower: float, cap: float) -> float: + tail = (lower / cap) ** shape + if abs(shape - 1.0) < 1e-9: + return lower * math.log(cap / lower) / (1.0 - tail) + return ( + shape + * lower**shape + * (cap ** (1.0 - shape) - lower ** (1.0 - shape)) + / ((1.0 - shape) * (1.0 - tail)) + ) + + +def large_employment_mean_range( + lower: float = 250.0, cap: float = LARGE_EMPLOYMENT_CAP +) -> tuple[float, float]: + """The 250+ means the Pareto draw can hit exactly, ``(smallest, largest)``. + + They are the truncated means at the ends of + ``LARGE_EMPLOYMENT_SHAPE_BRACKET``; a mean outside them would make the + bisection saturate at a bracket end and miss the mean silently. + """ + + low_shape, high_shape = LARGE_EMPLOYMENT_SHAPE_BRACKET + return ( + _large_employment_truncated_mean(high_shape, lower, cap), + _large_employment_truncated_mean(low_shape, lower, cap), + ) + + +def large_employment_pareto_shape( + mean: float = LARGE_EMPLOYMENT_MEAN, + lower: float = 250.0, + cap: float = LARGE_EMPLOYMENT_CAP, +) -> float: + """Shape of the Pareto on ``[lower, cap]`` whose mean is ``mean``. + + The truncated mean falls as the shape rises, so bisection on + ``LARGE_EMPLOYMENT_SHAPE_BRACKET`` converges; the shape-one case is its + logarithmic limit. A mean outside ``large_employment_mean_range`` raises + ``ValueError`` rather than saturating at a bracket end. + """ + + if not lower < mean < cap: + raise ValueError( + f"Large-firm mean {mean!r} must lie strictly inside ({lower}, {cap})." + ) + smallest, largest = large_employment_mean_range(lower, cap) + if not smallest <= mean <= largest: + raise ValueError( + f"Large-firm mean {mean!r} is outside [{smallest:,.2f}, " + f"{largest:,.2f}], the means a Pareto shape in " + f"{LARGE_EMPLOYMENT_SHAPE_BRACKET} can reach on [{lower}, {cap}]." + ) + + low, high = LARGE_EMPLOYMENT_SHAPE_BRACKET + for _ in range(200): + middle = 0.5 * (low + high) + if _large_employment_truncated_mean(middle, lower, cap) > mean: + low = middle + else: + high = middle + return 0.5 * (low + high) + + +def large_employment_slice_means( + masses: np.ndarray, + mean: float = LARGE_EMPLOYMENT_MEAN, + lower: float = 250.0, + cap: float = LARGE_EMPLOYMENT_CAP, +) -> np.ndarray: + """Mean headcount of consecutive probability slices of the large-firm draw. + + ``masses`` are the slices' non-negative sizes, lowest quantiles first; + they are rescaled to sum to one. Each slice gets the mean of the + truncated Pareto on ``[lower, cap]`` with mean ``mean`` over its quantile + range, so the mass-weighted mean of the result is ``mean`` exactly. A + zero-mass slice gets the quantile at its position. + """ + + masses = np.asarray(masses, dtype=np.float64) + if masses.size == 0: + return np.empty(0, dtype=np.float64) + if np.any(masses < 0) or not masses.sum() > 0: + raise ValueError("Large-firm slice masses must be non-negative, not all zero.") + shape = large_employment_pareto_shape(mean, lower, cap) + span = 1.0 - (lower / cap) ** shape + exponent = 1.0 - 1.0 / shape + cumulative = np.concatenate([[0.0], np.cumsum(masses)]) / masses.sum() + cumulative[-1] = 1.0 + edges = 1.0 - cumulative * span + if abs(exponent) < 1e-12: + integral = np.log(edges) / span + else: + integral = edges**exponent / (exponent * span) + width = np.diff(cumulative) + quantile = lower * edges[:-1] ** (-1.0 / shape) + with np.errstate(divide="ignore", invalid="ignore"): + means = lower * (integral[:-1] - integral[1:]) / width + return np.where(width > 0, means, quantile) + + NEGATIVE_LIABILITY_SECTORS = { 1, 3, @@ -230,6 +399,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 +554,46 @@ 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. + + ``large_employment_mean`` (headcount) replaces the paper's 250+ draw, + clamped at 2,000 staff, with a truncated Pareto on + ``[250, LARGE_EMPLOYMENT_CAP]`` with that base-weighted mean over the + ONS-frame rows; :data:`LARGE_EMPLOYMENT_MEAN` is DBT's private-sector + mean. Out-of-frame rows (the HMRC zero-turnover traders) then draw a + headcount below 250, so every 250+ firm is a frame firm. ``None`` (the + default) keeps the paper's draw, in which they can reach 250+. + + ``bpe_turnover`` (a ``firm_headcount.UKFirmBPESource``; ``None``, the + default, keeps the paper's draws) switches on the opt-in BPE turnover + fix (``firm_bpe_turnover.py``): the open ONS turnover band takes a + truncated Pareto tail pinned to DBT BPE 2025 total turnover instead of + the log-uniform draw capped at 50 million pounds, and frame rows' + employment is re-paired with turnover inside each SIC division by a + Gaussian copula whose ``rho`` is fitted to BPE turnover by employment + band. Both act before the solve and draw nothing from the generator's + stream; on an unthinned build its draws are unchanged, while a thinned + build stratifies on the new turnover and so keeps different rows. + + ``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 +605,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 +613,54 @@ 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 + large_employment_mean: float | None = None + bpe_turnover: Any = 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 +678,22 @@ 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.") + if self.large_employment_mean is not None: + smallest, largest = large_employment_mean_range() + if not smallest <= float(self.large_employment_mean) <= largest: + raise ValueError( + f"large_employment_mean must lie in [{smallest:,.2f}, " + f"{largest:,.2f}], the means the Pareto draw can hit " + "exactly." + ) def _vat_rule_period(data_vintage: str) -> dict[str, str]: @@ -446,14 +741,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 +766,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 +824,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 +838,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) @@ -534,6 +850,7 @@ class UKFirmGenerationResult: calibration: UKFirmCalibrationResult target_diagnostics: pd.DataFrame config: UKFirmGenerationConfig + bpe_turnover: Mapping[str, Any] | None = None def read_uk_firm_source_data( @@ -729,6 +1046,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 +1054,161 @@ 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), + bpe_turnover: dict[str, Any] | None = None + if cfg.bpe_turnover is not None: + frame_turnover, bpe_turnover = _bpe_open_band_tail( + frame_sic, frame_turnover, data, hmrc_bands, cfg + ) + 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 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, + weights=base_weights, + large_employment_mean=cfg.large_employment_mean, + in_frame=frame_mask, ) - 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, + employment_np = employment.detach().cpu().numpy() + 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) + if cfg.bpe_turnover is not None and bpe_turnover is not None: + in_frame_np = _as_numpy(frame_mask, bool) + fit = fit_uk_firm_employment_turnover_rho( + sic_np, + turnover_np, + employment_np, + in_frame_np, + _as_numpy(base_weights, np.float64), + cfg.bpe_turnover, + seed=cfg.seed, + firm_ids=firm_ids, + ) + employment_np = repair_uk_firm_employment_turnover( + sic_np, + turnover_np, + employment_np, + in_frame_np, + rho=fit.rho, + seed=cfg.seed, + firm_ids=firm_ids, + ) + bpe_turnover["rho"] = fit.rho + bpe_turnover["rho_sse"] = fit.sse + bpe_turnover["rho_at_bound"] = fit.at_bound + bpe_turnover["rho_fit"] = fit.table.to_dict(orient="records") + employment_band_indices = employment_band_index_array(employment_np) + 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, ) - employment_band_indices = torch.tensor( - [_employment_band_index(value.item()) for value in base_employment], - dtype=torch.long, - device=cfg.device, + 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, + propensity=propensity, + frame_mask=frame_mask, + vat_liability_if_registered_k=liability_if_registered_k, ) - final_vat_liability = calculate_vat_liability_values( + 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, @@ -818,6 +1216,49 @@ def generate_uk_firm_population( calibration=calibration, target_diagnostics=diagnostics, config=cfg, + bpe_turnover=bpe_turnover, + ) + + +def _bpe_open_band_tail( + frame_sic: Tensor, + frame_turnover: Tensor, + data: UKFirmSourceData, + hmrc_bands: Mapping[str, float], + cfg: UKFirmGenerationConfig, +) -> tuple[Tensor, dict[str, Any]]: + """Frame turnover with the open band redrawn on the BPE-pinned tail.""" + + sic = frame_sic.detach().cpu().numpy().astype(np.int64) + turnover = frame_turnover.detach().cpu().numpy().astype(np.float64) + open_band = turnover >= OPEN_BAND_LOWER_K + tail = uk_firm_open_band_tail_parameters( + data.ons_turnover, + hmrc_bands, + cfg.bpe_turnover, + sic=sic, + turnover_k=turnover, + in_frame=np.ones(len(sic), dtype=bool), + open_band=open_band, + ) + uniforms = uk_firm_open_band_uniforms(turnover[open_band]) + section_k = np.isin(sic[open_band], (64, 65, 66)) + turnover[open_band] = draw_uk_firm_open_band_turnover( + uniforms, tail.alpha, tail.cap_k, strata=section_k + ) + record = { + "alpha": tail.alpha, + "cap_k": tail.cap_k, + "target_mean_k": tail.target_mean_k, + "p_over_10m": tail.p_over_10m, + "model_p_over_10m": tail.model_p_over_10m, + "open_band_rows": int(open_band.sum()), + } + return ( + torch.tensor( + turnover, dtype=frame_turnover.dtype, device=frame_turnover.device + ), + record, ) @@ -852,7 +1293,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 +1320,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 +1345,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 +1358,243 @@ def generate_input_values( def assign_employment( - n_firms: int, + sic_codes: Tensor, ons_employment: pd.DataFrame, device: str = "cpu", + weights: np.ndarray | Tensor | None = None, + large_employment_mean: float | None = None, + in_frame: np.ndarray | Tensor | None = None, ) -> 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. + + By default the open 250+ band keeps the paper's lognormal draw clamped + to ``[250, 2000]``. With ``large_employment_mean`` it is not clamped: the + band's rows, ranked by the same lognormal draw (so the generator's + stream is unchanged), take the means of consecutive slices of a + truncated Pareto on ``[250, LARGE_EMPLOYMENT_CAP]`` with that mean, each + slice's probability proportional to the row's ``weights`` (equal when + omitted). The band's weighted mean headcount is then that mean, up to + rounding. + + ``in_frame`` (every row when omitted) marks the ONS-frame rows and is + read only with ``large_employment_mean``. The published 250+ mean + describes businesses in the frame, so a row outside it whose band draw + is 250+ takes no slice of the tail: its lognormal draw instead picks a + headcount below 250 from its sector's shares of the smaller bands + (:func:`_employment_below_large_band`). The 250+ band then holds frame + rows only, and it is their weighted mean that equals the mean. Neither + option draws from the generator beyond the default's draws. + """ + 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() + 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, + ) + + frame: Tensor | None = None + if large_employment_mean is not None and in_frame is not None: + frame = torch.as_tensor( + _as_numpy(in_frame, bool), dtype=torch.bool, device=device + ) + if len(frame) != n_firms: + raise ValueError("in_frame must have one entry per firm.") + result = torch.empty(n_firms, dtype=torch.float32, device=device) + large_idx: list[Tensor] = [] + large_scores: list[Tensor] = [] + 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: - 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) + 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 == "250+": + # The paper's lognormal draw. With a large-employment mean it + # only ranks the band's rows, keeping the generator's stream + # unchanged; their headcounts are set after the loop. + log_mean = torch.log(torch.tensor(float(midpoint), device=device)) + scores = torch.normal(log_mean, 0.8, (len(out_idx),), device=device) + if large_employment_mean is None: + result[out_idx] = torch.clamp(scores.exp(), lower, upper).round() + elif frame is None: + large_idx.append(out_idx) + large_scores.append(scores) + else: + inside = frame[out_idx] + large_idx.append(out_idx[inside]) + large_scores.append(scores[inside]) + outside = out_idx[~inside] + if len(outside): + result[outside] = torch.as_tensor( + _employment_below_large_band( + scores[~inside].detach().cpu().numpy(), + float(log_mean), + 0.8, + probs.detach().cpu().numpy(), + national.detach().cpu().numpy(), + ), + dtype=torch.float32, + device=device, + ) + continue + if band == "0-4": + values = torch.randint(1, 5, (len(out_idx),), device=device).float() + else: + values = torch.randint( + int(lower), int(upper) + 1, (len(out_idx),), device=device + ).float() + result[out_idx] = values + if large_idx and sum(len(rows) for rows in large_idx): + # Ranked rows take consecutive weight-sized slices of a truncated + # Pareto fitted to the published mean, so the band's weighted mean + # matches the source without sampling noise from the heavy tail. + lower = ONS_EMPLOYMENT_BANDS["250+"][0] + rows = torch.cat(large_idx) + order = torch.argsort(torch.cat(large_scores), stable=True) + ranked = rows[order] + if weights is None: + masses = np.ones(len(ranked), dtype=np.float64) + else: + masses = _as_numpy(weights, np.float64)[ranked.cpu().numpy()] + slices = large_employment_slice_means( + masses, mean=float(large_employment_mean), lower=lower + ) + result[ranked] = torch.as_tensor( + np.round(slices), dtype=torch.float32, device=device + ) + return result -def assign_vat_flags( - turnover_values: Tensor, - hmrc_bands: dict[str, float], - config: UKFirmGenerationConfig, -) -> Tensor: - """Assign VAT-registration flags.""" +def _employment_below_large_band( + scores: np.ndarray, + log_mean: float, + log_sd: float, + shares: np.ndarray, + fallback_shares: np.ndarray, +) -> np.ndarray: + """Headcounts below the open 250+ band for rows outside the ONS frame. + + ``scores`` are the rows' normal draws on the log scale (mean + ``log_mean``, sd ``log_sd``). Each row's quantile of that normal picks + one of the closed bands by ``shares`` (band shares in + :data:`EMPLOYMENT_BANDS` order; the open band's share is dropped and + the rest renormalised) and a whole headcount inside it, so the result + is deterministic and consumes no random draws. ``fallback_shares`` + serve when ``shares`` has no mass below the open band, and equal shares + when neither has. + """ - 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 + closed_bands = list(ONS_EMPLOYMENT_BANDS.values())[:-1] + mass = np.asarray(shares, dtype=np.float64)[: len(closed_bands)] + if not mass.sum() > 0: + mass = np.asarray(fallback_shares, dtype=np.float64)[: len(closed_bands)] + if not mass.sum() > 0: + mass = np.ones(len(closed_bands), dtype=np.float64) + mass = mass / mass.sum() + standard = (np.asarray(scores, dtype=np.float64) - log_mean) / log_sd + quantile = np.asarray( + [0.5 * (1.0 + math.erf(value / math.sqrt(2.0))) for value in standard], + dtype=np.float64, + ) + upper_edges = np.cumsum(mass) + last = int(np.flatnonzero(mass > 0)[-1]) + band = np.minimum(np.searchsorted(upper_edges, quantile, side="right"), last) + lower_edges = np.concatenate([[0.0], upper_edges[:-1]]) + position = np.clip((quantile - lower_edges[band]) / mass[band], 0.0, 1.0) + lowest = np.asarray([lower for lower, _, _ in closed_bands])[band] + highest = np.asarray([upper for _, upper, _ in closed_bands])[band] + return np.minimum(lowest + np.floor(position * (highest - lowest + 1.0)), highest) + + +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. + """ + + 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 +1603,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 +1612,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. + + ``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. + """ - _, 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) + 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 +1777,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 +1837,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 +1929,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 +1977,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 +2103,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 +2172,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 +2194,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 +2217,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 +2580,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_headcount.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_headcount.py new file mode 100644 index 0000000000..3d226af61a --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_headcount.py @@ -0,0 +1,956 @@ +"""UK firm headcount: working proprietors, employees and a small-firm redraw. + +The experimental UK firm generator draws ``employment`` from the ONS *UK +business: activity, size and location* employment bands. ONS employment is +employees plus working proprietors, and inside the ONS "0-4" band the +generator spreads headcount evenly over 1 to 4 whatever the legal status. This +module adds three opt-in pieces, none of which runs by default: + +- ``uk_firm_assumed_proprietors`` and ``uk_firm_employees`` split employment + into working proprietors and employees by ONS legal status: a sole + proprietorship (status 2) has one working proprietor, an ordinary + partnership (status 3) two (``min(2, employment)``), a company (status 1) + none, because the DBT *Business population estimates* (BPE) count a + company's working directors as PAYE employees; public corporations, central + and local government and non-profit bodies (statuses 4 to 7) none. These are + assumptions: a partnership may have more than two partners and a sole + trader's spouse may work unpaid. ``uk_firm_employee_size_bands`` labels + employees with the BPE employee size bands (``UK_FIRM_EMPLOYEE_SIZE_BANDS``). +- ``redraw_uk_firm_small_headcount`` redraws ``employment`` for company, sole + proprietorship and partnership rows in the ONS 0-4 band (employment 1 to 4) + from P(employment = k | legal status, 0-4 band) built from BPE 2025 Table 3 + (UK private sector by legal status and employee size band, start 2025). + Rows of any other status or band are left alone, and no row leaves its + band. +- ``uk_firm_small_headcount_diagnostics`` and + ``uk_firm_bpe_size_band_reconciliation`` report what the redraw did and how + modelled firms, employment and employees by BPE employee band compare with + BPE Table 2 (private sector and whole economy). + +How the target is built (``uk_firm_small_headcount_targets``). Each BPE Table +3 row of *registered* businesses ("With no employees (registered)", "1", +"2 to 4"; the unregistered row is excluded because the ONS frame holds VAT- or +PAYE-registered enterprises only) is turned into an employment support by the +proprietor assumption: + +- companies: the no-employee row is employment 1 (BPE notes that a company + whose one PAYE employee is its working director is counted with no + employees); "2 to 4" is employment 2 to 4; the "1" row is empty by that + same reclassification; +- sole proprietorships: employees plus one, so no-employee is 1, "1" is 2 and + "2 to 4" is 3 to 5; +- partnerships: employees plus two, so no-employee is 2, "1" is 3 and + "2 to 4" is 4 to 6. A partnership never has employment 1 under the + two-partner assumption, so its k = 1 share is zero. + +A row whose support has several values is spread over it by a truncated +geometric distribution, p(j) proportional to ``ratio ** (j - low)``, whose +mean equals the row's published mean employment (employment thousands times +1,000 over business number; BPE employment already counts working +proprietors, so the proprietor assumption shifts the support, not the mean). +The ratio is solved numerically and may exceed one. A mean outside the open +support is clipped just inside it and the row is flagged ``clipped``. The +fitted distribution is then cut to the ONS band (employment 1 to 4) and only +the in-band part of the row's business count is kept: a sole trader with four +employees, or a partnership with three or four, has employment 5 or 6 and +belongs to the ONS 5-9 band, so that share (``in_band_share`` below one in the +fit table) is dropped and disclosed rather than piled onto k = 4. + +Caveats a caller should know before opting in: + +- the BPE Table 3 split of small firms by legal status becomes an in-sample + fact: a later comparison of the redrawn frame with that table is not an + independent check; +- BPE describes the business population at the start of 2025; the ONS band + counts are the generator's own vintage, so the two can disagree on the + number of firms in a band. The redraw keeps every row's band and weight and + changes only the shape inside the 0-4 band; +- the draw ignores industry and turnover, and the paybill, employees and + any column computed from ``employment`` before the redraw are stale. + +Every number comes from the fixture +(``tests/fixtures/uk/firm_bpe_2025/``, re-created by +``tools/extract_uk_firm_bpe_tables.py``); none is written here. +""" + +from __future__ import annotations + +import hashlib +import re +import zlib +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path +from types import MappingProxyType +from typing import Any + +import numpy as np +import pandas as pd + +#: The extracted BPE Table 3 CSV in a BPE source directory. +UK_FIRM_BPE_LEGAL_STATUS_FILE = "bpe_legal_status_bands.csv" +#: The extracted BPE Tables 1 and 2 CSV in a BPE source directory. +UK_FIRM_BPE_SIZE_BANDS_FILE = "bpe_size_bands.csv" +UK_FIRM_BPE_LEGAL_STATUS_COLUMNS = ( + "legal_status", + "size_band", + "business_number", + "business_number_flag", + "employment_thousand", + "employment_flag", +) +UK_FIRM_BPE_SIZE_BANDS_COLUMNS = ( + "table", + "sector", + "size_band", + "business_number", + "employment_thousand", + "employees_thousand", + "working_proprietors_thousand", + "turnover_million", +) +#: The flag BPE prints for a disclosive cell; the fixture leaves it empty. +UK_FIRM_BPE_SUPPRESSED = "[c]" + +#: The receipt's status and method for the redraw. +UK_FIRM_HEADCOUNT_STATUS = "assumed" +UK_FIRM_HEADCOUNT_METHOD = ( + "employment of ONS legal status 1-3 rows in the ONS 0-4 band redrawn from " + "P(employment | legal status, 0-4 band) built from DBT Business population " + "estimates 2025 Table 3 registered rows, mapped to employment by the " + "proprietor assumption (company 0, sole proprietor 1, partnership 2 " + "working proprietors) with a mean-matched truncated geometric inside " + "multi-value rows, cut to the band" +) + +#: BPE employee size bands, 0 and 1 kept apart, in order. +UK_FIRM_EMPLOYEE_SIZE_BANDS: tuple[str, ...] = ( + "0", + "1", + "2-4", + "5-9", + "10-19", + "20-49", + "50-99", + "100-199", + "200-249", + "250-499", + "500-999", + "1000+", +) +#: The lowest employee count of each band in ``UK_FIRM_EMPLOYEE_SIZE_BANDS``. +_EMPLOYEE_BAND_LOWER_EDGES = np.asarray( + [int(re.match(r"\d+", band).group()) for band in UK_FIRM_EMPLOYEE_SIZE_BANDS], + dtype=np.int64, +) + +#: ONS legal status -> BPE Table 3 section the redraw reads. +UK_FIRM_SMALL_HEADCOUNT_STATUSES: Mapping[int, str] = MappingProxyType( + {1: "companies", 2: "sole_proprietorships", 3: "ordinary_partnerships"} +) +#: Working proprietors assumed per ONS legal status (capped at employment). +UK_FIRM_ASSUMED_PROPRIETORS: Mapping[int, int] = MappingProxyType( + {1: 0, 2: 1, 3: 2, 4: 0, 5: 0, 6: 0, 7: 0} +) +#: The ONS "0-4" employment band as the generator draws it (employment 1-4). +UK_FIRM_ONS_SMALL_BAND: tuple[int, int] = (1, 4) +#: BPE Table 3 registered rows the targets read, with the employee range. +_BPE_NO_EMPLOYEES_REGISTERED = "With no employees (registered)" +_BPE_SMALL_ROWS: tuple[tuple[str, int, int], ...] = ( + (_BPE_NO_EMPLOYEES_REGISTERED, 0, 0), + ("1", 1, 1), + ("2 to 4", 2, 4), +) +_BPE_UNREGISTERED = "With no employees (unregistered)" +#: Distinguishes this redraw's random stream from any other use of ``seed``. +_SEED_TAG = zlib.crc32(b"microcosm.uk_firm_headcount.small_redraw") +_MID_SEED_TAG = zlib.crc32(b"microcosm.uk_firm_headcount.mid_remap") +_LARGE_SEED_TAG = zlib.crc32(b"microcosm.uk_firm_headcount.large_remap") +#: Status codes the BPE private sector covers (companies include public +#: corporations, BPE Table 3 heading). +_PRIVATE_SECTOR_STATUSES = (1, 2, 3, 4) + + +@dataclass(frozen=True) +class UKFirmBPESource: + """The extracted BPE 2025 tables. + + ``legal_status`` is Table 3 and ``size_bands`` Tables 1 and 2, as read + from the CSVs, numbers as floats (NaN where suppressed); ``sha256`` maps + each file name to its hash. + """ + + legal_status: pd.DataFrame + size_bands: pd.DataFrame + sha256: Mapping[str, str] + + +def _number_column(frame: pd.DataFrame, column: str, name: str) -> pd.Series: + text = frame[column].str.strip() + values = pd.to_numeric(text.replace("", np.nan), errors="coerce") + bad = text.ne("") & values.isna() + if bad.any(): + raise ValueError(f"UK firm BPE {name} {column} has non-numbers.") + if (values.dropna() < 0).any(): + raise ValueError(f"UK firm BPE {name} {column} has negative values.") + return values.astype(np.float64) + + +def read_uk_firm_bpe_source(path: str | Path) -> UKFirmBPESource: + """Read the BPE 2025 CSVs from their directory. + + Raises ``ValueError`` unless each file has exactly its columns, every + number parses, and in Table 3 a value is empty exactly when its flag is + ``[c]``. + """ + + directory = Path(path) + frames = {} + hashes = {} + for name, columns in ( + (UK_FIRM_BPE_LEGAL_STATUS_FILE, UK_FIRM_BPE_LEGAL_STATUS_COLUMNS), + (UK_FIRM_BPE_SIZE_BANDS_FILE, UK_FIRM_BPE_SIZE_BANDS_COLUMNS), + ): + file = directory / name + payload = file.read_bytes() + frame = pd.read_csv(file, dtype=str, keep_default_na=False) + if tuple(frame.columns) != columns: + raise ValueError( + f"UK firm BPE {name} columns {list(frame.columns)} are not " + f"{list(columns)}." + ) + frames[name] = frame + hashes[name] = hashlib.sha256(payload).hexdigest() + legal = frames[UK_FIRM_BPE_LEGAL_STATUS_FILE] + for value, flag in ( + ("business_number", "business_number_flag"), + ("employment_thousand", "employment_flag"), + ): + flags = legal[flag].str.strip() + if not flags.isin(["", UK_FIRM_BPE_SUPPRESSED]).all(): + raise ValueError(f"UK firm BPE Table 3 {flag} must be empty or [c].") + if not ( + legal[value].str.strip().eq("") == flags.eq(UK_FIRM_BPE_SUPPRESSED) + ).all(): + raise ValueError( + f"UK firm BPE Table 3 {value} must be empty exactly where " + f"{flag} is [c]." + ) + legal[value] = _number_column(legal, value, UK_FIRM_BPE_LEGAL_STATUS_FILE) + size = frames[UK_FIRM_BPE_SIZE_BANDS_FILE] + for column in UK_FIRM_BPE_SIZE_BANDS_COLUMNS[3:]: + size[column] = _number_column(size, column, UK_FIRM_BPE_SIZE_BANDS_FILE) + return UKFirmBPESource( + legal_status=legal, + size_bands=size, + sha256=MappingProxyType(hashes), + ) + + +def _table_3(source: UKFirmBPESource, section: str, band: str) -> tuple[float, float]: + """``(business number, employment in people)`` of one Table 3 row.""" + + frame = source.legal_status + rows = frame[(frame["legal_status"] == section) & (frame["size_band"] == band)] + if len(rows) != 1: + raise ValueError(f"UK firm BPE Table 3 {section} {band!r} found {len(rows)}x.") + businesses = float(rows["business_number"].iloc[0]) + employment = float(rows["employment_thousand"].iloc[0]) * 1000.0 + if not (np.isfinite(businesses) and np.isfinite(employment)): + raise ValueError(f"UK firm BPE Table 3 {section} {band!r} is suppressed.") + return businesses, employment + + +# -- proprietors and employees ------------------------------------------------- + + +def _status_array(legal_status: Any) -> np.ndarray: + status = np.asarray(legal_status) + if status.dtype.kind not in "iu": + if status.dtype.kind == "f" and np.all(status == np.round(status)): + status = status.astype(np.int64) + else: + raise ValueError("UK firm ons_legal_status must be integers.") + status = status.astype(np.int64) + if not np.isin(status, list(UK_FIRM_ASSUMED_PROPRIETORS)).all(): + raise ValueError( + "UK firm ons_legal_status must be ONS legal status codes " + f"{sorted(UK_FIRM_ASSUMED_PROPRIETORS)}." + ) + return status + + +def _employment_array(employment: Any) -> np.ndarray: + values = np.asarray(employment, dtype=np.float64) + if ( + not np.all(np.isfinite(values)) + or np.any(values != np.round(values)) + or np.any(values < 0) + ): + raise ValueError("UK firm employment must be non-negative whole numbers.") + return values.astype(np.int64) + + +def uk_firm_assumed_proprietors(legal_status: Any, employment: Any) -> np.ndarray: + """Working proprietors per firm (int64) under the legal status assumption. + + Sole proprietorship (ONS status 2) one, ordinary partnership (3) two, + company (1) and statuses 4 to 7 none; never more than ``employment``. + """ + + status = _status_array(legal_status) + employment = _employment_array(employment) + if status.shape != employment.shape: + raise ValueError("legal_status and employment differ in shape.") + per_status = np.zeros(max(UK_FIRM_ASSUMED_PROPRIETORS) + 1, dtype=np.int64) + for code, owners in UK_FIRM_ASSUMED_PROPRIETORS.items(): + per_status[code] = owners + return np.minimum(per_status[status], employment) + + +def uk_firm_employees(legal_status: Any, employment: Any) -> np.ndarray: + """Employees per firm (int64): employment less assumed proprietors, >= 0.""" + + employment_values = _employment_array(employment) + proprietors = uk_firm_assumed_proprietors(legal_status, employment_values) + return np.maximum(employment_values - proprietors, 0) + + +def uk_firm_employee_size_bands(employees: Any) -> np.ndarray: + """BPE employee size band label of each employee count (str array).""" + + values = _employment_array(employees) + index = np.searchsorted(_EMPLOYEE_BAND_LOWER_EDGES, values, side="right") - 1 + return np.asarray(UK_FIRM_EMPLOYEE_SIZE_BANDS, dtype=object)[index].astype(str) + + +# -- the target ---------------------------------------------------------------- + + +def _geometric_pmf(low: int, high: int, ratio: float) -> np.ndarray: + steps = np.arange(high - low + 1, dtype=np.float64) + log = steps * np.log(ratio) + weights = np.exp(log - log.max()) + return weights / weights.sum() + + +def fit_truncated_geometric( + low: int, high: int, mean: float +) -> tuple[float, float, bool]: + """``(ratio, fitted mean, clipped)`` of p(j) ~ ratio ** (j - low) on low..high. + + The ratio is found by bisection on its logarithm (the mean rises with + it). A mean outside the open interval (low, high) is clipped to within + 1e-6 of the nearer end and ``clipped`` is True. + """ + + if high <= low: + raise ValueError("a geometric fit needs at least two support values") + edge = 1e-6 + clipped = not (low + edge <= mean <= high - edge) + target = min(max(mean, low + edge), high - edge) + support = np.arange(low, high + 1, dtype=np.float64) + lower, upper = -60.0, 60.0 + for _ in range(200): + middle = 0.5 * (lower + upper) + if float(support @ _geometric_pmf(low, high, np.exp(middle))) < target: + lower = middle + else: + upper = middle + ratio = float(np.exp(0.5 * (lower + upper))) + return ratio, float(support @ _geometric_pmf(low, high, ratio)), clipped + + +def _support(status: int, employees_low: int, employees_high: int) -> tuple[int, int]: + """Employment range of a BPE employee range under the proprietor rule.""" + + if status == 1 and employees_high == 0: + # BPE counts a company whose one PAYE employee is its working + # director with no employees: employment 1. + return 1, 1 + shift = UK_FIRM_ASSUMED_PROPRIETORS[status] + return employees_low + shift, employees_high + shift + + +def _fits(source: UKFirmBPESource) -> pd.DataFrame: + band_low, band_high = UK_FIRM_ONS_SMALL_BAND + rows = [] + for status, section in UK_FIRM_SMALL_HEADCOUNT_STATUSES.items(): + for band, employees_low, employees_high in _BPE_SMALL_ROWS: + rows.append( + _fit_row(source, status, section, band, employees_low, employees_high) + ) + return pd.DataFrame(rows) + + +def uk_firm_small_headcount_fits(source: UKFirmBPESource) -> pd.DataFrame: + """One row per (status, BPE registered row): its support, fit and mass. + + Columns: ``ons_legal_status``, ``bpe_legal_status``, ``bpe_size_band``, + ``businesses``, ``employment``, ``mean_employment`` (published), + ``support_low``/``support_high`` (employment), ``ratio`` (NaN for one + value), ``fitted_mean``, ``clipped``, ``in_band_share`` and + ``in_band_businesses``. + """ + + return _fits(source).drop(columns="_pmf") + + +def _fit_row( + source: UKFirmBPESource, + status: int, + section: str, + band: str, + employees_low: int, + employees_high: int, +) -> dict[str, Any]: + band_low, band_high = UK_FIRM_ONS_SMALL_BAND + businesses, employment = _table_3(source, section, band) + low, high = _support(status, employees_low, employees_high) + mean = employment / businesses if businesses > 0 else np.nan + if high > low and businesses > 0: + ratio, fitted, clipped = fit_truncated_geometric(low, high, mean) + pmf = _geometric_pmf(low, high, ratio) + else: + ratio, fitted, clipped = np.nan, float(low), False + pmf = np.ones(high - low + 1) / (high - low + 1) + values = np.arange(low, high + 1) + inside = (values >= band_low) & (values <= band_high) + share = float(pmf[inside].sum()) + return { + "ons_legal_status": status, + "bpe_legal_status": section, + "bpe_size_band": band, + "businesses": businesses, + "employment": employment, + "mean_employment": mean, + "support_low": low, + "support_high": high, + "ratio": ratio, + "fitted_mean": fitted, + "clipped": clipped, + "in_band_share": share, + "in_band_businesses": businesses * share, + "_pmf": dict(zip(values.tolist(), (businesses * pmf).tolist(), strict=True)), + } + + +def uk_firm_small_headcount_targets(source: UKFirmBPESource) -> pd.DataFrame: + """P(employment = k | ONS legal status, 0-4 band) from BPE Table 3. + + One row per status (1, 2, 3) and k (1 to 4): ``ons_legal_status``, + ``employment``, ``businesses`` (BPE businesses assigned to k) and + ``share`` (sums to one within a status). + """ + + fits = _fits(source) + band_low, band_high = UK_FIRM_ONS_SMALL_BAND + rows = [] + for status in UK_FIRM_SMALL_HEADCOUNT_STATUSES: + mass = dict.fromkeys(range(band_low, band_high + 1), 0.0) + for pmf in fits.loc[fits["ons_legal_status"] == status, "_pmf"]: + for value, businesses in pmf.items(): + if value in mass: + mass[value] += businesses + total = sum(mass.values()) + if not total > 0: + raise ValueError(f"BPE gives no businesses in band for status {status}.") + rows.extend( + { + "ons_legal_status": status, + "employment": value, + "businesses": businesses, + "share": businesses / total, + } + for value, businesses in mass.items() + ) + return pd.DataFrame(rows) + + +# -- the redraw ---------------------------------------------------------------- + + +def _firm_ids(firms: pd.DataFrame, id_column: str | None) -> np.ndarray: + if id_column is None: + id_column = next( + (c for c in ("source_firm_id", "firm_id") if c in firms.columns), None + ) + ids = firms.index.to_numpy() if id_column is None else firms[id_column].to_numpy() + if np.asarray(ids).dtype.kind not in "iu": + raise ValueError("UK firm ids must be integers.") + ordered = np.sort(np.asarray(ids, dtype=np.int64)) + if ordered.size and np.any(np.diff(ordered) == 0): + raise ValueError("UK firm ids repeat.") + return np.asarray(ids, dtype=np.int64) + + +def _redrawn( + firms: pd.DataFrame, + source: UKFirmBPESource, + seed: int, + id_column: str | None, + employment_column: str, +) -> np.ndarray: + for column in ("ons_legal_status", employment_column): + if column not in firms.columns: + raise ValueError(f"UK firm headcount redraw needs column {column!r}.") + status = _status_array(firms["ons_legal_status"].to_numpy()) + employment = _employment_array(firms[employment_column].to_numpy()) + ids = _firm_ids(firms, id_column) + band_low, band_high = UK_FIRM_ONS_SMALL_BAND + eligible = ( + np.isin(status, list(UK_FIRM_SMALL_HEADCOUNT_STATUSES)) + & (employment >= band_low) + & (employment <= band_high) + ) + after = employment.copy() + rows = np.flatnonzero(eligible) + rows = rows[np.argsort(ids[rows], kind="stable")] + rng = np.random.default_rng(np.random.SeedSequence([int(seed), _SEED_TAG])) + uniform = rng.random(rows.size) + targets = uk_firm_small_headcount_targets(source) + for code in UK_FIRM_SMALL_HEADCOUNT_STATUSES: + target = targets[targets["ons_legal_status"] == code].sort_values("employment") + cdf = np.cumsum(target["share"].to_numpy()) + cdf[-1] = 1.0 + values = target["employment"].to_numpy(np.int64) + mine = status[rows] == code + pick = np.searchsorted(cdf, uniform[mine], side="right") + after[rows[mine]] = values[np.minimum(pick, values.size - 1)] + redrawn = after[rows] + if np.any((redrawn < band_low) | (redrawn > band_high)): + raise AssertionError("UK firm headcount redraw left the 0-4 band") + return after + + +def redraw_uk_firm_small_headcount( + firms: pd.DataFrame, + source: UKFirmBPESource, + *, + seed: int, + id_column: str | None = None, + employment_column: str = "employment", +) -> pd.DataFrame: + """A copy of ``firms`` with small-firm employment redrawn from BPE. + + Rows with ``ons_legal_status`` 1, 2 or 3 and employment 1 to 4 draw a + new employment from ``uk_firm_small_headcount_targets``; every other row, + the index, the order and every other column are unchanged. Draws come from + ``np.random.default_rng(SeedSequence([seed, tag]))`` in order of firm id + (``id_column``; by default ``source_firm_id``, else ``firm_id``, else the + index), so the result does not depend on row order. + """ + + after = _redrawn(firms, source, seed, id_column, employment_column) + result = firms.copy() + result[employment_column] = after.astype(firms[employment_column].dtype) + return result + + +# -- diagnostics --------------------------------------------------------------- + + +def uk_firm_small_headcount_diagnostics( + before: pd.DataFrame, + after: pd.DataFrame, + source: UKFirmBPESource, + *, + weight_col: str = "firm_weight", + employment_column: str = "employment", +) -> pd.DataFrame: + """Weighted counts by status (1-3) and employment 1-4, before and after. + + ``before`` and ``after`` are the frames either side of the redraw, rows + aligned. Columns: ``ons_legal_status``, ``employment``, + ``weight_before``, ``weight_after``, ``share_before``, ``share_after`` + (within status and band) and ``target_share``. + """ + + if len(before) != len(after): + raise ValueError("before and after differ in length.") + weight = before[weight_col].to_numpy(dtype=np.float64) + status = _status_array(before["ons_legal_status"].to_numpy()) + targets = uk_firm_small_headcount_targets(source) + rows = [] + for label, frame in (("before", before), ("after", after)): + employment = _employment_array(frame[employment_column].to_numpy()) + for _, target in targets.iterrows(): + code, value = int(target["ons_legal_status"]), int(target["employment"]) + rows.append( + { + "ons_legal_status": code, + "employment": value, + "when": label, + "weight": float( + weight[(status == code) & (employment == value)].sum() + ), + } + ) + table = ( + pd.DataFrame(rows) + .pivot_table( + index=["ons_legal_status", "employment"], columns="when", values="weight" + ) + .reset_index() + .rename(columns={"before": "weight_before", "after": "weight_after"}) + ) + table.columns.name = None + for when in ("before", "after"): + totals = table.groupby("ons_legal_status")[f"weight_{when}"].transform("sum") + table[f"share_{when}"] = np.where( + totals > 0, table[f"weight_{when}"] / totals.where(totals > 0, 1.0), 0.0 + ) + table = table.merge( + targets[["ons_legal_status", "employment", "share"]].rename( + columns={"share": "target_share"} + ), + on=["ons_legal_status", "employment"], + ) + return table[ + [ + "ons_legal_status", + "employment", + "weight_before", + "weight_after", + "share_before", + "share_after", + "target_share", + ] + ] + + +#: ONS employment bands the mid-band remap redraws within, with the BPE 2025 +#: Table 1 (private sector, employee bands) rows whose employment means pin +#: each band's shape. 100-249 mixes two BPE rows, weighted by their counts. +UK_FIRM_MID_BANDS: tuple[tuple[int, int, tuple[tuple[str, int, int], ...]], ...] = ( + (5, 9, (("5 to 9", 5, 9),)), + (10, 19, (("10 to 19", 10, 19),)), + (20, 49, (("20 to 49", 20, 49),)), + (50, 99, (("50 to 99", 50, 99),)), + (100, 249, (("100 to 199", 100, 199), ("200 to 249", 200, 249))), +) +#: Legal statuses the mid-band remap reads (BPE's private sector). +UK_FIRM_MID_BAND_STATUSES = (1, 2, 3, 4) +UK_FIRM_MID_HEADCOUNT_METHOD = ( + "Inside each ONS employment band from 5-9 to 100-249, for ONS legal " + "statuses 1-4, headcount is remapped by weighted rank to a truncated " + "geometric matched to DBT Business Population Estimates 2025 Table 1 " + "private-sector employment per business (100-249 a count-weighted mix of " + "the 100-199 and 200-249 rows). Bands, ranks and weights are kept. BPE " + "bands are by employees and ONS bands by employment; the shapes are " + "taken across that difference." +) + + +def uk_firm_mid_headcount_targets(source: UKFirmBPESource) -> pd.DataFrame: + """Target pmf per ONS mid band: ``ons_band``, ``employment``, ``probability``, + with the BPE rows, counts and means behind it.""" + + table_1 = source.size_bands[ + (source.size_bands["table"] == "Table 1") + & (source.size_bands["sector"] == "private_sector") + ].set_index("size_band") + rows = [] + for band_low, band_high, parts in UK_FIRM_MID_BANDS: + mixture = np.zeros(band_high - band_low + 1, dtype=np.float64) + total = 0.0 + for label, low, high in parts: + businesses = float(table_1.loc[label, "business_number"]) + mean = ( + float(table_1.loc[label, "employment_thousand"]) * 1_000.0 / businesses + ) + ratio, _, _ = fit_truncated_geometric(low, high, mean) + pmf = _geometric_pmf(low, high, ratio) + mixture[low - band_low : high - band_low + 1] += businesses * pmf + total += businesses + mixture /= total + for offset, probability in enumerate(mixture): + rows.append( + { + "ons_band": f"{band_low}-{band_high}", + "employment": band_low + offset, + "probability": float(probability), + } + ) + return pd.DataFrame(rows) + + +def _in_frame(firms: pd.DataFrame) -> np.ndarray: + """Rows in the ONS frame (every row when ``in_frame`` is absent): BPE's + size rows describe registered businesses, so the remaps read only them.""" + + if "in_frame" not in firms.columns: + return np.ones(len(firms), dtype=bool) + return firms["in_frame"].to_numpy(bool) + + +def remap_uk_firm_mid_headcount( + firms: pd.DataFrame, + source: UKFirmBPESource, + *, + seed: int, + weight_column: str = "firm_weight", + employment_column: str = "employment", + id_column: str | None = None, +) -> pd.DataFrame: + """A copy of ``firms`` with mid-band headcounts remapped to BPE shapes. + + For rows of ONS statuses 1-4 whose employment lies in an ONS band from + 5-9 to 100-249 (and in the ONS frame, when ``in_frame`` is given), each + band's rows are ordered by employment (ties by a + uniform from this function's own stream, in firm id order), and the row + at weighted mid-rank ``q`` takes the target pmf's ``q`` quantile. Every + row keeps its ONS band, its rank and its weight, so the ONS employment + band targets are unchanged; only headcounts inside the bands move. + """ + + out = firms.copy() + employment = out[employment_column].to_numpy(np.float64) + status = _status_array(out["ons_legal_status"]) + weight = out[weight_column].to_numpy(np.float64) + ids = _firm_ids(out, id_column) + order_ids = np.argsort(ids, kind="stable") + ties = np.empty(len(ids), dtype=np.float64) + ties[order_ids] = np.random.default_rng( + np.random.SeedSequence([int(seed), _MID_SEED_TAG]) + ).random(len(ids)) + targets = uk_firm_mid_headcount_targets(source) + result = employment.copy() + eligible = np.isin(status, UK_FIRM_MID_BAND_STATUSES) & _in_frame(out) + for band_low, band_high, _ in UK_FIRM_MID_BANDS: + rows = np.flatnonzero( + eligible & (employment >= band_low) & (employment <= band_high) + ) + if rows.size == 0: + continue + pmf = targets[targets["ons_band"] == f"{band_low}-{band_high}"] + cdf = np.cumsum(pmf["probability"].to_numpy(np.float64)) + values = pmf["employment"].to_numpy(np.float64) + ranked = rows[np.lexsort((ties[rows], employment[rows]))] + mass = np.maximum(weight[ranked], 0.0) + if not mass.sum() > 0: + mass = np.ones(len(ranked), dtype=np.float64) + upper = np.cumsum(mass) + mid = (upper - 0.5 * mass) / upper[-1] + index = np.minimum(np.searchsorted(cdf, mid, side="left"), len(values) - 1) + result[ranked] = values[index] + out[employment_column] = result.astype(out[employment_column].dtype) + return out + + +#: BPE 2025 Table 1 private-sector rows the large-band remap reads, top first. +UK_FIRM_LARGE_BAND_ROWS: tuple[tuple[str, int, int | None], ...] = ( + ("1000 or more", 1000, None), + ("500 to 999", 500, 999), + ("250 to 499", 250, 499), +) +UK_FIRM_LARGE_HEADCOUNT_METHOD = ( + "Inside the ONS 250+ band, for ONS legal statuses 1-4, firms are ranked " + "by headcount and, from the top, the weighted count of DBT Business " + "Population Estimates 2025 Table 1 private-sector businesses with 1000 or " + "more employees take the 1000+ shape, the next 500-999 count the 500-999 " + "shape, and the rest 250-499. 1000+ is a truncated Pareto on [1000, " + "LARGE_EMPLOYMENT_CAP] with BPE's mean employment per business; the " + "closed rows are truncated geometrics with BPE's means. The band's other " + "firms keep 250-499: the model has more 250+ firms than BPE." +) + + +def remap_uk_firm_large_headcount( + firms: pd.DataFrame, + source: UKFirmBPESource, + *, + seed: int, + weight_column: str = "firm_weight", + employment_column: str = "employment", + id_column: str | None = None, +) -> pd.DataFrame: + """A copy of ``firms`` with 250+ headcounts remapped to BPE's large rows. + + Ranks and weights are kept and every row stays at 250 or more; the BPE + business counts of the 1000+ and 500-999 rows are taken as absolute + weighted counts from the top of the ranking. + """ + + from microcosm.build.uk_runtime.firm_generation import ( + LARGE_EMPLOYMENT_CAP, + large_employment_slice_means, + ) + + out = firms.copy() + employment = out[employment_column].to_numpy(np.float64) + status = _status_array(out["ons_legal_status"]) + weight = np.maximum(out[weight_column].to_numpy(np.float64), 0.0) + ids = _firm_ids(out, id_column) + ties = np.empty(len(ids), dtype=np.float64) + ties[np.argsort(ids, kind="stable")] = np.random.default_rng( + np.random.SeedSequence([int(seed), _LARGE_SEED_TAG]) + ).random(len(ids)) + rows = np.flatnonzero( + np.isin(status, UK_FIRM_MID_BAND_STATUSES) + & (employment >= 250) + & _in_frame(out) + ) + result = employment.copy() + if rows.size: + table_1 = source.size_bands[ + (source.size_bands["table"] == "Table 1") + & (source.size_bands["sector"] == "private_sector") + ].set_index("size_band") + # Highest headcount first. + ranked = rows[np.lexsort((-ties[rows], -employment[rows]))] + mass = weight[ranked] + start = np.cumsum(mass) - mass + mid = start + 0.5 * mass + edge = 0.0 + for label, low, high in UK_FIRM_LARGE_BAND_ROWS: + businesses = float(table_1.loc[label, "business_number"]) + mean = ( + float(table_1.loc[label, "employment_thousand"]) * 1_000.0 / businesses + ) + take = mid >= edge + if label != UK_FIRM_LARGE_BAND_ROWS[-1][0]: + take &= mid < edge + businesses + members = ranked[take][::-1] # lowest headcount first + edge += businesses + if members.size == 0: + continue + masses = weight[members] + if not masses.sum() > 0: + masses = np.ones(len(members), dtype=np.float64) + if high is None: + result[members] = np.round( + large_employment_slice_means( + masses, mean=mean, lower=float(low), cap=LARGE_EMPLOYMENT_CAP + ) + ) + continue + ratio, _, _ = fit_truncated_geometric(low, high, mean) + cdf = np.cumsum(_geometric_pmf(low, high, ratio)) + upper = np.cumsum(masses) + total = upper[-1] if upper[-1] > 0 else 1.0 + quantile = (upper - 0.5 * masses) / total + index = np.minimum(np.searchsorted(cdf, quantile, side="left"), high - low) + result[members] = low + index + out[employment_column] = result.astype(out[employment_column].dtype) + return out + + +def _lower_edge(label: str) -> int: + if label.startswith("Zero"): + return 0 + match = re.match(r"\d+", label) + if match is None: + raise ValueError(f"BPE band {label!r} has no lower edge.") + return int(match.group()) + + +def uk_firm_bpe_size_band_reconciliation( + firms: pd.DataFrame, + source: UKFirmBPESource, + weight_col: str = "firm_weight", + *, + employment_column: str = "employment", +) -> pd.DataFrame: + """Modelled firms, employment and employees by BPE band against BPE. + + Bands are BPE Table 2's ("Zero or 1 employee", "2 to 4", ..., + "1000 or more", and "All"), on employees from ``uk_firm_employees``. + ``private_sector`` compares statuses 1 to 4 with Table 2's private + sector; ``whole_economy`` compares every row with Table 2's whole + economy. BPE counts unregistered businesses the ONS frame does not hold; + ``bpe_registered_businesses`` and ``bpe_registered_employment`` take + Table 1's unregistered row out of the "Zero or 1 employee" and "All" + bands (every unregistered business is private), and the ratios divide by + them. BPE counts people, start 2025; the model counts weighted firms. + """ + + status = _status_array(firms["ons_legal_status"].to_numpy()) + employment = _employment_array(firms[employment_column].to_numpy()) + weight = firms[weight_col].to_numpy(dtype=np.float64) + employees = uk_firm_employees(status, employment) + table_2 = source.size_bands[source.size_bands["table"] == "Table 2"] + table_1 = source.size_bands[source.size_bands["table"] == "Table 1"] + unregistered = table_1[table_1["size_band"] == _BPE_UNREGISTERED] + if len(unregistered) != 1: + raise ValueError("BPE Table 1 lacks the unregistered row.") + unregistered_businesses = float(unregistered["business_number"].iloc[0]) + unregistered_employment = float(unregistered["employment_thousand"].iloc[0]) * 1000 + rows = [] + for scope, keep in ( + ("private_sector", np.isin(status, _PRIVATE_SECTOR_STATUSES)), + ("whole_economy", np.ones(status.size, dtype=bool)), + ): + published = table_2[table_2["sector"] == scope] + bands = [band for band in published["size_band"] if band != "All"] + edges = np.asarray([_lower_edge(band) for band in bands], dtype=np.int64) + index = np.searchsorted(edges, employees, side="right") - 1 + for position, band in enumerate([*bands, "All"]): + rows_in = keep & (index == position) if band != "All" else keep + bpe = published[published["size_band"] == band].iloc[0] + businesses = float(bpe["business_number"]) + employment_people = float(bpe["employment_thousand"]) * 1000 + first = band == "All" or position == 0 + registered_businesses = businesses - ( + unregistered_businesses if first else 0.0 + ) + registered_employment = employment_people - ( + unregistered_employment if first else 0.0 + ) + modelled_businesses = float(weight[rows_in].sum()) + modelled_employment = float(weight[rows_in] @ employment[rows_in]) + rows.append( + { + "scope": scope, + "size_band": band, + "modelled_businesses": modelled_businesses, + "modelled_employment": modelled_employment, + "modelled_employees": float(weight[rows_in] @ employees[rows_in]), + "bpe_businesses": businesses, + "bpe_employment": employment_people, + "bpe_employees": float(bpe["employees_thousand"]) * 1000, + "bpe_registered_businesses": registered_businesses, + "bpe_registered_employment": registered_employment, + "businesses_ratio": modelled_businesses / registered_businesses + if registered_businesses > 0 + else np.nan, + "employment_ratio": modelled_employment / registered_employment + if registered_employment > 0 + else np.nan, + } + ) + return pd.DataFrame(rows) + + +__all__ = [ + "UK_FIRM_LARGE_BAND_ROWS", + "UK_FIRM_LARGE_HEADCOUNT_METHOD", + "remap_uk_firm_large_headcount", + "UK_FIRM_MID_BANDS", + "UK_FIRM_MID_BAND_STATUSES", + "UK_FIRM_MID_HEADCOUNT_METHOD", + "remap_uk_firm_mid_headcount", + "uk_firm_mid_headcount_targets", + "UK_FIRM_ASSUMED_PROPRIETORS", + "UK_FIRM_BPE_LEGAL_STATUS_COLUMNS", + "UK_FIRM_BPE_LEGAL_STATUS_FILE", + "UK_FIRM_BPE_SIZE_BANDS_COLUMNS", + "UK_FIRM_BPE_SIZE_BANDS_FILE", + "UK_FIRM_BPE_SUPPRESSED", + "UK_FIRM_EMPLOYEE_SIZE_BANDS", + "UK_FIRM_HEADCOUNT_METHOD", + "UK_FIRM_HEADCOUNT_STATUS", + "UK_FIRM_ONS_SMALL_BAND", + "UK_FIRM_SMALL_HEADCOUNT_STATUSES", + "UKFirmBPESource", + "fit_truncated_geometric", + "read_uk_firm_bpe_source", + "redraw_uk_firm_small_headcount", + "uk_firm_assumed_proprietors", + "uk_firm_bpe_size_band_reconciliation", + "uk_firm_employee_size_bands", + "uk_firm_employees", + "uk_firm_small_headcount_diagnostics", + "uk_firm_small_headcount_fits", + "uk_firm_small_headcount_targets", +] diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_pay_distribution.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_pay_distribution.py new file mode 100644 index 0000000000..7ebead77f7 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_pay_distribution.py @@ -0,0 +1,329 @@ +"""UK firm employees paid at or below the secondary threshold, from ASHE. + +policyengine-uk's ``firm_class_1_earnings_above_secondary_threshold`` removes +the employees supplied in ``firm_employees_below_secondary_threshold`` (int) +and their pay in ``firm_paybill_below_secondary_threshold`` (float) before its +average-pay approximation. Left at 0, every employee's unused threshold is +netted against others' pay, which understates the employer NIC base of firms +with low-paid staff. This module imputes the two inputs from one published +table: ONS ASHE Table 4.7a (*Annual pay - Gross*), 2025 revised edition, +sheet ``All``, tax year 2024-25, the same table ``firm_paybill`` uses. The +extracted CSV and its provenance sit in +``tests/fixtures/uk/firm_pay_distribution_2024/`` +(``tools/extract_uk_firm_pay_distribution_table.py`` re-creates it). + +Method, all of it assumption beyond the source (status ``assumed``): + +- a section's annual pay quantile function is piecewise linear through + (0, 0 pounds) and its published percentiles (10, 20, 25, 30, 40, 50, 60, + 70, 75, 80, 90). A percentile ONS marks ``x`` or ``:`` is skipped, so the + line runs between its published neighbours (section A has no p10 in 2025, + so its line runs from 0 pounds at p0 to p20). The straight line from 0 + pounds at p0 to the first published percentile is a guess: ASHE publishes + nothing below p10. In most sections the 2024-25 threshold (9,100 pounds) + is below p10, so the share is 10% x 9,100 / p10 and the mean pay below is + exactly 4,550 pounds: both rest wholly on that guess; +- the share of a section's jobs paid at or below the threshold is the + percentile at which that line reaches the threshold, and their mean pay is + the line's average below that percentile; +- a section with no published percentiles (section U in 2025), one whose + highest published percentile is below the threshold, and ``UNKNOWN`` take + the ``ALL EMPLOYEES`` row, as ``firm_paybill`` does; +- every firm in a section has that section's share, whatever its size. The + section total is unbiased, but a micro firm whose draw puts every employee + below the threshold has the rest of its paybill charged with no threshold + at all in policyengine-uk, which makes the split lumpy per firm (it matters + for the Employment Allowance); +- the head count is an integer (policyengine-uk ``value_type = int``): + ``floor(employees x share)`` plus one with probability equal to the + remainder, drawn from a fixed-seed generator of its own + (``UK_FIRM_PAY_DISTRIBUTION_SEED``), so the weighted total stays close to + the expected value and the firm generator's stream is untouched; +- the paybill is that count times the section's mean pay below the + threshold, capped at the firm's ``firm_paybill`` where the frame has one; +- ASHE annual pay covers employees on adult rates in the same job for more + than a year, so short-tenure and youth-rate jobs, which are lower paid, + are left out and the share leans low; annual pay at or below the annual + threshold is not the same as no secondary contributions, which are + assessed per earnings period. +""" + +from __future__ import annotations + +import hashlib +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 + +from microcosm.build.uk_runtime.firm_table import ( + UK_FIRM_SIC_SECTION_UNKNOWN, + UK_FIRM_SIC_SECTIONS, + uk_firm_sic_sections, +) + +#: The extracted ASHE table's file name in a pay distribution source directory. +UK_FIRM_PAY_DISTRIBUTION_FILE = "ashe_section_annual_pay_percentiles.csv" +#: Percentiles the table carries, in order (``p50`` is the sheet's median). +UK_FIRM_PAY_DISTRIBUTION_PERCENTILES = (10, 20, 25, 30, 40, 50, 60, 70, 75, 80, 90) +#: Its columns, in order. +UK_FIRM_PAY_DISTRIBUTION_SOURCE_COLUMNS = ( + "sic_section", + "description", + "jobs_thousand", + "mean", + *(f"p{p}" for p in UK_FIRM_PAY_DISTRIBUTION_PERCENTILES), +) +#: ``sic_section`` of the table's ``ALL EMPLOYEES`` row. +UK_FIRM_PAY_DISTRIBUTION_ALL_EMPLOYEES = "ALL" +#: ONS markers for a cell it does not publish. +UK_FIRM_PAY_DISTRIBUTION_MARKERS = ("x", ":") +#: The tax year the table describes (ASHE 2025 is the year to 5 April 2025). +UK_FIRM_PAY_DISTRIBUTION_TAX_YEAR = "2024-25" +UK_FIRM_PAY_DISTRIBUTION_STATUS = "assumed" +UK_FIRM_PAY_DISTRIBUTION_METHOD = ( + "share of section jobs at or below the secondary threshold from a " + "piecewise-linear ONS ASHE 2025 Table 4.7a percentile curve (0 pounds at " + "p0), times firm_employees, rounded by a fixed-seed draw; paybill is the " + "count times the section's mean pay below the threshold" +) +#: Seed of the rounding generator; not the firm generator's seed. +UK_FIRM_PAY_DISTRIBUTION_SEED = 20242025 + +_SECTION_LETTERS = tuple( + section + for section in UK_FIRM_SIC_SECTIONS + if section != UK_FIRM_SIC_SECTION_UNKNOWN +) + + +@dataclass(frozen=True) +class UKFirmPayDistributionSource: + """Published annual gross pay percentiles (pounds) per SIC section. + + ``section_percentiles`` maps a section, or ``ALL``, to its published + ``{percentile: pay}`` (unpublished cells left out; a section with none + has an empty mapping). ``sha256`` is the CSV's hash. + """ + + section_percentiles: Mapping[str, Mapping[int, float]] + file: str + sha256: str + + +def read_uk_firm_pay_distribution_source( + path: str | Path, +) -> UKFirmPayDistributionSource: + """Read the ASHE percentile table from a directory or the CSV itself. + + Raises ``ValueError`` unless the file has exactly + ``UK_FIRM_PAY_DISTRIBUTION_SOURCE_COLUMNS``, sections A-U and ``ALL`` + once each, every percentile cell a positive number or an ONS marker, + published percentiles that do not fall as the percentile rises, and a + fully published ``ALL`` row. + """ + + path = Path(path) + if path.is_dir(): + path = path / UK_FIRM_PAY_DISTRIBUTION_FILE + payload = path.read_bytes() + frame = pd.read_csv(path, dtype=str, keep_default_na=False) + if tuple(frame.columns) != UK_FIRM_PAY_DISTRIBUTION_SOURCE_COLUMNS: + raise ValueError( + f"UK firm pay distribution columns {list(frame.columns)} are not " + f"{list(UK_FIRM_PAY_DISTRIBUTION_SOURCE_COLUMNS)}." + ) + keys = frame["sic_section"].str.strip().tolist() + expected = [*_SECTION_LETTERS, UK_FIRM_PAY_DISTRIBUTION_ALL_EMPLOYEES] + if sorted(keys) != sorted(expected): + raise ValueError( + f"UK firm pay distribution rows {keys} are not sections A-U and " + f"{UK_FIRM_PAY_DISTRIBUTION_ALL_EMPLOYEES!r}, once each." + ) + curves: dict[str, Mapping[int, float]] = {} + for key, (_, row) in zip(keys, frame.iterrows(), strict=True): + curve: dict[int, float] = {} + for percentile in UK_FIRM_PAY_DISTRIBUTION_PERCENTILES: + cell = row[f"p{percentile}"].strip() + if cell in UK_FIRM_PAY_DISTRIBUTION_MARKERS: + continue + try: + value = float(cell) + except ValueError: + raise ValueError( + f"UK firm pay distribution section {key} p{percentile} " + f"{cell!r} is neither a number nor an ONS marker." + ) from None + if not np.isfinite(value) or value <= 0: + raise ValueError( + f"UK firm pay distribution section {key} p{percentile} " + "must be positive." + ) + curve[percentile] = value + if np.any(np.diff(list(curve.values())) < 0): + raise ValueError( + f"UK firm pay distribution section {key} percentiles fall." + ) + curves[key] = MappingProxyType(curve) + if len(curves[UK_FIRM_PAY_DISTRIBUTION_ALL_EMPLOYEES]) != len( + UK_FIRM_PAY_DISTRIBUTION_PERCENTILES + ): + raise ValueError("UK firm pay distribution ALL row is not fully published.") + return UKFirmPayDistributionSource( + section_percentiles=MappingProxyType(dict(sorted(curves.items()))), + file=path.name, + sha256=hashlib.sha256(payload).hexdigest(), + ) + + +def _share_and_mean( + curve: Mapping[int, float], threshold_gbp: float +) -> tuple[float, float] | None: + """Share of jobs at or below the threshold and their mean pay. + + ``None`` when the curve cannot place the threshold: no published + percentile, or the threshold above the highest one. + """ + + if not curve or threshold_gbp > max(curve.values()): + return None + points = np.array([0.0, *curve]) / 100.0 + pays = np.array([0.0, *curve.values()]) + if threshold_gbp <= 0: + return 0.0, 0.0 + # First knot at or above the threshold; pay rises strictly across it. + upper = int(np.searchsorted(pays, threshold_gbp, side="left")) + lower = upper - 1 + share = points[lower] + (points[upper] - points[lower]) * ( + threshold_gbp - pays[lower] + ) / (pays[upper] - pays[lower]) + # Area under the quantile line from 0 to ``share``: trapezoids. + knots_u = np.array([*points[:upper], share]) + knots_pay = np.array([*pays[:upper], threshold_gbp]) + area = float(np.sum(np.diff(knots_u) * (knots_pay[1:] + knots_pay[:-1]) / 2.0)) + return float(share), area / float(share) + + +def uk_firm_pay_below_threshold_by_section( + source: UKFirmPayDistributionSource, *, threshold_gbp: float +) -> pd.DataFrame: + """Per section A-U, ``UNKNOWN`` and ``ALL``: share and mean pay below. + + Columns ``sic_section``, ``share_at_or_below`` (0-1), + ``mean_pay_at_or_below_gbp`` and ``level`` (``section``, or + ``all_employees`` where the section takes the ``ALL`` row). + """ + + threshold = float(threshold_gbp) + if not np.isfinite(threshold) or threshold < 0: + raise ValueError("UK firm secondary threshold must be non-negative.") + all_key = UK_FIRM_PAY_DISTRIBUTION_ALL_EMPLOYEES + fallback = _share_and_mean(source.section_percentiles[all_key], threshold) + if fallback is None: + raise ValueError( + f"UK firm secondary threshold {threshold} is above the highest " + "published all-employees percentile." + ) + records = [] + for key in (*_SECTION_LETTERS, UK_FIRM_SIC_SECTION_UNKNOWN, all_key): + own = _share_and_mean(source.section_percentiles.get(key, {}), threshold) + share, mean = fallback if own is None else own + level = "all_employees" if own is None or key == all_key else "section" + records.append((key, share, mean, level)) + return pd.DataFrame( + records, + columns=[ + "sic_section", + "share_at_or_below", + "mean_pay_at_or_below_gbp", + "level", + ], + ) + + +def _employees_and_sections(frame: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]: + if {"firm_employees", "firm_sic_section"} <= set(frame.columns): + employees = frame["firm_employees"].to_numpy() + sections = frame["firm_sic_section"].astype(str).to_numpy(object) + if not np.isin(sections, UK_FIRM_SIC_SECTIONS).all(): + raise ValueError( + "UK firm firm_sic_section must be SICSection member names." + ) + elif {"employment", "sic_code"} <= set(frame.columns): + employees = frame["employment"].to_numpy() + sections = uk_firm_sic_sections(frame["sic_code"]) + else: + raise ValueError( + "UK firm pay distribution needs firm_employees and " + "firm_sic_section, or employment and sic_code." + ) + as_float = employees.astype(np.float64) + if ( + not np.all(np.isfinite(as_float)) + or np.any(as_float != np.round(as_float)) + or np.any(as_float < 0) + ): + raise ValueError("UK firm employees must be non-negative whole numbers.") + return as_float.astype(np.int64), sections + + +def assign_uk_firm_pay_below_secondary_threshold( + table_or_firms: pd.DataFrame, + source: UKFirmPayDistributionSource, + *, + threshold_gbp: float, + seed: int = UK_FIRM_PAY_DISTRIBUTION_SEED, +) -> dict[str, np.ndarray]: + """The two policyengine-uk below-threshold inputs per row, in row order. + + ``firm_employees_below_secondary_threshold`` (int64) is + ``floor(employees x share)`` plus a fixed-seed Bernoulli draw on the + remainder, never above the firm's employees. + ``firm_paybill_below_secondary_threshold`` (float64, pounds) is that + count times the section's mean pay at or below ``threshold_gbp``, capped + at ``firm_paybill`` when ``table_or_firms`` has that column. The frame is + a policyengine-uk firm table (``firm_employees``, ``firm_sic_section``) + or generator rows (``employment``, ``sic_code``). The draw depends on row + order. + """ + + employees, sections = _employees_and_sections(table_or_firms) + by_section = uk_firm_pay_below_threshold_by_section( + source, threshold_gbp=threshold_gbp + ).set_index("sic_section") + share = by_section["share_at_or_below"].reindex(sections).to_numpy(np.float64) + mean = by_section["mean_pay_at_or_below_gbp"].reindex(sections).to_numpy(np.float64) + expected = employees * share + whole = np.floor(expected) + draws = np.random.default_rng(seed).random(len(employees)) + count = (whole + (draws < expected - whole)).astype(np.int64) + count = np.minimum(count, employees) + paybill = count * mean + if "firm_paybill" in table_or_firms.columns: + paybill = np.minimum( + paybill, table_or_firms["firm_paybill"].to_numpy(np.float64) + ) + return { + "firm_employees_below_secondary_threshold": count, + "firm_paybill_below_secondary_threshold": paybill, + } + + +__all__ = [ + "UK_FIRM_PAY_DISTRIBUTION_ALL_EMPLOYEES", + "UK_FIRM_PAY_DISTRIBUTION_FILE", + "UK_FIRM_PAY_DISTRIBUTION_MARKERS", + "UK_FIRM_PAY_DISTRIBUTION_METHOD", + "UK_FIRM_PAY_DISTRIBUTION_PERCENTILES", + "UK_FIRM_PAY_DISTRIBUTION_SEED", + "UK_FIRM_PAY_DISTRIBUTION_SOURCE_COLUMNS", + "UK_FIRM_PAY_DISTRIBUTION_STATUS", + "UK_FIRM_PAY_DISTRIBUTION_TAX_YEAR", + "UKFirmPayDistributionSource", + "assign_uk_firm_pay_below_secondary_threshold", + "read_uk_firm_pay_distribution_source", + "uk_firm_pay_below_threshold_by_section", +] diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_paybill.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_paybill.py new file mode 100644 index 0000000000..91d0a156c2 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_paybill.py @@ -0,0 +1,293 @@ +"""UK firm paybill: employees times the ONS ASHE section mean annual gross pay. + +policyengine-uk's ``firm_paybill`` is a firm's annual Class 1 earnings in +pounds, before employer contributions. The experimental UK firm generator draws +no pay, so this module imputes it as + + firm_paybill = firm_employees x mean annual gross pay of the firm's section + +from one published table: ONS ASHE Table 4.7a (*Annual pay - Gross*), 2025 +revised edition, sheet ``All`` (all employee jobs, full-time and part-time), +column ``Mean``. ASHE annual estimates cover the tax year ending 5 April of the +reference year, so the 2025 edition is tax year 2024-25. The extracted CSV and +its provenance sit in ``tests/fixtures/uk/firm_paybill_2024/`` +(``tools/extract_uk_firm_paybill_table.py`` re-creates it). + +Choices and caveats, all of them assumptions beyond the source: + +- the all-employees mean, not the full-time mean: the generator's employment + is a headcount that includes part-time staff, so a full-time mean would + overstate pay in part-time-heavy sections (accommodation, retail, health); +- every firm in a section pays that section's mean, whatever its size, + region or turnover; +- ASHE annual pay covers employees on adult rates in the same job for more + than a year, which leaves out short-tenure and youth-rate jobs (lower + paid), so the mean leans high; +- the generator's employment comes from ONS employment size bands, which + count working proprietors as well as employees, so a proprietor without + a payroll gets a paybill they would not pay as Class 1 earnings; +- a section ONS does not publish (``x`` or ``:``; section U in 2025) and the + ``UNKNOWN`` section take the table's ``ALL EMPLOYEES`` mean. + ``uk_firm_paybill_fallback_counts`` counts the firms that do. + +The table is for tax year 2024-25 (``UK_FIRM_PAYBILL_TAX_YEAR``), and +``build_uk_firm_dataset`` refuses a paybill source for any other +``data_vintage``. + +Measured on the 20-iteration thinned 2024-25 test build (seed 42), the +paybill is kept, and disclosed, where it is least like a payroll: + +- out-of-frame zero-turnover traders (``in_frame`` false) carry about 2.43 + million weighted employees and about 103.8 billion pounds of paybill, + about 9.7% of the total. In-frame paybill is about 4% below ASHE's jobs + times its all-employees mean, so the build's excess over ASHE comes from + the out-of-frame stratum; +- no firm has a zero headcount, so working proprietors get a paybill: sole + traders carry about 123 billion pounds and partnerships about 45 billion + pounds, about 16% of the total together. + +On the full 2024-25 build (2,946,015 rows, 1,000 epochs) the weighted +paybill is 1.0255 trillion pounds and no firm falls back to the +all-employees mean. +""" + +from __future__ import annotations + +import hashlib +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 + +from microcosm.build.uk_runtime.firm_table import ( + UK_FIRM_SIC_SECTION_UNKNOWN, + UK_FIRM_SIC_SECTIONS, + uk_firm_sic_sections, +) + +#: The extracted ASHE table's file name in a paybill source directory. +UK_FIRM_PAYBILL_FILE = "ashe_section_annual_pay.csv" +#: Its columns, in order. +UK_FIRM_PAYBILL_SOURCE_COLUMNS = ( + "sic_section", + "description", + "jobs_thousand", + "mean_annual_gross_pay_gbp", + "marker", +) +#: ``sic_section`` of the table's ``ALL EMPLOYEES`` row. +UK_FIRM_PAYBILL_ALL_EMPLOYEES = "ALL" +#: The tax year the table's means describe: ASHE 2025 covers the year to +#: 5 April 2025. A build's ``data_vintage`` must match it. +UK_FIRM_PAYBILL_TAX_YEAR = "2024-25" +#: The receipt's ``uk_firm_paybill`` status and method. +UK_FIRM_PAYBILL_STATUS = "assumed" +UK_FIRM_PAYBILL_METHOD = ( + "firm_employees x ONS ASHE 2025 Table 4.7a section mean annual gross pay " + "(all employee jobs)" +) +#: Where a firm's mean pay comes from: its section's published mean, or the +#: all-employees mean for an unpublished or unknown section. +UK_FIRM_PAYBILL_LEVELS = ("section", "all_employees") + +_SECTION_LETTERS = tuple( + section + for section in UK_FIRM_SIC_SECTIONS + if section != UK_FIRM_SIC_SECTION_UNKNOWN +) + + +@dataclass(frozen=True) +class UKFirmPaybillSource: + """Mean annual gross pay (pounds) per SIC section from ASHE Table 4.7a. + + ``section_mean`` holds the sections ONS publishes; ``unpublished`` maps + each other section A-U to its ONS marker. ``sha256`` is the CSV's hash. + """ + + section_mean: Mapping[str, float] + all_employees_mean: float + unpublished: Mapping[str, str] + file: str + sha256: str + + +def read_uk_firm_paybill_source(path: str | Path) -> UKFirmPaybillSource: + """Read the ASHE section table from a directory or the CSV itself. + + Raises ``ValueError`` unless the file has exactly + ``UK_FIRM_PAYBILL_SOURCE_COLUMNS``, each of sections A-U once and one + ``ALL`` row, a positive finite mean wherever no ONS marker stands, and + no mean beside a marker. + """ + + path = Path(path) + if path.is_dir(): + path = path / UK_FIRM_PAYBILL_FILE + payload = path.read_bytes() + frame = pd.read_csv(path, dtype=str, keep_default_na=False) + if tuple(frame.columns) != UK_FIRM_PAYBILL_SOURCE_COLUMNS: + raise ValueError( + f"UK firm paybill source columns {list(frame.columns)} are not " + f"{list(UK_FIRM_PAYBILL_SOURCE_COLUMNS)}." + ) + keys = frame["sic_section"].str.strip().tolist() + expected = [*_SECTION_LETTERS, UK_FIRM_PAYBILL_ALL_EMPLOYEES] + if sorted(keys) != sorted(expected): + raise ValueError( + f"UK firm paybill source rows {keys} are not sections A-U and " + f"{UK_FIRM_PAYBILL_ALL_EMPLOYEES!r}, once each." + ) + means: dict[str, float] = {} + unpublished: dict[str, str] = {} + for key, mean, marker in zip( + keys, + frame["mean_annual_gross_pay_gbp"].str.strip(), + frame["marker"].str.strip(), + strict=True, + ): + if marker: + if mean: + raise ValueError( + f"UK firm paybill section {key} has a mean and marker {marker!r}." + ) + unpublished[key] = marker + continue + try: + value = float(mean) + except ValueError: + raise ValueError( + f"UK firm paybill section {key} mean {mean!r} is not a number." + ) from None + if not np.isfinite(value) or value <= 0: + raise ValueError(f"UK firm paybill section {key} mean must be positive.") + means[key] = value + if UK_FIRM_PAYBILL_ALL_EMPLOYEES not in means: + raise ValueError("UK firm paybill source has no all-employees mean.") + all_employees = means.pop(UK_FIRM_PAYBILL_ALL_EMPLOYEES) + return UKFirmPaybillSource( + section_mean=MappingProxyType(dict(sorted(means.items()))), + all_employees_mean=all_employees, + unpublished=MappingProxyType(dict(sorted(unpublished.items()))), + file=path.name, + sha256=hashlib.sha256(payload).hexdigest(), + ) + + +def _employees_and_sections(frame: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]: + """Headcount and ``SICSection`` names from a firm table or generator rows.""" + + if {"firm_employees", "firm_sic_section"} <= set(frame.columns): + employees = frame["firm_employees"].to_numpy() + sections = frame["firm_sic_section"].astype(str).to_numpy(object) + if not np.isin(sections, UK_FIRM_SIC_SECTIONS).all(): + raise ValueError( + "UK firm firm_sic_section must be SICSection member names." + ) + elif {"employment", "sic_code"} <= set(frame.columns): + employees = frame["employment"].to_numpy() + sections = uk_firm_sic_sections(frame["sic_code"]) + else: + raise ValueError( + "UK firm paybill needs firm_employees and firm_sic_section, or " + "employment and sic_code." + ) + as_float = employees.astype(np.float64) + if ( + not np.all(np.isfinite(as_float)) + or np.any(as_float != np.round(as_float)) + or np.any(as_float < 0) + ): + raise ValueError("UK firm employees must be non-negative whole numbers.") + return as_float.astype(np.int64), sections + + +def _uses_section_mean(sections: np.ndarray, source: UKFirmPaybillSource) -> np.ndarray: + return np.isin(sections, list(source.section_mean)) + + +def uk_firm_paybill_mean_pay( + table_or_firms: pd.DataFrame, source: UKFirmPaybillSource +) -> np.ndarray: + """Each row's mean annual gross pay (pounds), in row order. + + A section ``source`` publishes gives its mean; any other section, + ``UNKNOWN`` included, gives ``source.all_employees_mean``. + """ + + _, sections = _employees_and_sections(table_or_firms) + lookup = {**source.section_mean} + return np.array( + [lookup.get(section, source.all_employees_mean) for section in sections], + dtype=np.float64, + ) + + +def assign_uk_firm_paybill( + table_or_firms: pd.DataFrame, source: UKFirmPaybillSource +) -> np.ndarray: + """Annual paybill in pounds per row, in row order: employees x mean pay. + + ``table_or_firms`` is a policyengine-uk firm table (``firm_employees``, + ``firm_sic_section``) or the generator's rows (``employment``, + ``sic_code``). A firm with no employees has a zero paybill. Sections + without a published mean use the all-employees mean; see + ``uk_firm_paybill_fallback_counts``. + """ + + employees, _ = _employees_and_sections(table_or_firms) + return employees * uk_firm_paybill_mean_pay(table_or_firms, source) + + +def uk_firm_paybill_fallback_counts( + table_or_firms: pd.DataFrame, source: UKFirmPaybillSource +) -> pd.DataFrame: + """Firms, weight and paybill per mean-pay level. + + One row per ``UK_FIRM_PAYBILL_LEVELS`` entry with ``firms`` (rows), + ``firms_with_employees`` (rows with a positive headcount), ``weight`` + (sum of ``firm_weight``, or of ones when the frame has none) and + ``weighted_paybill_gbp``. + """ + + employees, sections = _employees_and_sections(table_or_firms) + level = np.where(_uses_section_mean(sections, source), 0, 1) + weight = ( + table_or_firms["firm_weight"].to_numpy(dtype=np.float64) + if "firm_weight" in table_or_firms.columns + else np.ones(len(table_or_firms), dtype=np.float64) + ) + paybill = assign_uk_firm_paybill(table_or_firms, source) + n_levels = len(UK_FIRM_PAYBILL_LEVELS) + firms = np.bincount(level, minlength=n_levels) + employing = np.bincount(level, weights=employees > 0, minlength=n_levels) + weights = np.bincount(level, weights=weight, minlength=n_levels) + totals = np.bincount(level, weights=weight * paybill, minlength=n_levels) + return pd.DataFrame( + { + "level": list(UK_FIRM_PAYBILL_LEVELS), + "firms": firms.astype(np.int64), + "firms_with_employees": employing.astype(np.int64), + "weight": weights, + "weighted_paybill_gbp": totals, + } + ) + + +__all__ = [ + "UK_FIRM_PAYBILL_ALL_EMPLOYEES", + "UK_FIRM_PAYBILL_FILE", + "UK_FIRM_PAYBILL_LEVELS", + "UK_FIRM_PAYBILL_METHOD", + "UK_FIRM_PAYBILL_SOURCE_COLUMNS", + "UK_FIRM_PAYBILL_STATUS", + "UK_FIRM_PAYBILL_TAX_YEAR", + "UKFirmPaybillSource", + "assign_uk_firm_paybill", + "read_uk_firm_paybill_source", + "uk_firm_paybill_fallback_counts", + "uk_firm_paybill_mean_pay", +] diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_paybill_anchor.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_paybill_anchor.py new file mode 100644 index 0000000000..18dd592a19 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_paybill_anchor.py @@ -0,0 +1,96 @@ +"""UK paybill anchors: national accounts wages and salaries and PAYE RTI pay (report-only). + +The opt-in paybill (``firm_paybill.py``) is headcount times ASHE section mean +pay, and its binding guard is the ratio to ASHE annual jobs times mean pay +(0.85-1.25). That guard shares ASHE's means with the paybill itself, so only +the jobs count is independent. The anchors here are two published paybill +totals that do not depend on ASHE: + +- ONS DTWL, UK wages and salaries (ESA D.11), calendar 2024, whole economy; +- ONS/HMRC PAYE RTI aggregate pay, tax year 2024-25 (sum of twelve months, + not seasonally adjusted), with the mean payrolled employee count. + +:func:`uk_firm_paybill_anchor_ratios` divides a build's weighted paybill and +employees by them. The ratios are reported, never used as a target or a +guard. Neither anchor is the firm table's concept: both include employees of +every employer (the firm table's public sector is partial), D.11 includes +wages in kind, and the RTI count is of payrolled employees (persons) in each month, averaged. +""" + +from __future__ import annotations + +import hashlib +import json +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 + +UK_FIRM_PAYBILL_ANCHOR_FILE = "paybill_anchors.csv" +UK_FIRM_PAYBILL_ANCHORS = ( + "ons_d11_wages_and_salaries", + "paye_rti_aggregate_pay", + "paye_rti_payrolled_employees", +) + + +@dataclass(frozen=True) +class UKFirmPaybillAnchors: + """Anchor values by name (pounds, or persons for the employee count).""" + + values: Mapping[str, float] + sha256: str + + +def read_uk_firm_paybill_anchors(path: str | Path) -> UKFirmPaybillAnchors: + """Read ``paybill_anchors.csv``; refuse a file whose sha256 differs from provenance.""" + + directory = Path(path) + payload = (directory / UK_FIRM_PAYBILL_ANCHOR_FILE).read_bytes() + digest = hashlib.sha256(payload).hexdigest() + provenance = json.loads((directory / "provenance.json").read_text()) + if provenance["files"][UK_FIRM_PAYBILL_ANCHOR_FILE]["sha256"] != digest: + raise ValueError( + f"{UK_FIRM_PAYBILL_ANCHOR_FILE} sha256 differs from provenance.json." + ) + frame = pd.read_csv(directory / UK_FIRM_PAYBILL_ANCHOR_FILE) + if tuple(frame["anchor"]) != UK_FIRM_PAYBILL_ANCHORS: + raise ValueError(f"paybill anchors must be {list(UK_FIRM_PAYBILL_ANCHORS)}.") + values = dict(zip(frame["anchor"], frame["value"].astype(np.float64), strict=True)) + if not all(v > 0 for v in values.values()): + raise ValueError("paybill anchors must be positive.") + return UKFirmPaybillAnchors(values=MappingProxyType(values), sha256=digest) + + +def uk_firm_paybill_anchor_ratios( + paybill: np.ndarray, + employees: np.ndarray, + weight: np.ndarray, + anchors: UKFirmPaybillAnchors, +) -> dict[str, float | str]: + """Weighted paybill and employees over each anchor (report-only).""" + + weight = np.asarray(weight, np.float64) + total_pay = float((np.asarray(paybill, np.float64) * weight).sum()) + total_employees = float((np.asarray(employees, np.float64) * weight).sum()) + v = anchors.values + return { + "weighted_paybill_gbp": total_pay, + "weighted_employees": total_employees, + "paybill_over_ons_d11": total_pay / v["ons_d11_wages_and_salaries"], + "paybill_over_paye_rti": total_pay / v["paye_rti_aggregate_pay"], + "employees_over_paye_rti": total_employees / v["paye_rti_payrolled_employees"], + "status": "report_only", + } + + +__all__ = [ + "UK_FIRM_PAYBILL_ANCHORS", + "UK_FIRM_PAYBILL_ANCHOR_FILE", + "UKFirmPaybillAnchors", + "read_uk_firm_paybill_anchors", + "uk_firm_paybill_anchor_ratios", +] 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..81b07ffd57 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_policyengine_uk_rules.py @@ -0,0 +1,529 @@ +"""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 (capital +expenditure, the bank flag; paybill, profit, R&D and rateable value unless +the build is given ``--paybill-dir``, ``--profit-dir``, +``--rd-tax-credits-dir`` and ``--rateable-value-dir``) take policyengine-uk's +zero defaults, so the bank surcharge is zero, corporation tax is zero without +profit, business rates are zero without rateable value, and employer NIC, the +levy and auto-enrolment are zero without paybill. +``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_profit.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_profit.py new file mode 100644 index 0000000000..2b7a547396 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_profit.py @@ -0,0 +1,637 @@ +"""UK firm taxable profit: an opt-in draw from HMRC's liability bands. + +policyengine-uk's ``firm_taxable_trading_profit`` is unset by the experimental +UK firm build, so every company's corporation tax is 0. This module imputes +it for companies (``ons_legal_status`` 1, policyengine-uk ``COMPANY``) from +one published table, HMRC *Corporation Tax Statistics 2026*, Tables 9A and 9B +(*Tax liability by band*), financial year 2024-25: the number of companies and +the total liability in each of thirteen liability bands, and the number with +no liability. The extracted CSV and its provenance sit in +``tests/fixtures/uk/firm_ct_2024/`` (``tools/extract_uk_firm_ct_tables.py`` +re-creates it). ``build_uk_firm_dataset(profit_dir=...)`` and +``tools/build_uk_firms.py --profit-dir`` turn it on; the status of the +result is ``assumed``. + +**Inversion.** With no associated companies, no exempt distributions and a +twelve-month accounting period inside the financial year, policyengine-uk's +``corporation_tax_before_credits`` on taxable total profits ``p`` is + + T(p) = s p p <= L + = m p - f (U - p) L < p <= U + = m p p > U + +with main rate ``m``, small profits rate ``s``, marginal relief fraction ``f`` +and lower and upper limits ``L``, ``U`` (``UK_FIRM_PROFIT_CT_SCHEDULE``; the +values are policyengine-uk's parameters for the financial year 2024). ``T`` is +continuous and strictly increasing, so a liability ``t`` has one profit: + + p = t / s t <= s L + = (t + f U) / (m + f) s L < t <= m U + = t / m t > m U + +(``uk_corporation_tax_profit``). Each liability band's edges map through it to +a taxable-profit band (``uk_firm_profit_bands``). + +**Assignment.** Companies are ranked by turnover within their SIC section +(weighted, highest first; equal turnovers are ordered by a uniform draw from +this module's own random stream, seeded by ``UK_FIRM_PROFIT_SEED`` and drawn +in ``firm_id`` order, never the generator's stream). The within-section +weighted rank fractions are pooled, and bands are allotted from the top of +the pooled ranking: the highest band takes the first rows whose cumulative +weight reaches the band's published number of companies, and so on down; the +companies left over have no liability and a taxable profit of 0. A row +belongs to the band holding the midpoint of its weight, so a band's weighted +count differs from the table's by at most about one row's weight at each edge. + +Within a band, liabilities rise with rank and their weighted total is the +band's published total: in a closed band ``(a, b]`` the liability is +``a + (b - a) x`` with ``x`` a power of the within-band rank fraction, the +power set by the band mean and ``x`` then shifted to make the mean exact; in +the open top band the excess over the floor is exponential in shape, scaled to +the mean. Where the published total over the build's weighted count falls +outside the band (the build holds too few or too many companies there), the +table's own band mean is used instead and the diagnostics say so. + +Assumptions beyond the source, all of them: + +- the tables' "tax liability" is Corporation Tax *payable* (after double + taxation relief, with ring fence tax and the supplementary charge), read + here as ``T(p)``; +- the imputed amount is profits chargeable to corporation tax, after capital + allowances, reliefs and losses, standing in for + ``firm_taxable_trading_profit`` while policyengine-uk's capital allowances, + non-trading profits, losses and R&D inputs are unset; a company with no + liability gets 0, never a loss; +- profit rises with turnover rank inside every SIC section, and every + section has the same share of companies in each band: the sector pattern + of liability (Tables 6A and 6B, held out in ``ct_sic_sections.csv``) is + not used, so the financial sector's share of liability is not reproduced; +- HMRC counts 3.3 million companies filing a return, many of them dormant + or outside the VAT and PAYE frame; the build's companies are ONS frame + enterprises. Positive-liability band counts are matched in absolute terms + and the zero band is whatever the build has left over; +- sole traders, partnerships and other bodies get 0 (policyengine-uk charges + corporation tax on ``COMPANY`` only); +- public corporations (``ons_legal_status`` 4) export as ``COMPANY``, so they + are liable to corporation tax, but they get 0 profit: HMRC's liability + bands are allotted to status 1 only. Their corporation tax is therefore 0, + an understatement. Rows with only ``firm_legal_form`` (no + ``ons_legal_status``) count every ``COMPANY``, status 4 included. + +HMRC's sector tables do not isolate banks (the finest split is SIC division +64, *Financial service activities, except insurance and pension funding*), so +``firm_is_bank`` stays unset. +""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +import pandas as pd + +from microcosm.build.uk_runtime.firm_table import uk_firm_sic_sections + +#: The extracted liability-band table's file name in a profit source directory. +UK_FIRM_PROFIT_FILE = "ct_liability_bands.csv" +#: Its columns, in order. +UK_FIRM_PROFIT_SOURCE_COLUMNS = ( + "band", + "lower_gbp", + "upper_gbp", + "companies", + "liability_gbp_million", +) +#: ``band`` of the rows that are not a positive-liability band. +UK_FIRM_PROFIT_ZERO_BAND = "0" +UK_FIRM_PROFIT_POSITIVE_ROW = "POSITIVE" +UK_FIRM_PROFIT_ALL_RETURNS_ROW = "ALL_RETURNS" +#: The financial year the table describes (1 April 2024 to 31 March 2025). +UK_FIRM_PROFIT_FINANCIAL_YEAR = "2024-25" +#: The receipt status and method of the imputed profit. +UK_FIRM_PROFIT_STATUS = "assumed" +UK_FIRM_PROFIT_METHOD = ( + "HMRC Corporation Tax Statistics 2026 Tables 9A/9B liability bands " + "(2024-25), inverted through the corporation tax rate schedule and " + "allotted to companies by turnover rank within SIC section" +) +#: Seed of this module's own random stream (tie-breaks between equal +#: turnovers). It is not the generator's seed and shares no state with it. +UK_FIRM_PROFIT_SEED = 20_240_904 +#: ONS legal status code of a company (policyengine-uk ``COMPANY``). +UK_FIRM_PROFIT_COMPANY_LEGAL_STATUS = 1 +_COMPANY_LEGAL_FORM = "COMPANY" +_GBP_PER_MILLION = 1_000_000.0 + + +@dataclass(frozen=True) +class UKCorporationTaxSchedule: + """The corporation tax rate schedule on taxable total profits.""" + + main_rate: float + small_profits_rate: float + marginal_relief_fraction: float + lower_limit: float + upper_limit: float + + def __post_init__(self) -> None: + low = self.small_profits_rate * self.lower_limit + high = self.main_rate * self.lower_limit - self.marginal_relief_fraction * ( + self.upper_limit - self.lower_limit + ) + if not ( + 0 < self.small_profits_rate <= self.main_rate + and self.marginal_relief_fraction >= 0 + and 0 < self.lower_limit < self.upper_limit + ): + raise ValueError("UK corporation tax schedule is not ordered.") + if not np.isclose(low, high, rtol=1e-12, atol=1e-9): + raise ValueError( + "UK corporation tax schedule is not continuous at the lower limit." + ) + + +#: policyengine-uk's ``gov.hmrc.corporation_tax`` parameters for the financial +#: year 2024 (values dated 2023-04-01): ``main_rate`` (Finance Act 2021 +#: s. 6(2)(b)), ``small_profits_rate`` (s. 7(2)(a)), ``marginal_relief. +#: fraction`` (s. 7(2)(b), 3/200ths), ``marginal_relief.lower_limit`` and +#: ``upper_limit`` (Corporation Tax Act 2010 s. 18D). Read from the +#: policyengine-uk checkout at 57a99a67ac26 on 2026-11-22. +UK_FIRM_PROFIT_CT_SCHEDULE = UKCorporationTaxSchedule( + main_rate=0.25, + small_profits_rate=0.19, + marginal_relief_fraction=0.015, + lower_limit=50_000.0, + upper_limit=250_000.0, +) + + +def uk_corporation_tax_liability( + profit: np.ndarray | float, + schedule: UKCorporationTaxSchedule = UK_FIRM_PROFIT_CT_SCHEDULE, +) -> np.ndarray: + """Corporation tax (pounds) on taxable total profits ``profit``. + + The small profits rate up to the lower limit, the main rate less marginal + relief up to the upper limit, the main rate above it; 0 on no profit. + One company, no associates, no exempt distributions, a full year. + """ + + p = np.maximum(np.asarray(profit, dtype=np.float64), 0.0) + relief = schedule.marginal_relief_fraction * (schedule.upper_limit - p) + return np.select( + [p <= schedule.lower_limit, p <= schedule.upper_limit], + [p * schedule.small_profits_rate, p * schedule.main_rate - relief], + default=p * schedule.main_rate, + ) + + +def uk_corporation_tax_profit( + liability: np.ndarray | float, + schedule: UKCorporationTaxSchedule = UK_FIRM_PROFIT_CT_SCHEDULE, +) -> np.ndarray: + """Taxable total profits (pounds) whose corporation tax is ``liability``. + + The inverse of ``uk_corporation_tax_liability`` on non-negative amounts. + """ + + t = np.maximum(np.asarray(liability, dtype=np.float64), 0.0) + small_top = schedule.small_profits_rate * schedule.lower_limit + main_floor = schedule.main_rate * schedule.upper_limit + taper = (t + schedule.marginal_relief_fraction * schedule.upper_limit) / ( + schedule.main_rate + schedule.marginal_relief_fraction + ) + return np.select( + [t <= small_top, t <= main_floor], + [t / schedule.small_profits_rate, taper], + default=t / schedule.main_rate, + ) + + +@dataclass(frozen=True) +class UKFirmProfitBand: + """One positive-liability band: ``lower`` exclusive, ``upper`` inclusive + (``inf`` for the open band), pounds; ``liability`` in pounds.""" + + label: str + lower: float + upper: float + companies: float + liability: float + + +@dataclass(frozen=True) +class UKFirmProfitSource: + """HMRC liability bands, lowest first, with the table's own totals.""" + + bands: tuple[UKFirmProfitBand, ...] + zero_companies: float + positive_companies: float + positive_liability: float + all_returns: float + file: str + sha256: str + + +def _number(text: str, where: str) -> float: + try: + value = float(text) + except ValueError: + raise ValueError( + f"UK firm profit source {where} {text!r} is not a number." + ) from None + if not np.isfinite(value) or value < 0: + raise ValueError(f"UK firm profit source {where} must be non-negative.") + return value + + +def read_uk_firm_profit_source(path: str | Path) -> UKFirmProfitSource: + """Read the liability-band table from a directory or the CSV itself. + + Raises ``ValueError`` unless the file has exactly + ``UK_FIRM_PROFIT_SOURCE_COLUMNS``; a ``0`` row, contiguous bands rising + from 0 to one open band, then ``POSITIVE`` and ``ALL_RETURNS`` rows; a + positive count and liability in every band; and each band's mean + liability inside the band. + """ + + path = Path(path) + if path.is_dir(): + path = path / UK_FIRM_PROFIT_FILE + payload = path.read_bytes() + frame = pd.read_csv(path, dtype=str, keep_default_na=False) + if tuple(frame.columns) != UK_FIRM_PROFIT_SOURCE_COLUMNS: + raise ValueError( + f"UK firm profit source columns {list(frame.columns)} are not " + f"{list(UK_FIRM_PROFIT_SOURCE_COLUMNS)}." + ) + records = {str(row.band).strip(): row for row in frame.itertuples(index=False)} + if len(records) != len(frame): + raise ValueError("UK firm profit source repeats a band.") + special = ( + UK_FIRM_PROFIT_ZERO_BAND, + UK_FIRM_PROFIT_POSITIVE_ROW, + UK_FIRM_PROFIT_ALL_RETURNS_ROW, + ) + for key in special: + if key not in records: + raise ValueError(f"UK firm profit source has no {key!r} row.") + bands: list[UKFirmProfitBand] = [] + edge = 0.0 + for label, row in records.items(): + if label in special: + continue + lower = _number(row.lower_gbp, f"band {label} lower edge") + if lower != edge or not np.isfinite(edge): + raise ValueError(f"UK firm profit band {label} does not follow on.") + upper = ( + _number(row.upper_gbp, f"band {label} upper edge") + if row.upper_gbp.strip() + else np.inf + ) + companies = _number(row.companies, f"band {label} companies") + liability = ( + _number(row.liability_gbp_million, f"band {label} liability") + * _GBP_PER_MILLION + ) + if not upper > lower or companies <= 0 or liability <= 0: + raise ValueError(f"UK firm profit band {label} is empty or inverted.") + if not lower < liability / companies < upper: + raise ValueError( + f"UK firm profit band {label} mean liability is outside the band." + ) + bands.append(UKFirmProfitBand(label, lower, upper, companies, liability)) + edge = upper + if not bands or np.isfinite(edge): + raise ValueError("UK firm profit source must end with one open band.") + positive = records[UK_FIRM_PROFIT_POSITIVE_ROW] + return UKFirmProfitSource( + bands=tuple(bands), + zero_companies=_number( + records[UK_FIRM_PROFIT_ZERO_BAND].companies, "zero-band companies" + ), + positive_companies=_number(positive.companies, "positive companies"), + positive_liability=_number(positive.liability_gbp_million, "positive liability") + * _GBP_PER_MILLION, + all_returns=_number( + records[UK_FIRM_PROFIT_ALL_RETURNS_ROW].companies, "all returns" + ), + file=path.name, + sha256=hashlib.sha256(payload).hexdigest(), + ) + + +def uk_firm_profit_bands( + source: UKFirmProfitSource, + schedule: UKCorporationTaxSchedule = UK_FIRM_PROFIT_CT_SCHEDULE, +) -> pd.DataFrame: + """Each liability band with its taxable-profit band, lowest first. + + ``profit_lower_gbp`` and ``profit_upper_gbp`` are the liability edges + through ``uk_corporation_tax_profit``; ``mean_liability_gbp`` and + ``mean_profit_gbp`` describe a company at the band's mean liability. + """ + + lower = np.array([band.lower for band in source.bands]) + upper = np.array([band.upper for band in source.bands]) + companies = np.array([band.companies for band in source.bands]) + liability = np.array([band.liability for band in source.bands]) + finite_upper = np.where(np.isfinite(upper), upper, 0.0) + return pd.DataFrame( + { + "band": [band.label for band in source.bands], + "liability_lower_gbp": lower, + "liability_upper_gbp": upper, + "profit_lower_gbp": uk_corporation_tax_profit(lower, schedule), + "profit_upper_gbp": np.where( + np.isfinite(upper), + uk_corporation_tax_profit(finite_upper, schedule), + np.inf, + ), + "companies": companies, + "liability_gbp": liability, + "mean_liability_gbp": liability / companies, + "mean_profit_gbp": uk_corporation_tax_profit( + liability / companies, schedule + ), + } + ) + + +@dataclass(frozen=True) +class _Allotment: + """Per row, in row order: band index (-1 for none) and liability.""" + + band: np.ndarray + liability: np.ndarray + company: np.ndarray + weight: np.ndarray + sections: np.ndarray + table_mean_bands: tuple[int, ...] + + +def _columns(frame: pd.DataFrame) -> tuple[np.ndarray, ...]: + """Company flag, weight, turnover, section and ``firm_id`` per row.""" + + names = set(frame.columns) + if "firm_id" not in names: + raise ValueError("UK firm profit needs firm_id.") + firm_id = frame["firm_id"].to_numpy() + if not pd.Index(firm_id).is_unique: + raise ValueError("UK firm profit needs one row per firm_id.") + if "ons_legal_status" in names: + company = ( + frame["ons_legal_status"].to_numpy() == UK_FIRM_PROFIT_COMPANY_LEGAL_STATUS + ) + elif "firm_legal_form" in names: + company = ( + frame["firm_legal_form"].astype(str).to_numpy(object) == _COMPANY_LEGAL_FORM + ) + else: + raise ValueError("UK firm profit needs ons_legal_status or firm_legal_form.") + turnover_column = next( + (name for name in ("annual_turnover_k", "firm_turnover") if name in names), + None, + ) + if turnover_column is None: + raise ValueError("UK firm profit needs annual_turnover_k or firm_turnover.") + turnover = frame[turnover_column].to_numpy(np.float64) + if "firm_sic_section" in names: + sections = frame["firm_sic_section"].astype(str).to_numpy(object) + elif "sic_code" in names: + sections = uk_firm_sic_sections(frame["sic_code"]) + else: + raise ValueError("UK firm profit needs firm_sic_section or sic_code.") + weight = ( + frame["firm_weight"].to_numpy(np.float64) + if "firm_weight" in names + else np.ones(len(frame), dtype=np.float64) + ) + if not np.all(np.isfinite(turnover)) or not np.all(np.isfinite(weight)): + raise ValueError("UK firm profit needs finite turnover and weights.") + if np.any(weight < 0): + raise ValueError("UK firm profit needs non-negative weights.") + return company, weight, turnover, sections, firm_id + + +def _band_liabilities( + weight: np.ndarray, band: UKFirmProfitBand +) -> tuple[np.ndarray, bool]: + """Liabilities of one band's rows, given top rank first. + + Returns the liabilities and whether the table's band mean stood in for + the published total over the weighted count. + """ + + total = weight.sum() + mean = band.liability / total if total > 0 else np.inf + table_mean = not band.lower < mean < band.upper + if table_mean: + mean = band.liability / band.companies + if total <= 0: + return np.full(len(weight), mean), table_mean + # Rank fraction in (0, 1): near 1 at the top of the band. + fraction = 1.0 - (np.cumsum(weight) - weight / 2.0) / total + fraction = np.clip(fraction, 1e-12, 1.0 - 1e-12) + if np.isfinite(band.upper): + target = (mean - band.lower) / (band.upper - band.lower) + shape = fraction ** ((1.0 - target) / target) + got = np.average(shape, weights=weight) + if got >= target: + shape = shape * (target / got) + else: + shape = 1.0 - (1.0 - shape) * ((1.0 - target) / (1.0 - got)) + return band.lower + (band.upper - band.lower) * shape, table_mean + excess = -np.log1p(-fraction) + excess = excess / np.average(excess, weights=weight) + return band.lower + (mean - band.lower) * excess, table_mean + + +def _allot(frame: pd.DataFrame, source: UKFirmProfitSource, seed: int) -> _Allotment: + company, weight, turnover, sections, firm_id = _columns(frame) + n = len(frame) + # One draw per row in firm_id order, so row order never changes a draw. + draws = np.empty(n, dtype=np.float64) + draws[np.argsort(firm_id, kind="stable")] = np.random.default_rng(seed).random(n) + + rows = np.flatnonzero(company & (weight > 0)) + band_index = np.full(n, -1, dtype=np.int64) + liability = np.zeros(n, dtype=np.float64) + table_mean: list[int] = [] + if rows.size: + # Weighted rank fraction within section, 0 at the highest turnover. + codes = pd.factorize(sections[rows], sort=True)[0] + order = np.lexsort((draws[rows], -turnover[rows], codes)) + ordered_weight = weight[rows][order] + ordered_codes = codes[order] + running = np.cumsum(ordered_weight) + section_total = np.bincount(ordered_codes, weights=ordered_weight) + before = np.concatenate(([0.0], np.cumsum(section_total)[:-1])) + rank = np.empty(rows.size, dtype=np.float64) + rank[order] = ( + running - ordered_weight / 2.0 - before[ordered_codes] + ) / section_total[ordered_codes] + # Pool the sections and allot bands from the top by cumulative weight. + pooled = np.lexsort((draws[rows], rank)) + pooled_weight = weight[rows][pooled] + midpoint = np.cumsum(pooled_weight) - pooled_weight / 2.0 + top_down = source.bands[::-1] + edges = np.cumsum([band.companies for band in top_down]) + position = np.searchsorted(edges, midpoint, side="right") + n_bands = len(top_down) + for step, band in enumerate(top_down): + members = np.flatnonzero(position == step) + if not members.size: + continue + index = n_bands - 1 - step + values, used_table_mean = _band_liabilities(pooled_weight[members], band) + target = rows[pooled[members]] + band_index[target] = index + liability[target] = values + if used_table_mean: + table_mean.append(index) + return _Allotment( + band=band_index, + liability=liability, + company=company, + weight=weight, + sections=np.asarray(sections, dtype=object), + table_mean_bands=tuple(sorted(table_mean)), + ) + + +def assign_uk_firm_taxable_profit( + table_or_firms: pd.DataFrame, + source: UKFirmProfitSource, + *, + schedule: UKCorporationTaxSchedule = UK_FIRM_PROFIT_CT_SCHEDULE, + seed: int = UK_FIRM_PROFIT_SEED, +) -> np.ndarray: + """Taxable profit in pounds per row, in row order. + + ``table_or_firms`` is an extended policyengine-uk firm table or the + generator's rows after the attribute draw: ``firm_id``, a legal form + (``ons_legal_status`` or ``firm_legal_form``), a turnover + (``annual_turnover_k`` or ``firm_turnover``; only its order matters), a + section (``firm_sic_section`` or ``sic_code``) and, optionally, + ``firm_weight`` (ones without it). A row that is not a company, or has + no weight, or falls below the lowest band, gets 0. The result does not + depend on row order. + """ + + allotment = _allot(table_or_firms, source, seed) + return np.where( + allotment.band >= 0, + uk_corporation_tax_profit(allotment.liability, schedule), + 0.0, + ) + + +def uk_firm_profit_diagnostics( + table_or_firms: pd.DataFrame, + source: UKFirmProfitSource, + *, + schedule: UKCorporationTaxSchedule = UK_FIRM_PROFIT_CT_SCHEDULE, + seed: int = UK_FIRM_PROFIT_SEED, +) -> pd.DataFrame: + """The draw against the table, one row per band, lowest first. + + The first row is the ``0`` band (companies with no liability; the table's + count there covers every company filing a return, the build's only its + own companies). ``weighted_liability_gbp`` is the rate schedule applied + to the assigned profits, so it checks the inversion as well as the + allotment; ``weighted_profit_gbp`` is the weighted assigned profit. + ``table_mean_used`` marks a band whose published total over the build's + weighted count fell outside the band, so the table's band mean was used. + """ + + allotment = _allot(table_or_firms, source, seed) + profit = np.where( + allotment.band >= 0, + uk_corporation_tax_profit(allotment.liability, schedule), + 0.0, + ) + tax = uk_corporation_tax_liability(profit, schedule) + n_bands = len(source.bands) + # Slot 0 is the zero band; companies only. + slot = allotment.band[allotment.company] + 1 + weight = allotment.weight[allotment.company] + weighted = np.bincount(slot, weights=weight, minlength=n_bands + 1) + liability = np.bincount( + slot, weights=weight * tax[allotment.company], minlength=n_bands + 1 + ) + profits = np.bincount( + slot, weights=weight * profit[allotment.company], minlength=n_bands + 1 + ) + table_companies = np.array( + [source.zero_companies, *(band.companies for band in source.bands)] + ) + table_liability = np.array([0.0, *(band.liability for band in source.bands)]) + used = np.zeros(n_bands + 1, dtype=bool) + used[[index + 1 for index in allotment.table_mean_bands]] = True + return pd.DataFrame( + { + "band": [UK_FIRM_PROFIT_ZERO_BAND, *(b.label for b in source.bands)], + "table_companies": table_companies, + "weighted_companies": weighted, + "table_liability_gbp": table_liability, + "weighted_liability_gbp": liability, + "weighted_profit_gbp": profits, + "table_mean_used": used, + } + ) + + +def uk_firm_profit_section_liability( + table_or_firms: pd.DataFrame, + source: UKFirmProfitSource, + *, + schedule: UKCorporationTaxSchedule = UK_FIRM_PROFIT_CT_SCHEDULE, + seed: int = UK_FIRM_PROFIT_SEED, +) -> pd.DataFrame: + """Weighted companies, companies with a liability, and liability per + ``SICSection`` name, for a check against HMRC's held-out sector table.""" + + allotment = _allot(table_or_firms, source, seed) + tax = uk_corporation_tax_liability( + uk_corporation_tax_profit(allotment.liability, schedule), schedule + ) + tax = np.where(allotment.band >= 0, tax, 0.0) + frame = pd.DataFrame( + { + "sic_section": allotment.sections[allotment.company], + "weighted_companies": allotment.weight[allotment.company], + "weighted_companies_with_liability": ( + allotment.weight * (allotment.band >= 0) + )[allotment.company], + "weighted_liability_gbp": (allotment.weight * tax)[allotment.company], + } + ) + return frame.groupby("sic_section", as_index=False, sort=True).sum() + + +__all__ = [ + "UK_FIRM_PROFIT_ALL_RETURNS_ROW", + "UK_FIRM_PROFIT_COMPANY_LEGAL_STATUS", + "UK_FIRM_PROFIT_CT_SCHEDULE", + "UK_FIRM_PROFIT_FILE", + "UK_FIRM_PROFIT_FINANCIAL_YEAR", + "UK_FIRM_PROFIT_METHOD", + "UK_FIRM_PROFIT_POSITIVE_ROW", + "UK_FIRM_PROFIT_SEED", + "UK_FIRM_PROFIT_SOURCE_COLUMNS", + "UK_FIRM_PROFIT_STATUS", + "UK_FIRM_PROFIT_ZERO_BAND", + "UKCorporationTaxSchedule", + "UKFirmProfitBand", + "UKFirmProfitSource", + "assign_uk_firm_taxable_profit", + "read_uk_firm_profit_source", + "uk_corporation_tax_liability", + "uk_corporation_tax_profit", + "uk_firm_profit_bands", + "uk_firm_profit_diagnostics", + "uk_firm_profit_section_liability", +] diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_public_sector.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_public_sector.py new file mode 100644 index 0000000000..d637ce9cb1 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_public_sector.py @@ -0,0 +1,338 @@ +"""UK firm public sector employment: an opt-in rescale to ONS headcounts. + +The experimental UK firm generator draws ``ons_legal_status`` from the ONS +*UK business: activity, size and location* tables, which count VAT- and +PAYE-registered enterprises. Central government (status 5) and local +authority (status 6) rows are therefore few and small: on the full 2024-25 +build they carry about 0.66 million weighted employees (0.47 million and 0.19 +million), where ONS counts about six million in central and local government. Employer NIC and the apprenticeship levy, +which follow the paybill, come out low for public bodies. + +``scale_uk_firm_public_sector_employment`` multiplies the headcount of the +existing status 5 and status 6 rows so that their weighted employment equals +the ONS *Public sector employment, UK: March 2025* Table 1 headcounts for +central government (series G6NQ) and local government (series G6NT). The +extracted CSV and its provenance sit in +``tests/fixtures/uk/firm_public_sector_2025/`` +(``tools/extract_uk_firm_public_sector_table.py`` re-creates it). + +Nothing calls this by default. It is an assumption, not an estimate, and it +has costs a caller should know before opting in: + +- no row is added and no weight moves: the same few bodies each grow by one + factor per status, so their headcounts leave the generator's size bands + (a status 5 row can reach tens of thousands of employees) while turnover + and every other column stay as drawn; +- the ONS public sector total covers the National Health Service, + education, police and HM Forces (the workbook's Table 2), whose staff the + generator may already hold under other statuses (companies, non-profit + bodies) through the business counts; those rows are not reduced, so total + weighted employment rises by about the amount added and passes the ASHE + jobs count; +- public corporations (status 4) are left alone; +- the headcount is the seasonally adjusted March 2025 quarter, the last + quarter of tax year 2024-25, not a tax-year average; +- a paybill computed before the rescale is stale: assign the paybill after. + +The rescale is to a published employment count, never to a tax receipt. +""" + +from __future__ import annotations + +import hashlib +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path +from types import MappingProxyType +from typing import Any + +import numpy as np +import pandas as pd + +#: The extracted ONS table's file name in a public sector source directory. +UK_FIRM_PUBLIC_SECTOR_FILE = "ons_public_sector_employment.csv" +#: Its columns, in order. +UK_FIRM_PUBLIC_SECTOR_SOURCE_COLUMNS = ( + "sector", + "ons_legal_status", + "series_id", + "period", + "headcount_thousand", +) +#: ONS legal status of the rows each sector's headcount is spread over. +UK_FIRM_PUBLIC_SECTOR_STATUSES = MappingProxyType( + {"central_government": 5, "local_government": 6} +) +#: ONS series identifiers of the two Table 1 columns. +UK_FIRM_PUBLIC_SECTOR_SERIES = MappingProxyType( + {"central_government": "G6NQ", "local_government": "G6NT"} +) +#: The quarter the headcounts describe and the build vintage it stands for. +UK_FIRM_PUBLIC_SECTOR_PERIOD = "Mar 2025" +UK_FIRM_PUBLIC_SECTOR_TAX_YEAR = "2024-25" +#: The receipt's status and method for the rescale. +UK_FIRM_PUBLIC_SECTOR_STATUS = "assumed" +UK_FIRM_PUBLIC_SECTOR_METHOD = ( + "employment of ONS legal status 5 and 6 rows scaled so weighted employment " + "equals ONS Public sector employment, UK: March 2025 Table 1 headcount " + "(central government G6NQ, local government G6NT)" +) + +_REQUIRED_COLUMNS = ("firm_weight", "ons_legal_status") + + +@dataclass(frozen=True) +class UKFirmPublicSectorSource: + """ONS public sector headcount (people) per ONS legal status. + + ``headcount`` maps ONS legal status (5, 6) to the published headcount in + people; ``series`` maps the same statuses to the ONS series identifier. + ``sha256`` is the CSV's hash. + """ + + headcount: Mapping[int, float] + series: Mapping[int, str] + period: str + file: str + sha256: str + + +def read_uk_firm_public_sector_source(path: str | Path) -> UKFirmPublicSectorSource: + """Read the ONS public sector headcounts from a directory or the CSV. + + Raises ``ValueError`` unless the file has exactly + ``UK_FIRM_PUBLIC_SECTOR_SOURCE_COLUMNS``, one row per sector in + ``UK_FIRM_PUBLIC_SECTOR_STATUSES`` with that sector's legal status and + series identifier, the ``UK_FIRM_PUBLIC_SECTOR_PERIOD`` quarter and a + positive finite headcount. + """ + + path = Path(path) + if path.is_dir(): + path = path / UK_FIRM_PUBLIC_SECTOR_FILE + payload = path.read_bytes() + frame = pd.read_csv(path, dtype=str, keep_default_na=False) + if tuple(frame.columns) != UK_FIRM_PUBLIC_SECTOR_SOURCE_COLUMNS: + raise ValueError( + f"UK firm public sector source columns {list(frame.columns)} are not " + f"{list(UK_FIRM_PUBLIC_SECTOR_SOURCE_COLUMNS)}." + ) + sectors = frame["sector"].str.strip().tolist() + if sorted(sectors) != sorted(UK_FIRM_PUBLIC_SECTOR_STATUSES): + raise ValueError( + f"UK firm public sector source rows {sectors} are not " + f"{list(UK_FIRM_PUBLIC_SECTOR_STATUSES)}, once each." + ) + headcount: dict[int, float] = {} + series: dict[int, str] = {} + for record in frame.itertuples(index=False): + sector = record.sector.strip() + status = UK_FIRM_PUBLIC_SECTOR_STATUSES[sector] + if record.ons_legal_status.strip() != str(status): + raise ValueError( + f"UK firm public sector {sector} must have ons_legal_status " + f"{status}, not {record.ons_legal_status!r}." + ) + if record.series_id.strip() != UK_FIRM_PUBLIC_SECTOR_SERIES[sector]: + raise ValueError( + f"UK firm public sector {sector} must be series " + f"{UK_FIRM_PUBLIC_SECTOR_SERIES[sector]}, not {record.series_id!r}." + ) + if record.period.strip() != UK_FIRM_PUBLIC_SECTOR_PERIOD: + raise ValueError( + f"UK firm public sector {sector} period {record.period!r} is not " + f"{UK_FIRM_PUBLIC_SECTOR_PERIOD!r}." + ) + try: + thousand = float(record.headcount_thousand) + except ValueError: + raise ValueError( + f"UK firm public sector {sector} headcount " + f"{record.headcount_thousand!r} is not a number." + ) from None + if not np.isfinite(thousand) or thousand <= 0: + raise ValueError( + f"UK firm public sector {sector} headcount must be positive." + ) + headcount[status] = thousand * 1000.0 + series[status] = record.series_id.strip() + return UKFirmPublicSectorSource( + headcount=MappingProxyType(dict(sorted(headcount.items()))), + series=MappingProxyType(dict(sorted(series.items()))), + period=UK_FIRM_PUBLIC_SECTOR_PERIOD, + file=path.name, + sha256=hashlib.sha256(payload).hexdigest(), + ) + + +def _columns( + firms: pd.DataFrame, employment_column: str +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Headcount, weight and legal status of ``firms``, checked.""" + + missing = [ + column + for column in (employment_column, *_REQUIRED_COLUMNS) + if column not in firms.columns + ] + if missing: + raise ValueError(f"UK firm public sector rescale needs columns {missing}.") + employment = firms[employment_column].to_numpy(dtype=np.float64) + weight = firms["firm_weight"].to_numpy(dtype=np.float64) + status = firms["ons_legal_status"].to_numpy() + if ( + not np.all(np.isfinite(employment)) + or np.any(employment != np.round(employment)) + or np.any(employment < 0) + ): + raise ValueError( + f"UK firm {employment_column} must be non-negative whole numbers." + ) + if not np.all(np.isfinite(weight)) or np.any(weight < 0): + raise ValueError("UK firm firm_weight must be non-negative and finite.") + return employment, weight, status + + +def _scaled_headcounts( + employment: np.ndarray, weight: np.ndarray, target: float +) -> tuple[np.ndarray, float]: + """Whole headcounts of one status whose weighted sum is nearest ``target``. + + Each row is scaled by ``target / sum(weight * employment)`` and floored, + never below one. Rows are then rounded up in order of falling fractional + part (row order breaks ties) for as long as that brings the weighted sum + closer to ``target``, so the result is deterministic and the miss is at + most half of one row's weight unless the floor of one binds. + """ + + before = float(np.dot(weight, employment)) + if not before > 0: + raise ValueError("weighted employment is not positive") + factor = target / before + scaled = employment * factor + floor = np.floor(scaled) + base = np.maximum(floor, 1.0) + fraction = np.where(floor >= 1.0, scaled - floor, 0.0) + shortfall = target - float(np.dot(weight, base)) + order = np.argsort(-fraction, kind="stable") + order = order[(fraction[order] > 0) & (weight[order] > 0)] + if shortfall > 0 and order.size: + added = np.concatenate([[0.0], np.cumsum(weight[order])]) + take = int(np.argmin(np.abs(shortfall - added))) + base[order[:take]] += 1.0 + return base, factor + + +def _rescale( + firms: pd.DataFrame, source: UKFirmPublicSectorSource, employment_column: str +) -> tuple[np.ndarray, dict[str, Any]]: + employment, weight, status = _columns(firms, employment_column) + after = employment.copy() + sectors: dict[str, dict[str, Any]] = {} + for sector, code in UK_FIRM_PUBLIC_SECTOR_STATUSES.items(): + if code not in source.headcount: + raise ValueError(f"UK firm public sector source has no status {code}.") + rows = status == code + if not rows.any(): + raise ValueError( + f"UK firm public sector rescale found no rows with " + f"ons_legal_status {code} ({sector})." + ) + target = float(source.headcount[code]) + try: + after[rows], factor = _scaled_headcounts( + employment[rows], weight[rows], target + ) + except ValueError as error: + raise ValueError( + f"UK firm public sector rescale cannot scale ons_legal_status " + f"{code} ({sector}): {error}." + ) from None + sectors[sector] = { + "ons_legal_status": code, + "series_id": source.series[code], + "rows": int(rows.sum()), + "weight": float(weight[rows].sum()), + "target_weighted_employment": target, + "weighted_employment_before": float(np.dot(weight[rows], employment[rows])), + "weighted_employment_after": float(np.dot(weight[rows], after[rows])), + "scale_factor": factor, + "largest_headcount_before": int(employment[rows].max()), + "largest_headcount_after": int(after[rows].max()), + } + diagnostics = { + "status": UK_FIRM_PUBLIC_SECTOR_STATUS, + "method": UK_FIRM_PUBLIC_SECTOR_METHOD, + "period": source.period, + "source_file": source.file, + "source_sha256": source.sha256, + "employment_column": employment_column, + "rows": len(firms), + "total_weighted_employment_before": float(np.dot(weight, employment)), + "total_weighted_employment_after": float(np.dot(weight, after)), + "sectors": sectors, + } + return after, diagnostics + + +def scale_uk_firm_public_sector_employment( + firms: pd.DataFrame, + source: UKFirmPublicSectorSource, + *, + employment_column: str = "employment", +) -> pd.DataFrame: + """A copy of ``firms`` with public authority headcounts scaled to ONS. + + Rows with ``ons_legal_status`` 5 are scaled to ``source``'s central + government headcount and rows with status 6 to its local government + headcount, each by one factor, so that ``firm_weight`` times + ``employment_column`` sums to the published total. Headcounts stay whole + and at least one; the weighted total misses by at most half of one row's + weight (see ``_scaled_headcounts``). Rows, their order, the index, the + weights and every other column are unchanged, public corporations + (status 4) included. + + Raises ``ValueError`` when a column is missing, a headcount is not a + non-negative whole number, or a status has no rows or no weighted + employment to scale. + """ + + after, _ = _rescale(firms, source, employment_column) + result = firms.copy() + result[employment_column] = after.astype(firms[employment_column].dtype) + return result + + +def uk_firm_public_sector_diagnostics( + firms: pd.DataFrame, + source: UKFirmPublicSectorSource, + *, + employment_column: str = "employment", +) -> dict[str, Any]: + """What ``scale_uk_firm_public_sector_employment`` does to ``firms``. + + ``firms`` is the frame before the rescale. The dict holds the method, + the source file and hash, total weighted employment before and after, + and per sector the legal status, series, rows, weight, target, weighted + employment before and after, scale factor and largest headcount before + and after. + """ + + _, diagnostics = _rescale(firms, source, employment_column) + return diagnostics + + +__all__ = [ + "UK_FIRM_PUBLIC_SECTOR_FILE", + "UK_FIRM_PUBLIC_SECTOR_METHOD", + "UK_FIRM_PUBLIC_SECTOR_PERIOD", + "UK_FIRM_PUBLIC_SECTOR_SERIES", + "UK_FIRM_PUBLIC_SECTOR_SOURCE_COLUMNS", + "UK_FIRM_PUBLIC_SECTOR_STATUS", + "UK_FIRM_PUBLIC_SECTOR_STATUSES", + "UK_FIRM_PUBLIC_SECTOR_TAX_YEAR", + "UKFirmPublicSectorSource", + "read_uk_firm_public_sector_source", + "scale_uk_firm_public_sector_employment", + "uk_firm_public_sector_diagnostics", +] diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_rateable_value.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_rateable_value.py new file mode 100644 index 0000000000..08c0d1a00c --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_rateable_value.py @@ -0,0 +1,326 @@ +"""UK firm rateable value: an assumed mapping of VOA property bands to firms. + +policyengine-uk's ``firm_rateable_value`` is the total rateable value, in +pounds, of the non-domestic properties a firm occupies. It drives +``firm_business_rates``, which policyengine-uk models for England only +(``firm_in_england``; a firm elsewhere pays 0) and treats as one aggregate +property per firm (``firm_n_properties`` only decides small business rate +relief). The experimental UK firm generator draws no property, so this module +imputes the value. Its status is ``assumed``: nothing links a generated firm to +a property, and the result is not calibrated to business rates (NNDR) receipts +or to any other tax total. + +Source: the Valuation Office Agency's *Non-domestic rating: stock of +properties, March 2026*, Table SOP2.2: hereditaments and total rateable value +in England by rateable-value band, on the **2023 rating list** as at 31 March +2026. The extracted CSV and its provenance sit in +``tests/fixtures/uk/firm_rateable_value_2024/`` +(``tools/extract_uk_firm_rateable_value_tables.py`` re-creates it). + +The mapping, every step of it an assumption beyond the source: + +- hereditaments are properties, not firms. The module lines the two up by + rank: firms in England are ordered by headcount, largest first, and the + hereditaments by rateable value, largest first, and the firm at a given + weighted rank takes the hereditaments at the same rank. A firm standing for + ``firm_weight`` firms takes that many hereditaments and carries their mean + rateable value, so the weighted total over the firms that get a property + equals the table's rateable value for the hereditaments they cover; +- firms with the same headcount are ordered by a draw from a separate + fixed-seed generator (``UK_FIRM_RATEABLE_VALUE_SEED``), which depends on + row order and on nothing else in the build; +- once the hereditaments run out, the remaining (smallest) firms get 0: they + are taken to trade from a home or from someone else's premises; +- one firm, one hereditament: a multi-site firm's properties are spread over + several firms rather than summed on one, so the largest firms' values are + too low and small business rate relief is overstated; empty properties and + those of households, charities and public bodies outside the generator are + handed to firms; +- inside a band, rateable value follows ``lower + (upper - lower) * q ** k`` + over the within-band quantile ``q``, with ``k`` set so the band's mean is + the published one (total over count). The open top band, and any band whose + published mean does not lie strictly inside its bounds, is flat at its + mean; +- the all-sector band table is used. The table's sectors (retail, offices, + industry, other) classify properties, not SIC sections, and the module + does not map one to the other; +- a firm outside England gets 0. Wales is in the VOA release, but + policyengine-uk does not model Welsh rates; +- the stock is as at 31 March 2026 and is used unchanged for the 2024-25 + build: the 2023 rating list was in force throughout, and + ``voa_stock_by_year.csv`` in the fixture gives the all-property stock at + 31 March 2024 and 2025 for comparison. +""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +import pandas as pd + +#: The extracted VOA band table's file name in a source directory. +UK_FIRM_RATEABLE_VALUE_FILE = "voa_rv_band_sector.csv" +#: Its columns, in order. +UK_FIRM_RATEABLE_VALUE_SOURCE_COLUMNS = ( + "geography", + "rv_band", + "band_lower_gbp", + "band_upper_gbp", + "sector", + "hereditaments", + "total_rv_gbp_thousand", +) +#: The rows the imputation reads. +UK_FIRM_RATEABLE_VALUE_GEOGRAPHY = "england" +UK_FIRM_RATEABLE_VALUE_SECTOR = "all" +UK_FIRM_RATEABLE_VALUE_TOTAL_BAND = "Total" +UK_FIRM_RATEABLE_VALUE_RATING_LIST = "2023" +UK_FIRM_RATEABLE_VALUE_STATUS = "assumed" +UK_FIRM_RATEABLE_VALUE_METHOD = ( + "Firms in England ranked by headcount (ties by a fixed-seed draw) take " + "the VOA 2023-list hereditaments at the same weighted rank by rateable " + "value; firms past the last hereditament, and firms outside England, " + "get 0. Not calibrated to business rates receipts." +) +#: Seed of the tie-breaking generator, used for nothing else. +UK_FIRM_RATEABLE_VALUE_SEED = 20230401 + + +@dataclass(frozen=True) +class UKFirmRateableValueSource: + """England's hereditaments by rateable-value band, largest band first. + + ``lower_gbp`` and ``upper_gbp`` are the band bounds in pounds + (``upper_gbp`` is ``inf`` for the open top band), ``hereditaments`` the + counts and ``total_rv_gbp`` the bands' rateable value in pounds. + ``published_*`` are the table's own ``Total`` row. ``sha256`` is the + CSV's hash. + """ + + bands: tuple[str, ...] + lower_gbp: tuple[float, ...] + upper_gbp: tuple[float, ...] + hereditaments: tuple[float, ...] + total_rv_gbp: tuple[float, ...] + published_hereditaments: float + published_total_rv_gbp: float + file: str + sha256: str + + @property + def n_hereditaments(self) -> float: + return float(sum(self.hereditaments)) + + @property + def total_gbp(self) -> float: + return float(sum(self.total_rv_gbp)) + + +def read_uk_firm_rateable_value_source(path: str | Path) -> UKFirmRateableValueSource: + """Read England's all-sector band rows from a directory or the CSV. + + Raises ``ValueError`` unless the file has exactly + ``UK_FIRM_RATEABLE_VALUE_SOURCE_COLUMNS``, a ``Total`` row, and bands with + positive counts and values whose bounds ascend without overlap and whose + last band alone is open. + """ + + path = Path(path) + if path.is_dir(): + path = path / UK_FIRM_RATEABLE_VALUE_FILE + payload = path.read_bytes() + frame = pd.read_csv(path, dtype=str, keep_default_na=False) + if tuple(frame.columns) != UK_FIRM_RATEABLE_VALUE_SOURCE_COLUMNS: + raise ValueError( + f"UK firm rateable value source columns {list(frame.columns)} are " + f"not {list(UK_FIRM_RATEABLE_VALUE_SOURCE_COLUMNS)}." + ) + rows = frame[ + (frame["geography"] == UK_FIRM_RATEABLE_VALUE_GEOGRAPHY) + & (frame["sector"] == UK_FIRM_RATEABLE_VALUE_SECTOR) + ] + is_total = rows["rv_band"] == UK_FIRM_RATEABLE_VALUE_TOTAL_BAND + if int(is_total.sum()) != 1: + raise ValueError("UK firm rateable value source needs one England Total row.") + total = rows[is_total].iloc[0] + bands = rows[~is_total] + if bands.empty: + raise ValueError("UK firm rateable value source has no England bands.") + try: + lower = bands["band_lower_gbp"].astype(np.float64).to_numpy() + upper = bands["band_upper_gbp"].replace("", "inf").astype(np.float64).to_numpy() + counts = bands["hereditaments"].astype(np.float64).to_numpy() + values = bands["total_rv_gbp_thousand"].astype(np.float64).to_numpy() * 1e3 + published_count = float(total["hereditaments"]) + published_value = float(total["total_rv_gbp_thousand"]) * 1e3 + except ValueError: + raise ValueError("UK firm rateable value source has a non-number.") from None + if ( + np.any(lower < 0) + or np.any(upper <= lower) + or np.any(lower[1:] <= upper[:-1]) + or not np.all(np.isfinite(upper[:-1])) + or np.isfinite(upper[-1]) + ): + raise ValueError( + "UK firm rateable value bands must ascend without overlap and end " + "with one open band." + ) + if ( + not np.all(np.isfinite(counts)) + or not np.all(np.isfinite(values)) + or np.any(counts <= 0) + or np.any(values <= 0) + ): + raise ValueError("UK firm rateable value bands need positive numbers.") + order = slice(None, None, -1) + return UKFirmRateableValueSource( + bands=tuple(bands["rv_band"].tolist()[order]), + lower_gbp=tuple(lower[order].tolist()), + upper_gbp=tuple(upper[order].tolist()), + hereditaments=tuple(counts[order].tolist()), + total_rv_gbp=tuple(values[order].tolist()), + published_hereditaments=published_count, + published_total_rv_gbp=published_value, + file=path.name, + sha256=hashlib.sha256(payload).hexdigest(), + ) + + +def uk_firm_rateable_value_of_top( + source: UKFirmRateableValueSource, rank: np.ndarray +) -> np.ndarray: + """Rateable value (pounds) of England's ``rank`` most valuable hereditaments. + + ``rank`` is a count from the top, not necessarily whole; it is clipped to + between 0 and ``source.n_hereditaments``. Within a band the value follows + the module's assumed curve, which returns each band's published total at + the band's end. + """ + + counts = np.asarray(source.hereditaments, dtype=np.float64) + totals = np.asarray(source.total_rv_gbp, dtype=np.float64) + lower = np.asarray(source.lower_gbp, dtype=np.float64) + upper = np.asarray(source.upper_gbp, dtype=np.float64) + mean = totals / counts + curved = np.isfinite(upper) & (mean > lower) & (mean < upper) + width = np.where(curved, upper - lower, 0.0) + # Exponent plus one of the within-band curve: (upper - lower) / (mean - lower). + power = np.where(curved, width / np.where(curved, mean - lower, 1.0), 1.0) + edges = np.concatenate([[0.0], np.cumsum(counts)]) + before = np.concatenate([[0.0], np.cumsum(totals)]) + + rank = np.clip(np.asarray(rank, dtype=np.float64), 0.0, edges[-1]) + band = np.clip(np.searchsorted(edges, rank, side="right") - 1, 0, len(counts) - 1) + share = np.clip((rank - edges[band]) / counts[band], 0.0, 1.0) + flat = share * totals[band] + bent = counts[band] * ( + lower[band] * share + + width[band] * (1.0 - (1.0 - share) ** power[band]) / power[band] + ) + return before[band] + np.where(curved[band], bent, flat) + + +def _headcount(frame: pd.DataFrame) -> np.ndarray: + # ONS headcount first: with the labour link group firm_employees excludes + # working proprietors and ons_employment keeps the headcount. + for column in ("ons_employment", "firm_employees", "employment"): + if column in frame.columns: + values = frame[column].to_numpy(dtype=np.float64) + break + else: + raise ValueError("UK firm rateable value needs firm_employees or employment.") + if not np.all(np.isfinite(values)) or np.any(values < 0): + raise ValueError("UK firm employees must be non-negative numbers.") + return values + + +def _weight(frame: pd.DataFrame) -> np.ndarray: + if "firm_weight" not in frame.columns: + return np.ones(len(frame), dtype=np.float64) + weight = frame["firm_weight"].to_numpy(dtype=np.float64) + if not np.all(np.isfinite(weight)) or np.any(weight < 0): + raise ValueError("UK firm firm_weight must be non-negative numbers.") + return weight + + +def _in_england(frame: pd.DataFrame) -> np.ndarray: + if "firm_in_england" not in frame.columns: + raise ValueError("UK firm rateable value needs firm_in_england.") + return frame["firm_in_england"].to_numpy(dtype=bool) + + +def assign_uk_firm_rateable_value( + table_or_firms: pd.DataFrame, + source: UKFirmRateableValueSource, + *, + seed: int = UK_FIRM_RATEABLE_VALUE_SEED, +) -> np.ndarray: + """Assumed rateable value in pounds per row, in row order. + + ``table_or_firms`` needs ``firm_in_england`` and ``firm_employees`` (or + the generator's ``employment``); ``firm_weight`` is 1 where absent. See + the module docstring for the mapping. Rows outside England, rows with no + weight and rows ranked past the last hereditament get 0. + """ + + headcount = _headcount(table_or_firms) + weight = _weight(table_or_firms) + england = np.flatnonzero(_in_england(table_or_firms) & (weight > 0)) + out = np.zeros(len(table_or_firms), dtype=np.float64) + if england.size == 0: + return out + ties = np.random.default_rng(seed).random(england.size) + order = england[np.lexsort((ties, -headcount[england]))] + end = np.cumsum(weight[order]) + start = end - weight[order] + covered = uk_firm_rateable_value_of_top( + source, end + ) - uk_firm_rateable_value_of_top(source, start) + out[order] = np.maximum(covered, 0.0) / weight[order] + return out + + +def uk_firm_rateable_value_summary( + table_or_firms: pd.DataFrame, + source: UKFirmRateableValueSource, + *, + seed: int = UK_FIRM_RATEABLE_VALUE_SEED, +) -> dict[str, float]: + """Weighted totals of the assumed rateable value, for disclosure. + + ``weighted_firms_in_england`` and ``weighted_firms_with_property`` are + sums of ``firm_weight``; ``weighted_rateable_value_gbp`` is the weighted + total, and ``source_*`` are the band table's sums it can at most reach. + """ + + weight = _weight(table_or_firms) + value = assign_uk_firm_rateable_value(table_or_firms, source, seed=seed) + return { + "weighted_firms_in_england": float(weight[_in_england(table_or_firms)].sum()), + "weighted_firms_with_property": float(weight[value > 0].sum()), + "weighted_rateable_value_gbp": float((weight * value).sum()), + "source_hereditaments": source.n_hereditaments, + "source_rateable_value_gbp": source.total_gbp, + } + + +__all__ = [ + "UK_FIRM_RATEABLE_VALUE_FILE", + "UK_FIRM_RATEABLE_VALUE_GEOGRAPHY", + "UK_FIRM_RATEABLE_VALUE_METHOD", + "UK_FIRM_RATEABLE_VALUE_RATING_LIST", + "UK_FIRM_RATEABLE_VALUE_SECTOR", + "UK_FIRM_RATEABLE_VALUE_SEED", + "UK_FIRM_RATEABLE_VALUE_SOURCE_COLUMNS", + "UK_FIRM_RATEABLE_VALUE_STATUS", + "UK_FIRM_RATEABLE_VALUE_TOTAL_BAND", + "UKFirmRateableValueSource", + "assign_uk_firm_rateable_value", + "read_uk_firm_rateable_value_source", + "uk_firm_rateable_value_of_top", + "uk_firm_rateable_value_summary", +] diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_rd_tax_credits.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_rd_tax_credits.py new file mode 100644 index 0000000000..20cbb11a74 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_rd_tax_credits.py @@ -0,0 +1,553 @@ +"""UK firm R&D: an opt-in, assumed allocation of HMRC R&D tax credit claims. + +policyengine-uk's R&D relief reads, per firm and year: + +- ``firm_qualifying_rd_expenditure`` (£, no default): qualifying R&D + expenditure already deducted in computing trading profit. Only a + ``COMPANY`` (``firm_legal_form``) gets relief. Claimants are drawn from + ``ons_legal_status`` 1; public corporations (status 4), which also export + as ``COMPANY``, are never drawn, except that rows with only + ``firm_legal_form`` count every ``COMPANY``; +- ``firm_is_sme`` (bool, default false): SME for R&D relief, which the + variable documents as fewer than 500 staff and either turnover of no more + than 100 million euros or a balance sheet of no more than 86 million euros, + with linked and partner enterprises; +- ``firm_total_relevant_expenditure`` (£): the R&D intensity denominator. + From April 2024 (``merged_scheme_in_effect``) a company claims SME relief + (enhanced R&D intensive support) only if it is an SME, R&D intensive and + loss-making; every other company with expenditure gets the merged R&D + expenditure credit (20%). + +The experimental UK firm generator sets none of these. This module sets the +first two from HMRC's *Research and Development Tax Credits Statistics: +September 2026* main tables (financial year 2024-25, provisional and +uplifted), extracted by ``tools/extract_uk_firm_rd_tax_credits_tables.py`` to +``tests/fixtures/uk/firm_rd_tax_credits_2024_25/``. Its status is +``assumed``. The steps: + +1. Strata. Per SIC 2007 section, RD6's large-company claims are its RDEC by + large companies plus merged RDEC by large companies (a suppressed or N/A + cell counts as 0, so the large count is a lower bound); SME claims are the + section's total claims less that. +2. Claims are not companies: RD1 gives 40,325 claims but 37,545 companies + in 2024-25. Both strata targets are scaled by companies over claims, so a + drawn company stands for one claiming company. +3. Claimants. Among companies of the section with turnover, the large + stratum is taken top-down by headcount (ties in the order of a uniform + from the module's own ``SeedSequence`` stream, assigned in ``firm_id`` + order) until summed ``firm_weight`` is nearest its target; the SME stratum + is then drawn uniformly at random from the rest, in the same uniform's + order, until its weight is nearest its target. A stratum whose pool runs + out is capped and reported. +4. Expenditure. A section by size table is seeded with RD6 claims times the + national expenditure per claim by size (RD4 over RD1: large is RDEC plus + merged RDEC by large companies, SME the rest) and raked to RD6 section + expenditure and to RD4's large and SME totals (£30,245m and £20,725m), + the latter scaled to the sections' sum, since RD6's "Unknown or other" + row (95 claims, £135m) has no section and is left unallocated. Each + cell is shared over its drawn claimants in proportion to turnover, with + expenditure never above turnover; what the cap leaves, or a cell with no + claimant, is reported unallocated. RD6's cost columns (relief paid) are + not used. +5. ``firm_is_sme``: a large-stratum claimant is False and an SME-stratum + claimant True; every other row has the headcount limb only (fewer than 500 + employees). The euro turnover and balance sheet limbs and linked + enterprises are not applied: the generator has no balance sheet. + +``firm_total_relevant_expenditure`` stays unset, so no company is R&D +intensive and, under policyengine-uk's merged scheme, every claimant gets the +20% expenditure credit. Modelled relief is therefore not calibrated to HMRC's +cost of support. +""" + +from __future__ import annotations + +import hashlib +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path +from types import MappingProxyType +from typing import Any + +import numpy as np +import pandas as pd + +UK_FIRM_RD_SECTOR_FILE = "hmrc_rd_rd6_sector_2024_25.csv" +UK_FIRM_RD_CLAIMS_FILE = "hmrc_rd_rd1_claims.csv" +UK_FIRM_RD_EXPENDITURE_FILE = "hmrc_rd_rd4_expenditure.csv" +UK_FIRM_RD_FILES = ( + UK_FIRM_RD_SECTOR_FILE, + UK_FIRM_RD_CLAIMS_FILE, + UK_FIRM_RD_EXPENDITURE_FILE, +) +UK_FIRM_RD_YEAR = "2024-25" +UK_FIRM_RD_SECTIONS = tuple("ABCDEFGHIJKLMNOPQRS") +UK_FIRM_RD_UNKNOWN_SECTOR = "Unknown or other" +UK_FIRM_RD_STATUS = "assumed" +UK_FIRM_RD_METHOD = ( + "per SIC section, HMRC R&D Tax Credits Statistics September 2026 RD6 " + "2024-25 claims split into large (RDEC and merged RDEC by large companies) " + "and SME strata and scaled by RD1 companies over claims; large claimants " + "taken top-down by headcount and SME claimants drawn uniformly among the " + "rest; expenditure raked to RD6 section and RD4 size totals and shared by " + "turnover, capped at turnover; firm_is_sme from the stratum for claimants " + "and from headcount under 500 otherwise" +) +#: policyengine-uk's SME headcount limit for R&D relief (``firm_is_sme``). +UK_FIRM_RD_SME_EMPLOYEE_LIMIT = 500 +#: Columns the assignment reads (one of each tuple). +UK_FIRM_RD_INPUT_COLUMNS = ( + ("firm_id",), + ("firm_weight", "weights"), + ("ons_employment", "firm_employees", "employment"), + ("firm_turnover", "annual_turnover_k"), + ("firm_sic_section", "sic_code"), + ("ons_legal_status", "firm_legal_form"), +) +#: Second word of the draw's ``SeedSequence``: ASCII "RDTC". +UK_FIRM_RD_SEED_TAG = 0x52445443 +UK_FIRM_RD_RAKE_ITERATIONS = 200 + +_COMPANY_STATUS = 1 +_COMPANY_FORM = "COMPANY" +_SME_CLAIM_COLUMNS = ( + "sme_scheme_claims", + "sme_intensive_eris_claims", + "rdec_sme_claims", + "merged_rdec_sme_claims", +) +_LARGE_CLAIM_COLUMNS = ("rdec_large_claims", "merged_rdec_large_claims") +#: RD1 / RD4 2024-25 columns of large-company claims and expenditure. +_RD1_LARGE = ("rdec_large", "merged_rdec_large") +_RD1_SME = ("sme_total", "rdec_sme", "merged_rdec_sme") +_RD4_LARGE = ("rdec_large", "merged_rdec_large") +_RD4_SME = ("sme_scheme", "sme_intensive_eris", "rdec_sme", "merged_rdec_sme") + + +def _published(value: str) -> float | None: + """A published cell as a number; None when suppressed, N/A or blank.""" + + text = value.strip() + if not text or text == "N/A" or text.startswith("<"): + return None + try: + return float(text.replace(",", "")) + except ValueError: + raise ValueError(f"HMRC R&D cell {value!r} is not a number.") from None + + +@dataclass(frozen=True) +class UKFirmRDSection: + """RD6 2024-25 for one SIC section: claims and expenditure (£).""" + + claims: float + expenditure_gbp: float + #: RDEC plus merged RDEC claims by large companies, suppressed cells as 0. + large_claims: float + large_cells_suppressed: int + #: Unsuppressed SME claim cells summed, and how many were suppressed. + sme_claims_published: float + sme_cells_suppressed: int + + @property + def sme_claims(self) -> float: + return self.claims - self.large_claims + + +@dataclass(frozen=True) +class UKFirmRDSource: + sections: Mapping[str, UKFirmRDSection] + unknown_claims: float + unknown_expenditure_gbp: float + national_claims: float + national_companies: float + national_large_claims: float + national_sme_claims: float + #: RD4 2024-25 expenditure (£) by scheme column. + national_expenditure_gbp: Mapping[str, float] + sha256: Mapping[str, str] + + @property + def national_large_expenditure_gbp(self) -> float: + return float(sum(self.national_expenditure_gbp[c] for c in _RD4_LARGE)) + + @property + def national_sme_expenditure_gbp(self) -> float: + return float(sum(self.national_expenditure_gbp[c] for c in _RD4_SME)) + + @property + def companies_per_claim(self) -> float: + return self.national_companies / self.national_claims + + +def _read(directory: Path, name: str) -> tuple[pd.DataFrame, str]: + path = directory / name + payload = path.read_bytes() + frame = pd.read_csv(path, dtype=str, keep_default_na=False) + return frame, hashlib.sha256(payload).hexdigest() + + +def _year_row(frame: pd.DataFrame, name: str) -> pd.Series: + rows = frame[frame["financial_year"] == UK_FIRM_RD_YEAR] + if len(rows) != 1: + raise ValueError(f"{name} has {len(rows)} rows for {UK_FIRM_RD_YEAR}.") + return rows.iloc[0] + + +def _required(value: str, label: str) -> float: + number = _published(value) + if number is None or not np.isfinite(number) or number < 0: + raise ValueError(f"HMRC R&D {label} must be a published number, not {value!r}.") + return number + + +def read_uk_firm_rd_source(path: str | Path) -> UKFirmRDSource: + """Read the three extracted HMRC R&D CSVs from a fixture directory.""" + + directory = Path(path) + sector, sector_sha = _read(directory, UK_FIRM_RD_SECTOR_FILE) + claims, claims_sha = _read(directory, UK_FIRM_RD_CLAIMS_FILE) + spend, spend_sha = _read(directory, UK_FIRM_RD_EXPENDITURE_FILE) + labels = sector["sector"].tolist() + if [label[:1] for label in labels[:-1]] != list(UK_FIRM_RD_SECTIONS) or ( + labels[-1] != UK_FIRM_RD_UNKNOWN_SECTOR + ): + raise ValueError(f"HMRC R&D RD6 sector rows {labels} are not A-S + unknown.") + sections: dict[str, UKFirmRDSection] = {} + for record in sector.iloc[:-1].to_dict("records"): + letter = record["sector"][:1] + sme = [_published(record[c]) for c in _SME_CLAIM_COLUMNS] + large = [_published(record[c]) for c in _LARGE_CLAIM_COLUMNS] + total = _required(record["total_claims"], f"{letter} total claims") + large_claims = float(sum(v for v in large if v is not None)) + if large_claims > total: + raise ValueError(f"HMRC R&D {letter} large claims exceed total claims.") + sections[letter] = UKFirmRDSection( + claims=total, + expenditure_gbp=1e6 + * _required(record["total_expenditure_gbp_m"], f"{letter} expenditure"), + large_claims=large_claims, + large_cells_suppressed=sum(v is None for v in large), + sme_claims_published=float(sum(v for v in sme if v is not None)), + sme_cells_suppressed=sum(v is None for v in sme), + ) + unknown = sector.iloc[-1] + year_claims = _year_row(claims, UK_FIRM_RD_CLAIMS_FILE) + year_spend = _year_row(spend, UK_FIRM_RD_EXPENDITURE_FILE) + national_expenditure = { + column: 1e6 * _required(year_spend[column], f"RD4 {column}") + for column in spend.columns + if column not in ("financial_year", "status") + } + return UKFirmRDSource( + sections=MappingProxyType(sections), + unknown_claims=_required(unknown["total_claims"], "unknown claims"), + unknown_expenditure_gbp=1e6 + * _required(unknown["total_expenditure_gbp_m"], "unknown expenditure"), + national_claims=_required(year_claims["total_claims"], "RD1 total claims"), + national_companies=_required( + year_claims["total_companies"], "RD1 total companies" + ), + national_large_claims=float( + sum(_required(year_claims[c], f"RD1 {c}") for c in _RD1_LARGE) + ), + national_sme_claims=float( + sum(_required(year_claims[c], f"RD1 {c}") for c in _RD1_SME) + ), + national_expenditure_gbp=MappingProxyType(national_expenditure), + sha256=MappingProxyType( + { + UK_FIRM_RD_SECTOR_FILE: sector_sha, + UK_FIRM_RD_CLAIMS_FILE: claims_sha, + UK_FIRM_RD_EXPENDITURE_FILE: spend_sha, + } + ), + ) + + +def uk_firm_rd_expenditure_table(source: UKFirmRDSource) -> pd.DataFrame: + """Section by size expenditure (£), raked to RD6 sections and RD4 sizes. + + Columns ``large`` and ``sme``, one row per section A-S. The seed is RD6 + claims times RD4 over RD1 expenditure per claim by size; RD4's size totals + are scaled to the sections' expenditure sum before raking. + """ + + letters = list(source.sections) + per_claim = np.array( + [ + source.national_large_expenditure_gbp / source.national_large_claims, + source.national_sme_expenditure_gbp / source.national_sme_claims, + ] + ) + table = ( + np.array( + [ + [source.sections[s].large_claims, source.sections[s].sme_claims] + for s in letters + ] + ) + * per_claim + ) + rows = np.array([source.sections[s].expenditure_gbp for s in letters]) + columns = np.array( + [source.national_large_expenditure_gbp, source.national_sme_expenditure_gbp] + ) + columns = columns * rows.sum() / columns.sum() + for _ in range(UK_FIRM_RD_RAKE_ITERATIONS): + table *= (rows / np.where(table.sum(1) > 0, table.sum(1), 1.0))[:, None] + table *= columns / table.sum(0) + return pd.DataFrame(table, index=letters, columns=["large", "sme"]) + + +def _first_column(frame: pd.DataFrame, names: tuple[str, ...]) -> str: + for name in names: + if name in frame.columns: + return name + raise ValueError(f"UK firm R&D needs one of {list(names)}.") + + +def _inputs(frame: pd.DataFrame) -> dict[str, np.ndarray]: + ids = frame[_first_column(frame, ("firm_id",))].to_numpy() + if not pd.Index(ids).is_unique: + raise ValueError("UK firm R&D needs one row per firm_id.") + weight = frame[_first_column(frame, ("firm_weight", "weights"))].to_numpy( + np.float64 + ) + if not np.all(np.isfinite(weight)) or np.any(weight < 0): + raise ValueError("UK firm weights must be finite and non-negative.") + employees = frame[ + _first_column(frame, ("ons_employment", "firm_employees", "employment")) + ].to_numpy(np.float64) + if not np.all(np.isfinite(employees)) or np.any(employees < 0): + raise ValueError("UK firm employees must be finite and non-negative.") + turnover_column = _first_column(frame, ("firm_turnover", "annual_turnover_k")) + turnover = frame[turnover_column].to_numpy(np.float64) + if turnover_column == "annual_turnover_k": + turnover = turnover * 1000.0 + if not np.all(np.isfinite(turnover)) or np.any(turnover < 0): + raise ValueError("UK firm turnover must be finite and non-negative.") + if "firm_sic_section" in frame.columns: + section = frame["firm_sic_section"].astype(str).to_numpy(object) + elif "sic_code" in frame.columns: + from microcosm.build.uk_runtime.firm_table import ( # noqa: PLC0415 + uk_firm_sic_sections, + ) + + section = uk_firm_sic_sections(frame["sic_code"]).astype(object) + else: + raise ValueError("UK firm R&D needs firm_sic_section or sic_code.") + if "ons_legal_status" in frame.columns: + company = pd.to_numeric(frame["ons_legal_status"]).to_numpy() == ( + _COMPANY_STATUS + ) + elif "firm_legal_form" in frame.columns: + company = frame["firm_legal_form"].astype(str).to_numpy(object) == ( + _COMPANY_FORM + ) + else: + raise ValueError("UK firm R&D needs ons_legal_status or firm_legal_form.") + return { + "ids": ids, + "weight": weight, + "employees": employees, + "turnover": turnover, + "section": section, + "company": company, + } + + +def _ordered_uniforms(ids: np.ndarray, seed: int) -> np.ndarray: + rng = np.random.default_rng( + np.random.SeedSequence([int(seed), UK_FIRM_RD_SEED_TAG]) + ) + uniforms = np.empty(len(ids), dtype=np.float64) + uniforms[np.argsort(ids, kind="stable")] = rng.random(len(ids)) + return uniforms + + +def _take_nearest(order: np.ndarray, weight: np.ndarray, target: float) -> np.ndarray: + """The leading rows of ``order`` whose summed weight is nearest ``target``.""" + + cumulative = np.concatenate([[0.0], np.cumsum(weight[order])]) + return order[: int(np.argmin(np.abs(cumulative - target)))] + + +def _share( + rows: np.ndarray, weight: np.ndarray, turnover: np.ndarray, target: float +) -> tuple[np.ndarray, float]: + """Expenditure of ``rows`` by turnover, at most turnover, and the remainder. + + Proportional shares with a cap at turnover reduce to one factor + ``min(target / weighted turnover, 1)``: no row is capped unless all are. + """ + + capacity = float(np.dot(weight[rows], turnover[rows])) + if capacity <= 0: + return np.zeros(rows.size), target + factor = min(target / capacity, 1.0) + return turnover[rows] * factor, max(target - capacity, 0.0) + + +@dataclass(frozen=True) +class UKFirmRDAssignment: + qualifying_rd_expenditure: np.ndarray + is_sme: np.ndarray + claimant: np.ndarray + diagnostics: Mapping[str, Any] + + +def draw_uk_firm_rd_tax_credits( + firms: pd.DataFrame, source: UKFirmRDSource, *, seed: int +) -> UKFirmRDAssignment: + """Draw claimants, their size stratum and expenditure (module docstring).""" + + data = _inputs(firms) + weight, employees, turnover = data["weight"], data["employees"], data["turnover"] + section, company = data["section"], data["company"] + uniforms = _ordered_uniforms(data["ids"], seed) + is_sme = employees < UK_FIRM_RD_SME_EMPLOYEE_LIMIT + claimant = np.zeros(len(firms), dtype=bool) + expenditure = np.zeros(len(firms), dtype=np.float64) + table = uk_firm_rd_expenditure_table(source) + ratio = source.companies_per_claim + rows: list[dict[str, Any]] = [] + unallocated = 0.0 + capped_rows = 0 + for letter, spec in source.sections.items(): + pool = np.flatnonzero( + company & (section == letter) & (weight > 0) & (turnover > 0) + ) + large_target = spec.large_claims * ratio + sme_target = spec.sme_claims * ratio + by_size = pool[np.lexsort((uniforms[pool], -employees[pool]))] + large = _take_nearest(by_size, weight, large_target) + rest = np.setdiff1d(pool, large, assume_unique=True) + rest = rest[np.argsort(uniforms[rest], kind="stable")] + sme = _take_nearest(rest, weight, sme_target) + claimant[large] = True + claimant[sme] = True + is_sme[large] = False + is_sme[sme] = True + row: dict[str, Any] = { + "section": letter, + "hmrc_claims": spec.claims, + "large_cells_suppressed": spec.large_cells_suppressed, + "pool_weight": float(weight[pool].sum()), + "pool_rows": int(pool.size), + } + for stratum, chosen, target, available in ( + ("large", large, large_target, float(weight[pool].sum())), + ("sme", sme, sme_target, float(weight[rest].sum())), + ): + amounts, left = _share(chosen, weight, turnover, table.at[letter, stratum]) + expenditure[chosen] = amounts + unallocated += left + at_cap = int(np.sum(amounts >= turnover[chosen])) if left > 0 else 0 + capped_rows += at_cap + drawn = float(weight[chosen].sum()) + row.update( + { + f"{stratum}_target_companies": target, + f"{stratum}_weighted_claimants": drawn, + f"{stratum}_claimant_rows": int(chosen.size), + f"{stratum}_draw_capped": available < target, + f"{stratum}_target_expenditure_gbp": float( + table.at[letter, stratum] + ), + f"{stratum}_model_expenditure_gbp": float( + np.dot(weight[chosen], amounts) + ), + f"{stratum}_unallocated_gbp": left, + f"{stratum}_rows_at_turnover_cap": at_cap, + } + ) + row["hmrc_expenditure_gbp"] = spec.expenditure_gbp + row["model_expenditure_gbp"] = ( + row["large_model_expenditure_gbp"] + row["sme_model_expenditure_gbp"] + ) + rows.append(row) + large_claimant = claimant & ~is_sme + sme_claimant = claimant & is_sme + diagnostics = { + "status": UK_FIRM_RD_STATUS, + "method": UK_FIRM_RD_METHOD, + "year": UK_FIRM_RD_YEAR, + "seed": int(seed), + "seed_tag": UK_FIRM_RD_SEED_TAG, + "companies_per_claim": ratio, + "hmrc_national_claims": source.national_claims, + "hmrc_national_companies": source.national_companies, + "hmrc_unallocated_claims": source.unknown_claims, + "hmrc_unallocated_expenditure_gbp": source.unknown_expenditure_gbp, + "hmrc_large_expenditure_gbp": source.national_large_expenditure_gbp, + "hmrc_sme_expenditure_gbp": source.national_sme_expenditure_gbp, + "hmrc_section_expenditure_gbp": float( + sum(s.expenditure_gbp for s in source.sections.values()) + ), + "weighted_claimants": float(weight[claimant].sum()), + "weighted_large_claimants": float(weight[large_claimant].sum()), + "weighted_sme_claimants": float(weight[sme_claimant].sum()), + "model_expenditure_gbp": float(np.dot(weight, expenditure)), + "model_large_expenditure_gbp": float( + np.dot(weight[large_claimant], expenditure[large_claimant]) + ), + "model_sme_expenditure_gbp": float( + np.dot(weight[sme_claimant], expenditure[sme_claimant]) + ), + "unallocated_expenditure_gbp": unallocated, + "rows_at_turnover_cap": capped_rows, + "draw_capped_strata": [ + f"{row['section']}:{stratum}" + for row in rows + for stratum in ("large", "sme") + if row[f"{stratum}_draw_capped"] + ], + "sections": rows, + "sha256": dict(source.sha256), + } + return UKFirmRDAssignment( + qualifying_rd_expenditure=expenditure, + is_sme=is_sme, + claimant=claimant, + diagnostics=MappingProxyType(diagnostics), + ) + + +def assign_uk_firm_rd_tax_credits( + firms: pd.DataFrame, source: UKFirmRDSource, *, seed: int +) -> pd.DataFrame: + """A copy of ``firms`` with ``firm_qualifying_rd_expenditure`` (£) and + ``firm_is_sme`` set; rows, order, index and other columns unchanged. + + ``firms`` needs one column of each tuple in ``UK_FIRM_RD_INPUT_COLUMNS``. + """ + + draw = draw_uk_firm_rd_tax_credits(firms, source, seed=seed) + result = firms.copy() + result["firm_qualifying_rd_expenditure"] = draw.qualifying_rd_expenditure + result["firm_is_sme"] = draw.is_sme + return result + + +__all__ = [ + "UK_FIRM_RD_CLAIMS_FILE", + "UK_FIRM_RD_EXPENDITURE_FILE", + "UK_FIRM_RD_FILES", + "UK_FIRM_RD_INPUT_COLUMNS", + "UK_FIRM_RD_METHOD", + "UK_FIRM_RD_SECTIONS", + "UK_FIRM_RD_SECTOR_FILE", + "UK_FIRM_RD_SEED_TAG", + "UK_FIRM_RD_SME_EMPLOYEE_LIMIT", + "UK_FIRM_RD_STATUS", + "UK_FIRM_RD_UNKNOWN_SECTOR", + "UK_FIRM_RD_YEAR", + "UKFirmRDAssignment", + "UKFirmRDSection", + "UKFirmRDSource", + "assign_uk_firm_rd_tax_credits", + "draw_uk_firm_rd_tax_credits", + "read_uk_firm_rd_source", + "uk_firm_rd_expenditure_table", +] 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..fa4cb4c349 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_table.py @@ -0,0 +1,1411 @@ +"""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 groups 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``. +- ``paybill``: ``firm_paybill`` (pounds, from + ``firm_paybill.assign_uk_firm_paybill``), carried unchanged. It extends + ``attributes``; with it the layout is ``UK_FIRM_PAYBILL_TABLE_COLUMNS``. +- ``employment_allowance``: the assumed ``firm_claims_employment_allowance`` + and ``firm_is_single_director_company`` flags (from + ``firm_employment_allowance.assign_uk_firm_employment_allowance``), checked + against ``ons_legal_status`` and ``firm_employees``. It extends + ``attributes``. +- ``pay_distribution``: the assumed + ``firm_employees_below_secondary_threshold`` and + ``firm_paybill_below_secondary_threshold`` (from + ``firm_pay_distribution.assign_uk_firm_pay_below_secondary_threshold``). + It extends ``attributes`` and ``paybill``. +- ``profit``: the assumed ``firm_taxable_trading_profit`` (pounds, from + ``firm_profit.assign_uk_firm_taxable_profit``), zero for firms other than ONS status 1 companies. + It extends ``attributes``. +- ``rateable_value``: the assumed ``firm_rateable_value`` (pounds, from + ``firm_rateable_value.assign_uk_firm_rateable_value``), zero outside + England. It extends ``attributes``. +- ``sic_division``: Microcosm-only ``firm_sic_division``, the generator's + SIC 2007 division, a linkage key the labour and consumption groups both + extend. It extends ``attributes``. +- ``labour_link``: switched on by ``employees`` (ONS employment less the + assumed working proprietors, ``firm_headcount.uk_firm_employees``), which + then fills ``firm_employees``. Its Microcosm-only columns are the linkage + keys for a labour match with household data: ``ons_employment`` (the ONS + headcount the employees came from), ``firm_employee_size_band`` (DBT + Business Population Estimates bands on employees), ``firm_mean_pay`` + (``firm_paybill`` over ``firm_employees``, today the section mean) and + ``firm_is_public_sector`` (ONS statuses 5 and 6, + ``UK_FIRM_PUBLIC_SECTOR_ONS_LEGAL_STATUSES``; an assumption: status 4, + public corporations, which ONS counts in the public sector and the export + marks ``firm_is_public_body``, is left out, and status 7, non-profit + bodies, is outside it). It extends ``attributes``, ``paybill`` and + ``sic_division``. +- ``employment_allowance_takeup``: ``firm_employment_allowance_rule_claims`` + keeps the rule flag, and ``firm_claims_employment_allowance`` becomes a + draw within it at HMRC's take-up by employee size band + (``firm_employment_allowance_takeup.py``). It extends ``attributes``, + ``paybill``, ``employment_allowance``, ``sic_division`` and + ``labour_link``. +- ``rd_tax_credits``: the assumed ``firm_qualifying_rd_expenditure`` + (pounds, companies only, never above turnover) and ``firm_is_sme`` (from + ``firm_rd_tax_credits.draw_uk_firm_rd_tax_credits``). It extends + ``attributes``. +- ``consumption``: Microcosm-only ``firm_household_sales``, + ``firm_intermediate_sales`` and ``firm_other_final_sales`` (pounds), + turnover split by the firm's SIC division's shares of total demand in the + ONS Supply and Use Tables 2024 (``firm_consumption.py``), the linkage keys + for a consumption match with household data. They sum to + ``firm_turnover``. It extends ``attributes`` and ``sic_division``. +- ``vat_composition``: Microcosm-only ``firm_sut_*`` columns, the firm's + SIC section's standard-, reduced-, zero-rated and exempt shares of + turnover, export share, input VAT rate and input ratio from the Supply and + Use Tables 2024 read through the VAT Act 1994 schedules + (``firm_vat_composition.py``). Columns only: no policyengine-uk input + changes, so VAT is still scored on all-standard-rated supplies. It + extends ``attributes``. + +``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; without a paybill source +``firm_paybill`` is unset too, 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.firm_consumption import UK_FIRM_CONSUMPTION_COLUMNS +from microcosm.build.uk_runtime.firm_employment_allowance import ( + UK_FIRM_EMPLOYMENT_ALLOWANCE_COLUMNS, + uk_firm_employment_allowance_flags, +) +from microcosm.build.uk_runtime.firm_headcount import ( + uk_firm_employee_size_bands, + uk_firm_employees, +) +from microcosm.build.uk_runtime.firm_vat_composition import ( + UK_FIRM_VAT_COMPOSITION_SHARE_COLUMNS, +) +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", +) + +#: policyengine-uk firm inputs the paybill group adds. +UK_FIRM_PAYBILL_POLICYENGINE_UK_COLUMNS = ("firm_paybill",) + +#: 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", + # ONS employment, which counts working proprietors, by default. With + # the labour link group (firm_headcount.py) it is assumed: employment + # less assumed working proprietors (1 per sole proprietor, up to 2 + # per partnership). + "firm_employees": "assumed", + "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", + # Headcount x ONS ASHE 2025 (tax year 2024-25) all-employees mean + # annual gross pay of the firm's SIC section (firm_paybill.py): every + # firm pays its section's mean, and ONS employment, which counts + # working proprietors, stands in for employees. Only when the build + # is given a paybill source. + "firm_paybill": "assumed", + # Assumed (firm_profit.py): HMRC Corporation Tax statistics + # liability bands (2024-25) inverted through the rate schedule and + # allotted to companies by turnover rank. In-sample for CT. Only when + # the build is given a profit source. + "firm_taxable_trading_profit": "assumed", + # Assumed (firm_rateable_value.py): VOA 2023-list hereditaments in + # England allotted to firms by headcount rank. Only when the build is + # given a rateable value source. + "firm_rateable_value": "assumed", + # 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", + # Assumed from ONS legal status and employment + # (firm_employment_allowance.py): a company with employment 1 is a + # single-director company. Only when the build sets the Employment + # Allowance flags. + "firm_is_single_director_company": "assumed", + "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", + # Assumed (firm_employment_allowance.py): sole proprietors with + # employment of at most 1 and partnerships with employment of at + # most 2 are their proprietors alone and do not claim. Only when the build sets the + # Employment Allowance flags. + "firm_claims_employment_allowance": "assumed", + "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", + # Assumed (firm_pay_distribution.py): the share of the section's + # ASHE 2025 jobs at or below the secondary threshold, from a linear + # percentile curve. Only when the build is given a pay distribution + # source. + "firm_employees_below_secondary_threshold": "assumed", + "firm_paybill_above_auto_enrolment_upper_limit": "not_set", + "firm_paybill_below_auto_enrolment_earnings_trigger": "not_set", + "firm_paybill_below_secondary_threshold": "assumed", + # National Minimum Wage floor (policyengine-uk ca037fad2). + "firm_low_paid_hours": "not_set", + "firm_low_paid_paybill": "not_set", + # R&D. + # Assumed (firm_rd_tax_credits.py): HMRC R&D tax credit statistics + # 2024-25 claims by section and size stratum, expenditure raked to + # section and size totals and capped at turnover; firm_is_sme from + # the stratum, else ONS employment below 500. Only when the build is + # given an R&D source. + "firm_is_sme": "assumed", + "firm_qualifying_rd_expenditure": "assumed", + # 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: + # ``employees`` (labour link group) excludes working proprietors; without + # it ONS employment stands in for employees. + column = "employees" if "employees" in frame.columns else "employment" + values = frame[column].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, + } + + +def _paybill_group_columns(ordered: pd.DataFrame) -> dict[str, np.ndarray]: + return {"firm_paybill": ordered["firm_paybill"].to_numpy(np.float64)} + + +def _employment_allowance_group_columns(ordered: pd.DataFrame) -> dict[str, np.ndarray]: + return { + column: ordered[column].to_numpy(bool) + for column in UK_FIRM_EMPLOYMENT_ALLOWANCE_COLUMNS + } + + +def _validate_employment_allowance_columns(df: pd.DataFrame) -> None: + for column in UK_FIRM_EMPLOYMENT_ALLOWANCE_COLUMNS: + if not pd.api.types.is_bool_dtype(df[column]): + raise ValueError(f"UK firm {column} must be boolean.") + # The flags are stated on ONS employment. With the labour link group + # firm_employees excludes working proprietors and ons_employment keeps + # the ONS headcount the flags read. + headcount = "ons_employment" if "ons_employment" in df else "firm_employees" + expected = uk_firm_employment_allowance_flags( + df["ons_legal_status"].to_numpy(np.int64), + df[headcount].to_numpy(np.int64), + ) + for column, values in expected.items(): + actual = df[column].to_numpy(bool) + if ( + column == "firm_claims_employment_allowance" + and UK_FIRM_EA_RULE_CLAIMS_COLUMN in df + ): + # With the take-up group the claim is drawn within the rule flag, + # which the group keeps. + actual = df[UK_FIRM_EA_RULE_CLAIMS_COLUMN].to_numpy(bool) + if not np.array_equal(actual, values): + raise ValueError( + f"UK firm {column} does not follow ons_legal_status and firm_employees." + ) + + +#: The take-up group's Microcosm-only column: the rule flag before the draw. +UK_FIRM_EA_RULE_CLAIMS_COLUMN = "firm_employment_allowance_rule_claims" + + +def _employment_allowance_takeup_group_columns( + ordered: pd.DataFrame, +) -> dict[str, np.ndarray]: + return { + UK_FIRM_EA_RULE_CLAIMS_COLUMN: ordered[UK_FIRM_EA_RULE_CLAIMS_COLUMN].to_numpy( + bool + ) + } + + +def _validate_employment_allowance_takeup_columns(df: pd.DataFrame) -> None: + rule = df[UK_FIRM_EA_RULE_CLAIMS_COLUMN] + if not pd.api.types.is_bool_dtype(rule): + raise ValueError(f"UK firm {UK_FIRM_EA_RULE_CLAIMS_COLUMN} must be boolean.") + if np.any(df["firm_claims_employment_allowance"].to_numpy(bool) & ~rule.to_numpy()): + raise ValueError( + "UK firm firm_claims_employment_allowance must be drawn within " + f"{UK_FIRM_EA_RULE_CLAIMS_COLUMN}." + ) + + +def _single_column(column: str) -> Callable[[pd.DataFrame], dict[str, np.ndarray]]: + def columns(ordered: pd.DataFrame) -> dict[str, np.ndarray]: + return {column: ordered[column].to_numpy(np.float64)} + + return columns + + +def _non_negative(df: pd.DataFrame, column: str) -> np.ndarray: + 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.") + return values + + +#: policyengine-uk inputs the pay distribution group adds. +UK_FIRM_PAY_DISTRIBUTION_COLUMNS = ( + "firm_employees_below_secondary_threshold", + "firm_paybill_below_secondary_threshold", +) + + +def _pay_distribution_group_columns(ordered: pd.DataFrame) -> dict[str, np.ndarray]: + return { + "firm_employees_below_secondary_threshold": ordered[ + "firm_employees_below_secondary_threshold" + ].to_numpy(np.int64), + "firm_paybill_below_secondary_threshold": ordered[ + "firm_paybill_below_secondary_threshold" + ].to_numpy(np.float64), + } + + +def _validate_pay_distribution_columns(df: pd.DataFrame) -> None: + count = df["firm_employees_below_secondary_threshold"].to_numpy() + if not np.issubdtype(count.dtype, np.integer) or np.any(count < 0): + raise ValueError( + "UK firm firm_employees_below_secondary_threshold must be " + "non-negative integers." + ) + if np.any(count > df["firm_employees"].to_numpy(np.int64)): + raise ValueError( + "UK firm firm_employees_below_secondary_threshold must not exceed " + "firm_employees." + ) + pay = _non_negative(df, "firm_paybill_below_secondary_threshold") + if np.any(pay > df["firm_paybill"].to_numpy(np.float64)): + raise ValueError( + "UK firm firm_paybill_below_secondary_threshold must not exceed " + "firm_paybill." + ) + if np.any(pay[count == 0]): + raise ValueError( + "UK firm firm_paybill_below_secondary_threshold must be zero " + "without employees below the threshold." + ) + + +def _validate_profit_columns(df: pd.DataFrame) -> None: + profit = _non_negative(df, "firm_taxable_trading_profit") + not_company = df["ons_legal_status"].to_numpy(np.int64) != 1 + if np.any(profit[not_company]): + raise ValueError( + "UK firm firm_taxable_trading_profit must be zero for firms that " + "are not ONS status 1 companies." + ) + + +def _validate_rateable_value_columns(df: pd.DataFrame) -> None: + value = _non_negative(df, "firm_rateable_value") + if np.any(value[~df["firm_in_england"].to_numpy(bool)]): + raise ValueError("UK firm firm_rateable_value must be zero outside England.") + + +#: ONS legal statuses the labour link marks ``firm_is_public_sector``: +#: central government (5) and local authorities (6). Public corporations (4), +#: public bodies for ``firm_is_public_body``, are left out. +UK_FIRM_PUBLIC_SECTOR_ONS_LEGAL_STATUSES: frozenset[int] = frozenset({5, 6}) + +#: Microcosm-only columns of the labour link group, in order. +UK_FIRM_LABOUR_LINK_COLUMNS = ( + "ons_employment", + "firm_employee_size_band", + "firm_mean_pay", + "firm_is_public_sector", +) + + +def _labour_link_group_columns(ordered: pd.DataFrame) -> dict[str, np.ndarray]: + employees = ordered["employees"].to_numpy(np.int64) + paybill = ordered["firm_paybill"].to_numpy(np.float64) + return { + "ons_employment": ordered["employment"].to_numpy(np.int64), + "firm_employee_size_band": uk_firm_employee_size_bands(employees), + "firm_mean_pay": _mean_pay(paybill, employees), + "firm_is_public_sector": np.isin( + ordered["ons_legal_status"].to_numpy(np.int64), + list(UK_FIRM_PUBLIC_SECTOR_ONS_LEGAL_STATUSES), + ), + } + + +def _mean_pay(paybill: np.ndarray, employees: np.ndarray) -> np.ndarray: + out = np.zeros(len(paybill), dtype=np.float64) + has = employees > 0 + out[has] = paybill[has] / employees[has] + return out + + +def _sic_division_group_columns(ordered: pd.DataFrame) -> dict[str, np.ndarray]: + return {"firm_sic_division": ordered["firm_sic_division"].to_numpy(np.int64)} + + +def _validate_sic_division_columns(df: pd.DataFrame) -> None: + division = df["firm_sic_division"].to_numpy() + if not np.issubdtype(division.dtype, np.integer): + raise ValueError("UK firm firm_sic_division must be integers.") + if not np.array_equal( + uk_firm_sic_sections(division).astype(str), + df["firm_sic_section"].astype(str).to_numpy(), + ): + raise ValueError("UK firm firm_sic_division must lie in firm_sic_section.") + + +def _validate_labour_link_columns(df: pd.DataFrame) -> None: + ons_employment = df["ons_employment"].to_numpy() + if not np.issubdtype(ons_employment.dtype, np.integer) or np.any( + ons_employment < 0 + ): + raise ValueError("UK firm ons_employment must be non-negative integers.") + employees = df["firm_employees"].to_numpy(np.int64) + expected = uk_firm_employees( + df["ons_legal_status"].to_numpy(np.int64), ons_employment.astype(np.int64) + ) + if not np.array_equal(employees, expected): + raise ValueError( + "UK firm firm_employees must be ons_employment less the assumed " + "working proprietors." + ) + if not np.array_equal( + df["firm_employee_size_band"].astype(str).to_numpy(), + uk_firm_employee_size_bands(employees), + ): + raise ValueError( + "UK firm firm_employee_size_band does not follow firm_employees." + ) + if not np.allclose( + df["firm_mean_pay"].to_numpy(np.float64), + _mean_pay(df["firm_paybill"].to_numpy(np.float64), employees), + rtol=1e-9, + atol=1e-6, + ): + raise ValueError( + "UK firm firm_mean_pay must be firm_paybill over firm_employees." + ) + if not np.array_equal( + df["firm_is_public_sector"].to_numpy(bool), + np.isin( + df["ons_legal_status"].to_numpy(np.int64), + list(UK_FIRM_PUBLIC_SECTOR_ONS_LEGAL_STATUSES), + ), + ): + raise ValueError("UK firm firm_is_public_sector must follow ons_legal_status.") + + +def _consumption_group_columns(ordered: pd.DataFrame) -> dict[str, np.ndarray]: + return { + column: ordered[column].to_numpy(np.float64) + for column in UK_FIRM_CONSUMPTION_COLUMNS + } + + +UK_FIRM_VAT_COMPOSITION_COLUMNS = tuple(UK_FIRM_VAT_COMPOSITION_SHARE_COLUMNS.values()) +_UK_FIRM_VAT_SUPPLY_SHARE_COLUMNS = tuple( + UK_FIRM_VAT_COMPOSITION_SHARE_COLUMNS[k] + for k in ("standard", "reduced", "zero", "exempt") +) + + +def _vat_composition_group_columns(ordered: pd.DataFrame) -> dict[str, np.ndarray]: + return { + column: ordered[column].to_numpy(np.float64) + for column in UK_FIRM_VAT_COMPOSITION_COLUMNS + } + + +def _validate_vat_composition_columns(df: pd.DataFrame) -> None: + for column in UK_FIRM_VAT_COMPOSITION_COLUMNS: + values = df[column].to_numpy(np.float64) + if not np.all(np.isfinite(values)) or np.any(values < 0) or np.any(values > 1): + raise ValueError(f"UK firm {column} must be a share in [0, 1].") + total = sum(df[c].to_numpy(np.float64) for c in _UK_FIRM_VAT_SUPPLY_SHARE_COLUMNS) + if not np.allclose(total, 1.0, rtol=0, atol=1e-9): + raise ValueError("UK firm VAT composition supply shares must sum to 1.") + sections = df["firm_sic_section"].astype(str) + for column in UK_FIRM_VAT_COMPOSITION_COLUMNS: + if (df.groupby(sections)[column].nunique() > 1).any(): + raise ValueError(f"UK firm {column} must be uniform within a SIC section.") + + +def _validate_consumption_columns(df: pd.DataFrame) -> None: + turnover = df["firm_turnover"].to_numpy(np.float64) + parts = [df[column].to_numpy(np.float64) for column in UK_FIRM_CONSUMPTION_COLUMNS] + tolerance = np.abs(turnover) * 1e-9 + 1e-6 + for column, values in zip(UK_FIRM_CONSUMPTION_COLUMNS, parts, strict=True): + if not np.all(np.isfinite(values)): + raise ValueError(f"UK firm {column} must be finite.") + if np.any(values * np.sign(turnover) < -tolerance): + raise ValueError(f"UK firm {column} must have firm_turnover's sign.") + if np.any(np.abs(values) > np.abs(turnover) * (1 + 1e-9) + 1e-6): + raise ValueError(f"UK firm {column} must not exceed firm_turnover.") + if not np.allclose(sum(parts), turnover, rtol=1e-9, atol=1e-6): + raise ValueError( + "UK firm household, intermediate and other final sales must sum " + "to firm_turnover." + ) + + +def _rd_group_columns(ordered: pd.DataFrame) -> dict[str, np.ndarray]: + return { + "firm_qualifying_rd_expenditure": ordered[ + "firm_qualifying_rd_expenditure" + ].to_numpy(np.float64), + "firm_is_sme": ordered["firm_is_sme"].to_numpy(bool), + } + + +def _validate_rd_columns(df: pd.DataFrame) -> None: + spend = _non_negative(df, "firm_qualifying_rd_expenditure") + if np.any(spend[df["ons_legal_status"].to_numpy(np.int64) != 1]): + raise ValueError( + "UK firm firm_qualifying_rd_expenditure must be zero for firms that " + "are not ONS status 1 companies." + ) + if np.any(spend > np.maximum(df["firm_turnover"].to_numpy(np.float64), 0.0)): + raise ValueError( + "UK firm firm_qualifying_rd_expenditure must not exceed firm_turnover." + ) + if not pd.api.types.is_bool_dtype(df["firm_is_sme"]): + raise ValueError("UK firm firm_is_sme must be boolean.") + + +def _validate_paybill_columns(df: pd.DataFrame) -> None: + for column in UK_FIRM_PAYBILL_POLICYENGINE_UK_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.") + no_employees = df["firm_employees"].to_numpy() == 0 + if np.any(df["firm_paybill"].to_numpy(np.float64)[no_employees]): + raise ValueError("UK firm firm_paybill must be zero without employees.") + + +@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, + ), + UKFirmExportGroup( + name="paybill", + source_columns=("firm_paybill",), + policyengine_uk_columns=UK_FIRM_PAYBILL_POLICYENGINE_UK_COLUMNS, + microcosm_columns=(), + requires=("attributes",), + columns=_paybill_group_columns, + validate=_validate_paybill_columns, + ), + UKFirmExportGroup( + name="employment_allowance", + source_columns=UK_FIRM_EMPLOYMENT_ALLOWANCE_COLUMNS, + policyengine_uk_columns=UK_FIRM_EMPLOYMENT_ALLOWANCE_COLUMNS, + microcosm_columns=(), + requires=("attributes",), + columns=_employment_allowance_group_columns, + validate=_validate_employment_allowance_columns, + ), + UKFirmExportGroup( + name="pay_distribution", + source_columns=UK_FIRM_PAY_DISTRIBUTION_COLUMNS, + policyengine_uk_columns=UK_FIRM_PAY_DISTRIBUTION_COLUMNS, + microcosm_columns=(), + requires=("attributes", "paybill"), + columns=_pay_distribution_group_columns, + validate=_validate_pay_distribution_columns, + ), + UKFirmExportGroup( + name="profit", + source_columns=("firm_taxable_trading_profit",), + policyengine_uk_columns=("firm_taxable_trading_profit",), + microcosm_columns=(), + requires=("attributes",), + columns=_single_column("firm_taxable_trading_profit"), + validate=_validate_profit_columns, + ), + UKFirmExportGroup( + name="rateable_value", + source_columns=("firm_rateable_value",), + policyengine_uk_columns=("firm_rateable_value",), + microcosm_columns=(), + requires=("attributes",), + columns=_single_column("firm_rateable_value"), + validate=_validate_rateable_value_columns, + ), + UKFirmExportGroup( + name="sic_division", + source_columns=("firm_sic_division",), + policyengine_uk_columns=(), + microcosm_columns=("firm_sic_division",), + requires=("attributes",), + columns=_sic_division_group_columns, + validate=_validate_sic_division_columns, + ), + UKFirmExportGroup( + name="labour_link", + source_columns=("employees",), + policyengine_uk_columns=(), + microcosm_columns=UK_FIRM_LABOUR_LINK_COLUMNS, + requires=("attributes", "paybill", "sic_division"), + columns=_labour_link_group_columns, + validate=_validate_labour_link_columns, + ), + UKFirmExportGroup( + name="employment_allowance_takeup", + source_columns=(UK_FIRM_EA_RULE_CLAIMS_COLUMN,), + policyengine_uk_columns=(), + microcosm_columns=(UK_FIRM_EA_RULE_CLAIMS_COLUMN,), + requires=( + "attributes", + "paybill", + "employment_allowance", + "sic_division", + "labour_link", + ), + columns=_employment_allowance_takeup_group_columns, + validate=_validate_employment_allowance_takeup_columns, + ), + UKFirmExportGroup( + name="rd_tax_credits", + source_columns=("firm_qualifying_rd_expenditure", "firm_is_sme"), + policyengine_uk_columns=("firm_qualifying_rd_expenditure", "firm_is_sme"), + microcosm_columns=(), + requires=("attributes",), + columns=_rd_group_columns, + validate=_validate_rd_columns, + ), + UKFirmExportGroup( + name="consumption", + source_columns=UK_FIRM_CONSUMPTION_COLUMNS, + policyengine_uk_columns=(), + microcosm_columns=UK_FIRM_CONSUMPTION_COLUMNS, + requires=("attributes", "sic_division"), + columns=_consumption_group_columns, + validate=_validate_consumption_columns, + ), + UKFirmExportGroup( + name="vat_composition", + source_columns=UK_FIRM_VAT_COMPOSITION_COLUMNS, + policyengine_uk_columns=(), + microcosm_columns=UK_FIRM_VAT_COMPOSITION_COLUMNS, + requires=("attributes",), + columns=_vat_composition_group_columns, + validate=_validate_vat_composition_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",)) + +#: policyengine-uk firm input variables in the paybill export (base, +#: attributes and paybill), in order. +UK_FIRM_PAYBILL_EXTENDED_POLICYENGINE_UK_COLUMNS = uk_firm_policyengine_uk_columns( + ("attributes", "paybill") +) + +#: The paybill export's columns (base, attributes and paybill), in order. +UK_FIRM_PAYBILL_TABLE_COLUMNS = uk_firm_table_columns(("attributes", "paybill")) + + +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, + ``UK_FIRM_EXTENDED_TABLE_COLUMNS`` with both + ``UK_FIRM_ONS_ATTRIBUTE_COLUMNS`` and ``UK_FIRM_PAYBILL_TABLE_COLUMNS`` + when attributed ``firms`` also carry ``firm_paybill`` (pounds a year, + from ``firm_paybill.assign_uk_firm_paybill``). Some of a group's source + columns without the rest (one ONS attribute column without the other), + or a group without one it extends (``firm_paybill`` without the ONS + attribute columns), 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; + - paybill only: ``firm_paybill`` is carried from the row unchanged. + + 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; + the paybill group a + finite non-negative ``firm_paybill`` that is zero for a firm without + employees. + """ + + 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_PAYBILL_EXTENDED_POLICYENGINE_UK_COLUMNS", + "UK_FIRM_PAYBILL_POLICYENGINE_UK_COLUMNS", + "UK_FIRM_PAYBILL_TABLE_COLUMNS", + "UK_FIRM_POLICYENGINE_UK_COLUMNS", + "UK_FIRM_POLICYENGINE_UK_INPUT_STATUS", + "UK_FIRM_PUBLIC_BODY_ONS_LEGAL_STATUSES", + "UK_FIRM_PUBLIC_SECTOR_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..5934aca3a6 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_target_candidates.py @@ -0,0 +1,443 @@ +"""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. + # The opt-in headcount redraw (firm_headcount.py, bpe_dir) reads the + # registered 0-4 employee rows of BPE 2025 Table 3, so those rows are + # in-sample for a build that uses it. + 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/src/microcosm/build/uk_runtime/firm_vat_composition.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_vat_composition.py new file mode 100644 index 0000000000..afefc92a34 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_vat_composition.py @@ -0,0 +1,766 @@ +"""UK firm VAT composition: zero-rated, reduced-rated and exempt supplies by SIC section. + +Opt-in, and **columns only**. The firm export scores VAT on wholly +standard-rated turnover with input VAT at 20% of input costs. This module +works out, for each SIC section, the split of sales into standard-, +reduced-, zero-rated and exempt supplies, the export share, the VAT rate on +purchases and the ratio of intermediate consumption to sales, from the ONS +Supply and Use Tables 2024 (Blue Book 2026) read through the VAT Act 1994 +schedules. :func:`add_uk_firm_vat_composition_columns` attaches them to the +firm table as Microcosm-only columns (``firm_sut_*``, status ``assumed``): +no policyengine-uk input changes, and the build's weights are untouched. + +**Not supported: the calibration seam.** :class:`UKFirmVATCompositionRules` +(VAT evaluated on the composition during calibration) and +:func:`rescale_uk_firm_input_costs` (input costs rescaled to the SUT ratio) +are kept for experiments and failed review (gate B2, 27 November 2026). On a +full 2024-25 build the VAT liability band accuracy fell to 0.998973 (seeds +2 and 3: 0.997182, 0.998228; bar 0.999), and the held-out error of VAT by +section doubled (sum of absolute section errors £168.0bn against £79.8bn; +section I at 3.6 times HMRC, G at 0.19 times). Applied to the reference +build's weights without a re-solve, the composition cuts VAT from £182.6bn +to £110.6bn: the frame carries about half of BPE's private turnover, so +realistic net rates cannot reach the HMRC liability totals and the solver +moves weight into high-net sections. (Those runs used the treatment table +before the ``exports`` rows and the ABS division weights for section G were +added.) + +**Sources** (``tests/fixtures/uk/firm_vat_composition_2024/``, with +``firm_supply_use_2024/`` for the product demand table): + +- ``vat_product_treatment.csv`` (hand-written): for each of the 103 SUT + products, the split of its sales into standard, reduced, zero and exempt + shares, by buyer where the law differs (``households``, ``other`` + domestic buyers, ``exports``; ``all`` covers every buyer not listed), with + the VATA 1994 group it rests on. ``statute`` rows have one treatment by + law; ``assumed`` rows carry a share set by judgement, never tuned to a + receipt or relief figure. Two rows are computed: construction + (``DWELLINGS``) and wholesale and retail (``GOODS``), below. +- ``sut_intermediate_consumption.csv``: the 'Combined Use' intermediate + consumption matrix, product by industry (industries written under the + product they make). +- ``sut_dwellings_gfcf.csv``: dwellings GFCF of the construction product. +- ``abs_section_turnover.csv``: ABS 2024 turnover by section and for + divisions 45, 46 and 47. +- ``hmrc_vat_relief_costs.csv``: HMRC tax relief statistics (January 2026), + for the checks only. + +**Output shares.** A product's sales are its Table 2 demand at purchasers' +prices (so they include imports, distributors' margins and product taxes, +as in ``firm_consumption.py``): households (the national-concept column), +other domestic uses (intermediate consumption, NPISH, government, GFCF, +valuables, inventories floored at 0) and exports. Each takes its buyer's +treatment. Exports are zero-rated (VATA s.30(6); services supplied abroad +are outside the scope with the right to recover, the same effect here), +except for the consumer services with an ``exports`` row (I55, I56, P85, +Q86, R90-R93, S96): their SUT exports are mostly non-residents' spending in +the UK, which is taxed as a UK supply. Construction's zero share is +dwellings GFCF times ``UK_FIRM_NEW_DWELLING_FRACTION`` (0.6, assumed) over +its total demand (Sch 8 Group 5). Retail (G47) sales take the treatment mix +of household purchases of goods (products with a positive distributors' +margin; it includes vehicles and fuel, which households also buy through +G45); wholesale (G46) takes the mix of non-household domestic and export +demand for goods; motor trade (G45) is standard. A section's shares are the +domestic-output weighted mean of its products' shares, each product counted +once per section, except section G, whose three trade products are weighted +by ABS 2024 division turnover (gross sales; the SUT's trade output is the +margin only). Imputed rent (``CPA_L68A``) is excluded. + +**Input VAT rate.** For industry ``j``, the intermediate-consumption +weighted mean of each product's VAT rate on business purchases +(``0.20 * standard + 0.05 * reduced`` of its ``other`` treatment). A +section's rate weights its industries by intermediate consumption. Capital +purchases are not included (stated, not patched). pe-uk applies the partial +exemption restriction itself (taxable / (taxable + exempt), rounded up). + +**Input ratio.** The SUT ratio of intermediate consumption to output by +section. Section G is on a gross-sales base: the ratio is +``1 - (margin - IC_G) / gross_sales`` with gross sales = ABS 2024 section G +turnover (assumed to share the SUT concept; wholesale sales to retailers +count in both). Section G's input VAT rate prices the goods resold +(gross sales less margin) at the margin-weighted business purchase rate of +goods and its own intermediate consumption at its SUT rate. The generator +clamp [0.10, 0.95] applies, so section T (no intermediate consumption) shows +0.10. + +**Assumptions stated once.** Shares are uniform across a section's firms (no +all-or-nothing draw; a wholly exempt bank gets the section mix). Public +administration (O84) is treated as exempt: its s.33 and s.41 refunds are not +modelled. The 2024-25 part year of VAT on private school fees (from 1 +January 2025) is folded into P85's assumed standard share. Zero-rating of +prescription drugs at dispensing is not modelled. + +**Checks, never targets** (:func:`uk_firm_vat_relief_checks`): the modelled +household base of eight zero- or reduced-rated reliefs against HMRC's 2024-25 +cost over the rate replaced. HMRC's 2024-25 figures for new dwellings and +prescription drugs (first forecast year 2023-24) and water and sewerage +(2024-25) are projections, not outturns; ``hmrc_vat_relief_costs.csv`` +carries each relief's first forecast year. All eight ratios are pinned in the tests, +including the poor ones (printed matter, domestic passenger transport) and +prescription drugs at 0 (not modelled). +""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Callable, Mapping +from dataclasses import dataclass +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_consumption import ( + UKFirmSupplyUseSource, + read_uk_firm_supply_use_source, +) + +UK_FIRM_VAT_TREATMENT_FILE = "vat_product_treatment.csv" +UK_FIRM_VAT_INT_CON_FILE = "sut_intermediate_consumption.csv" +UK_FIRM_VAT_DWELLINGS_FILE = "sut_dwellings_gfcf.csv" +UK_FIRM_VAT_ABS_FILE = "abs_section_turnover.csv" +UK_FIRM_VAT_RELIEF_FILE = "hmrc_vat_relief_costs.csv" +UK_FIRM_VAT_COMPOSITION_FILES = ( + UK_FIRM_VAT_TREATMENT_FILE, + UK_FIRM_VAT_INT_CON_FILE, + UK_FIRM_VAT_DWELLINGS_FILE, + UK_FIRM_VAT_ABS_FILE, + UK_FIRM_VAT_RELIEF_FILE, +) +UK_FIRM_VAT_COMPOSITION_STATUS = "assumed" +#: The supplies, in the order of the treatment table's share columns. +UK_FIRM_VAT_TREATMENTS = ("standard", "reduced", "zero", "exempt") +UK_FIRM_VAT_USERS = ("all", "households", "other", "exports") +UK_FIRM_VAT_SUPPLY_COLUMNS = { + "standard": "firm_standard_rated_supplies", + "reduced": "firm_reduced_rated_supplies", + "zero": "firm_zero_rated_supplies", + "exempt": "firm_exempt_supplies", +} +UK_FIRM_VAT_STANDARD_RATE = 0.20 +UK_FIRM_VAT_REDUCED_RATE = 0.05 +#: Share of construction's dwellings GFCF that is new build (Sch 8 Group 5), assumed. +UK_FIRM_NEW_DWELLING_FRACTION = 0.6 +#: The clamp the generator puts on the input ratio +#: (``firm_generation.INPUT_RATIO_LOWER`` / ``INPUT_RATIO_UPPER``; not imported, +#: because firm_generation imports firm_table, which imports this module). +UK_FIRM_INPUT_RATIO_BOUNDS = (0.10, 0.95) +#: Microcosm-only columns the columns-only mode adds (not policyengine-uk inputs). +UK_FIRM_VAT_COMPOSITION_SHARE_COLUMNS = { + "standard": "firm_sut_standard_rated_share", + "reduced": "firm_sut_reduced_rated_share", + "zero": "firm_sut_zero_rated_share", + "exempt": "firm_sut_exempt_share", + "export_share": "firm_sut_export_share", + "input_vat_rate": "firm_sut_input_vat_rate", + "input_ratio_target": "firm_sut_input_ratio", +} +_CONSTRUCTION = "CPA_F41, F42 & F43" +_TRADE = {"CPA_G45": "45", "CPA_G46": "46", "CPA_G47": "47"} +_EXCLUDED = ("CPA_L68A",) +_COMPUTED = ("DWELLINGS", "GOODS") +_ZERO = np.array([0.0, 0.0, 1.0, 0.0]) +_OTHER_DOMESTIC = ( + "intermediate_consumption", + "npish", + "central_government", + "local_government", + "gfcf", + "valuables", + "changes_in_inventories", +) +_WHOLESALE_DOMESTIC = ( + "intermediate_consumption", + "npish", + "central_government", + "local_government", + "gfcf", +) +#: Each relief check: (HMRC code, rate the relief replaces, treatment, products; +#: ``None`` = food products). NS5 is domestic passenger transport: rail and +#: bus/coach only (water and air passenger transport are mostly international). +_RELIEF_CHECKS: Mapping[str, tuple[str, float, str, tuple[str, ...] | None]] = { + "NS7 food (zero)": ("VAT - NS7", 0.20, "zero", None), + "NS1 printed matter (zero)": ("VAT - NS1", 0.20, "zero", ("CPA_J58",)), + "NS2 children's clothing (zero)": ( + "VAT - NS2", + 0.20, + "zero", + ("CPA_C14", "CPA_C15"), + ), + "NS3 new dwellings (zero)": ("VAT - NS3", 0.20, "zero", ()), + "NS4 domestic fuel and power (reduced)": ( + "VAT - NS4", + 0.15, + "reduced", + ("CPA_D351", "CPA_D352_3"), + ), + "NS5 domestic passenger transport (zero)": ( + "VAT - NS5", + 0.20, + "zero", + ("CPA_H491_2", "CPA_H493_5"), + ), + "NS6 prescription drugs (zero)": ("VAT - NS6", 0.20, "zero", ("CPA_C21",)), + "NS16 water and sewerage (zero)": ( + "VAT - NS16", + 0.20, + "zero", + ("CPA_E36", "CPA_E37"), + ), +} + + +@dataclass(frozen=True) +class UKFirmVATCompositionSource: + """The VAT composition inputs: treatment table, IC matrix, dwellings, ABS, reliefs, SUT.""" + + treatment: pd.DataFrame + intermediate: pd.DataFrame + dwellings_gfcf_gbp_million: float + abs_turnover: pd.DataFrame + relief_costs: pd.DataFrame + supply_use: UKFirmSupplyUseSource + sha256: Mapping[str, str] + + +def _validate_treatment(treatment: pd.DataFrame, products: set[str]) -> None: + if not set(treatment["user"]) <= set(UK_FIRM_VAT_USERS): + raise ValueError(f"VAT treatment user must be one of {UK_FIRM_VAT_USERS}.") + if treatment.duplicated(["product_code", "user"]).any(): + raise ValueError("VAT treatment repeats a (product, user) row.") + if not set(treatment["status"]) <= {"statute", "assumed"}: + raise ValueError("VAT treatment status must be statute or assumed.") + if set(treatment["product_code"]) != products: + raise ValueError("Every SUT product needs a VAT treatment, and only those.") + for product, rows in treatment.groupby("product_code"): + users = set(rows["user"]) + if "all" not in users and not {"households", "other"} <= users: + raise ValueError( + f"{product} needs an all row, or households and other rows." + ) + computed = treatment["standard"].isin(_COMPUTED) + allowed = {_CONSTRUCTION, "CPA_G46", "CPA_G47"} + if set(treatment.loc[computed, "product_code"]) - allowed: + raise ValueError("Only construction and G46/G47 have computed treatments.") + numeric = treatment.loc[~computed, list(UK_FIRM_VAT_TREATMENTS)].astype(np.float64) + if ((numeric < 0) | (numeric > 1)).any().any(): + raise ValueError("VAT treatment shares must lie in [0, 1].") + if not np.allclose(numeric.sum(axis=1), 1.0, atol=1e-12): + raise ValueError("VAT treatment shares must sum to 1 on every row.") + + +def read_uk_firm_vat_composition_source( + path: str | Path, supply_use_path: str | Path +) -> UKFirmVATCompositionSource: + """Read the fixture directory and the supply and use directory it builds on. + + Raises ``ValueError`` when a file's sha256 differs from ``provenance.json``, + a treatment row is malformed (unknown user or status, repeated, shares + outside [0, 1] or not summing to 1), a product lacks a treatment, the + matrix names an unknown product, or the ABS table lacks section G or + divisions 45-47. + """ + + directory = Path(path) + provenance = json.loads((directory / "provenance.json").read_text()) + hashes: dict[str, str] = {} + for name in UK_FIRM_VAT_COMPOSITION_FILES: + digest = hashlib.sha256((directory / name).read_bytes()).hexdigest() + if provenance["files"][name]["sha256"] != digest: + raise ValueError(f"{name} sha256 differs from provenance.json.") + hashes[name] = digest + supply_use = read_uk_firm_supply_use_source(supply_use_path) + products = set(supply_use.uses.index) + treatment = pd.read_csv(directory / UK_FIRM_VAT_TREATMENT_FILE, dtype=str) + _validate_treatment(treatment, products) + intermediate = pd.read_csv(directory / UK_FIRM_VAT_INT_CON_FILE) + named = set(intermediate["product_code"]) | set( + intermediate["industry_product_code"] + ) + if not named <= products: + raise ValueError("The intermediate consumption matrix names unknown products.") + dwellings = pd.read_csv(directory / UK_FIRM_VAT_DWELLINGS_FILE) + abs_turnover = pd.read_csv( + directory / UK_FIRM_VAT_ABS_FILE, dtype={"sic_section": str} + ) + if not {"G", *_TRADE.values()} <= set(abs_turnover["sic_section"]): + raise ValueError("The ABS table needs section G and divisions 45, 46 and 47.") + relief_costs = pd.read_csv(directory / UK_FIRM_VAT_RELIEF_FILE) + return UKFirmVATCompositionSource( + treatment=treatment, + intermediate=intermediate, + dwellings_gfcf_gbp_million=float( + dwellings["dwellings_gfcf_gbp_million"].iloc[0] + ), + abs_turnover=abs_turnover, + relief_costs=relief_costs, + supply_use=supply_use, + sha256=MappingProxyType(hashes | dict(supply_use.sha256)), + ) + + +_LOOKUP = { + "households": ("households", "all"), + "other": ("other", "all"), + "exports": ("exports",), + "all": ("all", "other"), +} + + +def _treatment( + source: UKFirmVATCompositionSource, product: str, user: str +) -> pd.Series | None: + rows = source.treatment[source.treatment["product_code"] == product] + for name in _LOOKUP[user]: + row = rows[rows["user"] == name] + if not row.empty: + return row.iloc[0] + if user == "exports": + return None + raise ValueError(f"No VAT treatment for {product}.") + + +def _goods(uses: pd.DataFrame) -> list[str]: + return [p for p in uses.index if uses.loc[p, "distributors_margins"] > 0] + + +def _vector( + source: UKFirmVATCompositionSource, product: str, user: str, *, nested: bool = False +) -> np.ndarray: + """Standard, reduced, zero, exempt shares of ``product``'s sales to ``user``.""" + + row = _treatment(source, product, user) + if row is None: # exports with no exports row: zero-rated (s.30(6)) + return _ZERO.copy() + uses = source.supply_use.uses + marker = row["standard"] + if marker == "DWELLINGS": + zero = ( + source.dwellings_gfcf_gbp_million + * UK_FIRM_NEW_DWELLING_FRACTION + / uses.loc[product, "total_demand"] + ) + return np.array([1.0 - zero, 0.0, zero, 0.0]) + if marker == "GOODS": + if nested: + raise ValueError(f"{product}: a trade product cannot resell trade.") + goods = _goods(uses) + if product == "CPA_G47": + weight = uses.loc[goods, "households"].clip(lower=0) + mix = sum( + weight[g] * _vector(source, g, "households", nested=True) for g in goods + ) + return mix / weight.sum() + total = np.zeros(4) + mass = 0.0 + for g in goods: + domestic = float(uses.loc[g, list(_WHOLESALE_DOMESTIC)].clip(lower=0).sum()) + exported = max(float(uses.loc[g, "exports"]), 0.0) + total += domestic * _vector(source, g, "other", nested=True) + total += exported * _vector(source, g, "exports", nested=True) + mass += domestic + exported + return total / mass + return row[list(UK_FIRM_VAT_TREATMENTS)].astype(np.float64).to_numpy() + + +def _purchase_rate(source: UKFirmVATCompositionSource, product: str) -> float: + """VAT rate a business pays when it buys ``product`` (its ``other`` treatment).""" + + if product in _EXCLUDED: + return 0.0 + v = _vector(source, product, "other") + return UK_FIRM_VAT_STANDARD_RATE * v[0] + UK_FIRM_VAT_REDUCED_RATE * v[1] + + +def uk_firm_vat_product_shares(source: UKFirmVATCompositionSource) -> pd.DataFrame: + """Per product: output shares, export share, domestic output, IC and input VAT rate.""" + + uses = source.supply_use.uses + goods = _goods(uses) + rows = {} + for p in uses.index: + if p in _EXCLUDED: + continue + if p in ("CPA_G46", "CPA_G47"): + shares = _vector(source, p, "all") + if p == "CPA_G46": + ex = sum(max(float(uses.loc[g, "exports"]), 0.0) for g in goods) + dom = sum( + float(uses.loc[g, list(_WHOLESALE_DOMESTIC)].clip(lower=0).sum()) + for g in goods + ) + export_share = ex / (ex + dom) + else: + export_share = 0.0 + else: + hh = max(float(uses.loc[p, "households"]), 0.0) + dom = float(uses.loc[p, list(_OTHER_DOMESTIC)].clip(lower=0).sum()) + ex = max(float(uses.loc[p, "exports"]), 0.0) + total = hh + dom + ex + shares = ( + hh * _vector(source, p, "households") + + dom * _vector(source, p, "other") + + ex * _vector(source, p, "exports") + ) / total + export_share = ex / total + rows[p] = dict(zip(UK_FIRM_VAT_TREATMENTS, shares, strict=True)) | { + "export_share": export_share, + "domestic_output": float(uses.loc[p, "domestic_output"]), + } + frame = pd.DataFrame(rows).T + rate = pd.Series({p: _purchase_rate(source, p) for p in uses.index}) + ic = source.intermediate + ic = ic.assign(vat=ic["value_gbp_million"] * ic["product_code"].map(rate)) + by_industry = ic.groupby("industry_product_code")[ + ["vat", "value_gbp_million"] + ].sum() + frame["intermediate_consumption"] = ( + by_industry["value_gbp_million"].reindex(frame.index).fillna(0.0) + ) + frame["input_vat_rate"] = ( + by_industry["vat"] / by_industry["value_gbp_million"] + ).reindex(frame.index) + return frame.astype(np.float64) + + +def uk_firm_vat_section_shares(source: UKFirmVATCompositionSource) -> pd.DataFrame: + """By SIC section: output shares, export share, input VAT rate and input ratio.""" + + products = uk_firm_vat_product_shares(source) + abs_turnover = source.abs_turnover.set_index("sic_section")["turnover_gbp_million"] + sections = source.supply_use.divisions[ + ["product_code", "sic_section"] + ].drop_duplicates() + sections = sections[sections["product_code"].isin(products.index)] + keys = (*UK_FIRM_VAT_TREATMENTS, "export_share") + rows = {} + for section, group in sections.groupby("sic_section"): + p = products.loc[group["product_code"]] + if section == "G": + # Gross-sales weights: ABS 2024 turnover of divisions 45, 46, 47. + w = pd.Series({c: float(abs_turnover[d]) for c, d in _TRADE.items()})[ + p.index + ] + else: + w = p["domestic_output"] + ic = p["intermediate_consumption"] + row: dict[str, Any] = {k: float(np.average(p[k], weights=w)) for k in keys} + row["input_vat_rate"] = ( + float(np.average(p["input_vat_rate"].fillna(0.0), weights=ic)) + if ic.sum() > 0 + else 0.0 + ) + row["input_ratio_target"] = float(ic.sum() / p["domestic_output"].sum()) + row["output_gbp_million"] = float(p["domestic_output"].sum()) + rows[section] = row + frame = pd.DataFrame(rows).T + uses = source.supply_use.uses + trade = products.loc[[c for c in _TRADE if c in products.index]] + margin = float(trade["domestic_output"].sum()) + ic_g = float(trade["intermediate_consumption"].sum()) + gross = float(abs_turnover["G"]) + goods = _goods(uses) + m = uses.loc[goods, "distributors_margins"] + goods_rate = float(sum(m[g] * _purchase_rate(source, g) for g in goods) / m.sum()) + goods_resold = gross - margin + frame.loc["G", "input_vat_rate"] = ( + goods_resold * goods_rate + ic_g * frame.loc["G", "input_vat_rate"] + ) / (goods_resold + ic_g) + frame.loc["G", "input_ratio_target"] = 1.0 - (margin - ic_g) / gross + frame.loc["G", "output_gbp_million"] = gross + lo, hi = UK_FIRM_INPUT_RATIO_BOUNDS + frame["input_ratio_target"] = frame["input_ratio_target"].clip(lo, hi) + shares = list(UK_FIRM_VAT_TREATMENTS) + if not np.allclose(frame[shares].sum(axis=1), 1.0, atol=1e-9): + raise ValueError("VAT composition section shares do not sum to 1.") + frame.index.name = "sic_section" + return frame + + +def add_uk_firm_vat_composition_columns( + firms: pd.DataFrame, shares: pd.DataFrame +) -> pd.DataFrame: + """``firms`` with the section composition as Microcosm-only share columns. + + The supported (columns-only) use: every policyengine-uk input, including + the supply columns and ``firm_input_vat``, keeps the value the build + solved its weights for. Refuses a table that already has a share column + and a section with no shares. + """ + + clash = sorted( + set(UK_FIRM_VAT_COMPOSITION_SHARE_COLUMNS.values()) & set(firms.columns) + ) + if clash: + raise ValueError(f"firm table already has {clash}.") + sections = firms["firm_sic_section"].astype(str) + missing = sorted(set(sections) - set(shares.index)) + if missing: + raise ValueError(f"No VAT composition shares for sections {missing}.") + rows = shares.reindex(sections.to_numpy()) + out = firms.copy() + for key, column in UK_FIRM_VAT_COMPOSITION_SHARE_COLUMNS.items(): + out[column] = rows[key].to_numpy(np.float64) + return out + + +def compose_uk_firm_vat_supplies( + firms: pd.DataFrame, shares: pd.DataFrame, in_scope: np.ndarray | None = None +) -> pd.DataFrame: + """Experimental (failed B2): the supply columns and ``firm_input_vat`` from shares. + + Rows in VAT scope (all, when ``in_scope`` is None) take their section's + shares of ``firm_turnover``; other rows stay wholly exempt, as the default + export has them. ``firm_input_vat`` is the section rate times + ``firm_input_costs``. Raises ``ValueError`` for a section with no shares. + """ + + sections = firms["firm_sic_section"].astype(str) + missing = sorted(set(sections) - set(shares.index)) + if missing: + raise ValueError(f"No VAT composition shares for sections {missing}.") + rows = shares.reindex(sections.to_numpy()) + turnover = firms["firm_turnover"].to_numpy(np.float64) + scope = ( + np.ones(len(firms), bool) if in_scope is None else np.asarray(in_scope, bool) + ) + out = firms.copy() + for key, column in UK_FIRM_VAT_SUPPLY_COLUMNS.items(): + part = turnover * rows[key].to_numpy(np.float64) + out[column] = np.where(scope, part, turnover if key == "exempt" else 0.0) + out["firm_input_vat"] = rows["input_vat_rate"].to_numpy(np.float64) * out[ + "firm_input_costs" + ].to_numpy(np.float64) + return out + + +def uk_firm_vat_voluntary_registration( + firms: pd.DataFrame, vat_registered: np.ndarray, threshold_gbp: float +) -> np.ndarray: + """Experimental (failed B2): registered rows at or below the threshold on taxable turnover. + + pe-uk registers a firm on taxable (standard + reduced + zero) turnover, so + a registered row the composition takes to the threshold or below keeps + its registration through ``firm_vat_voluntarily_registered``. + """ + + taxable = sum( + firms[UK_FIRM_VAT_SUPPLY_COLUMNS[k]].to_numpy(np.float64) + for k in ("standard", "reduced", "zero") + ) + return np.asarray(vat_registered, bool) & (taxable <= threshold_gbp) + + +def uk_firm_input_ratio_factors( + sections: np.ndarray, + ratio: np.ndarray, + turnover: np.ndarray, + targets: pd.Series, + *, + iterations: int = 200, +) -> dict[str, dict[str, float]]: + """Experimental (failed B2): ``k_s`` per section so the clipped mean ratio hits the target. + + Deterministic bisection on ``log k`` in [1e-3, 1e3]; the mean is + turnover-weighted over ``clip(ratio * k_s, 0.10, 0.95)``. A section with + no positive turnover, or no target, gets ``k = 1`` and ``rescaled = 0``. + """ + + lo, hi = UK_FIRM_INPUT_RATIO_BOUNDS + sections = np.asarray(sections).astype(str) + out: dict[str, dict[str, float]] = {} + for section in sorted(set(sections)): + mask = sections == section + r, w = np.asarray(ratio)[mask], np.asarray(turnover, np.float64)[mask] + + def mean(k: float, r: np.ndarray = r, w: np.ndarray = w) -> float: + return float(np.average(np.clip(r * k, lo, hi), weights=w)) + + if w.sum() <= 0 or section not in targets.index: + out[section] = { + "k": 1.0, + "target": float("nan"), + "achieved": float("nan"), + "before": float("nan"), + "rescaled": 0.0, + } + continue + target = float(targets[section]) + a, b = 1e-3, 1e3 + for _ in range(iterations): + mid = float(np.sqrt(a * b)) + if mean(mid) < target: + a = mid + else: + b = mid + k = float(np.sqrt(a * b)) + out[section] = { + "k": k, + "target": target, + "achieved": mean(k), + "before": mean(1.0), + "rescaled": 1.0, + } + return out + + +def rescale_uk_firm_input_costs( + turnover: np.ndarray, + input_costs: np.ndarray, + sections: np.ndarray, + targets: pd.Series, +) -> tuple[np.ndarray, dict[str, dict[str, float]]]: + """Experimental (failed B2): input costs rescaled by section to the target ratio. + + Rows with positive turnover in a section that has a target become + ``turnover * clip(input / turnover * k_s, 0.10, 0.95)``; every other row + keeps its input costs unchanged. + """ + + turnover = np.asarray(turnover, np.float64) + input_costs = np.asarray(input_costs, np.float64) + sections = np.asarray(sections).astype(str) + positive = turnover > 0 + ratio = np.divide( + input_costs, turnover, out=np.zeros_like(turnover), where=positive + ) + factors = uk_firm_input_ratio_factors( + sections[positive], ratio[positive], turnover[positive], targets + ) + k = np.array([factors.get(s, {"k": 1.0})["k"] for s in sections]) + moved = positive & np.array( + [factors.get(s, {"rescaled": 0.0})["rescaled"] > 0 for s in sections], + dtype=bool, + ) + lo, hi = UK_FIRM_INPUT_RATIO_BOUNDS + return np.where(moved, turnover * np.clip(ratio * k, lo, hi), input_costs), factors + + +#: Candidate columns the composition rules hand to policyengine-uk. +UK_FIRM_VAT_COMPOSITION_RULE_COLUMNS = ( + "firm_id", + "firm_turnover", + "firm_input_costs", + "firm_employees", + "firm_sic_section", + *UK_FIRM_VAT_SUPPLY_COLUMNS.values(), + "firm_input_vat", +) + + +@dataclass(frozen=True) +class UKFirmVATCompositionRules: + """Experimental (failed B2): ``UKFirmRules`` that evaluate VAT on the section composition. + + ``PolicyEngineUKFirmRules`` hands only its fixed input columns to the + simulation, which have no zero- or reduced-rated supplies, so recovery + would be standard / (standard + exempt). This class composes the + candidate table and calls the simulation factory itself with + ``UK_FIRM_VAT_COMPOSITION_RULE_COLUMNS``. Every candidate row is + composed: the rules return the liability if registered, before VAT scope + and registration are assigned. ``simulation_factory`` defaults to + ``policyengine_uk_firm_simulation``. + """ + + shares: pd.DataFrame + simulation_factory: Callable[[pd.DataFrame, int], object] | None = None + name: str = "policyengine_uk_vat_composition" + + def evaluate(self, firms: pd.DataFrame, *, period: int): + from microcosm.build.uk_runtime.firm_policyengine_uk_rules import ( + policyengine_uk_firm_simulation, + policyengine_uk_version, + ) + from microcosm.build.uk_runtime.firm_rules import UKFirmRuleOutputs + + period = int(period) + table = compose_uk_firm_vat_supplies(firms, self.shares) + table = table.loc[:, list(UK_FIRM_VAT_COMPOSITION_RULE_COLUMNS)].reset_index( + drop=True + ) + factory = self.simulation_factory or policyengine_uk_firm_simulation + simulation = factory(table, period) + liability = np.asarray( + simulation.calculate("firm_vat_liability_if_registered", period), + dtype=np.float64, + ) + firm_id = table["firm_id"].to_numpy(np.int64) + simulated = np.asarray(simulation.calculate("firm_id", period)).astype(np.int64) + if liability.shape != firm_id.shape or not np.array_equal(simulated, firm_id): + raise ValueError( + "policyengine-uk's firm_id order differs from the candidate table's." + ) + if not np.all(np.isfinite(liability)): + raise ValueError("policyengine-uk returned a non-finite VAT liability.") + return UKFirmRuleOutputs( + firm_id=firm_id, + vat_liability_if_registered=liability, + provenance={ + "rules": self.name, + "policyengine_uk_version": policyengine_uk_version(), + "variable": "firm_vat_liability_if_registered", + "period": str(period), + "output": "vat_liability_if_registered", + "vat_composition": "section shares, firm_vat_composition.py (experimental)", + }, + ) + + +def uk_firm_vat_relief_checks(source: UKFirmVATCompositionSource) -> pd.DataFrame: + """Modelled relief bases against HMRC relief cost / rate (pounds billion); a check only.""" + + uses = source.supply_use.uses + costs = source.relief_costs.set_index("code")["cost_2024_25_gbp_million"] + food = [ + p for p in uses.index if p.startswith("CPA_C10") or p in ("CPA_A01", "CPA_A03") + ] + + def household(product: str, key: str) -> float: + share = _vector(source, product, "households")[ + UK_FIRM_VAT_TREATMENTS.index(key) + ] + return float(uses.loc[product, "households"]) * share + + rows = {} + for name, (code, rate, key, products) in _RELIEF_CHECKS.items(): + if name.startswith("NS3"): + model = source.dwellings_gfcf_gbp_million * UK_FIRM_NEW_DWELLING_FRACTION + else: + model = sum( + household(p, key) for p in (food if products is None else products) + ) + base = float(costs[code]) / rate + rows[name] = { + "model_base_gbp_bn": model / 1e3, + "relief_base_gbp_bn": base / 1e3, + "ratio": model / base, + } + return pd.DataFrame(rows).T + + +__all__ = [ + "UK_FIRM_INPUT_RATIO_BOUNDS", + "UK_FIRM_NEW_DWELLING_FRACTION", + "UK_FIRM_VAT_COMPOSITION_FILES", + "UK_FIRM_VAT_COMPOSITION_RULE_COLUMNS", + "UK_FIRM_VAT_COMPOSITION_SHARE_COLUMNS", + "UK_FIRM_VAT_COMPOSITION_STATUS", + "UK_FIRM_VAT_SUPPLY_COLUMNS", + "UK_FIRM_VAT_TREATMENTS", + "UK_FIRM_VAT_USERS", + "UKFirmVATCompositionRules", + "UKFirmVATCompositionSource", + "add_uk_firm_vat_composition_columns", + "compose_uk_firm_vat_supplies", + "read_uk_firm_vat_composition_source", + "rescale_uk_firm_input_costs", + "uk_firm_input_ratio_factors", + "uk_firm_vat_product_shares", + "uk_firm_vat_relief_checks", + "uk_firm_vat_section_shares", + "uk_firm_vat_voluntary_registration", +] 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_bpe_turnover.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_bpe_turnover.py new file mode 100644 index 0000000000..6b4b6d72eb --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_bpe_turnover.py @@ -0,0 +1,398 @@ +"""Tests for the UK firm BPE turnover re-pairing and open-band tail.""" + +from __future__ import annotations + +import math +import re +from functools import cache + +import numpy as np +import pandas as pd +import pytest +import torch + +from microcosm.build.uk_runtime import firm_bpe_turnover as bt +from microcosm.build.uk_runtime import firm_generation as fg +from microcosm.build.uk_runtime.firm_headcount import ( + UKFirmBPESource, + read_uk_firm_bpe_source, +) +from test_support.paths import paths_for + +PATHS = paths_for("microcosm-build") +FIXTURES = PATHS.tests / "fixtures" / "uk" +BPE = FIXTURES / "firm_bpe_2025" +FIRM = FIXTURES / "firm_2024_25" +MODULE = PATHS.package / "src" / "microcosm" / "build" / "uk_runtime" + + +@cache +def _bpe() -> UKFirmBPESource: + return read_uk_firm_bpe_source(BPE) + + +@cache +def _firm_data() -> fg.UKFirmSourceData: + return fg.read_uk_firm_source_data(FIRM) + + +def _synthetic(n: int = 6_000, seed: int = 0) -> dict[str, np.ndarray]: + rng = np.random.default_rng(seed) + sic = rng.choice([10, 47, 64], size=n) + turnover = np.exp(rng.normal(5.0, 1.6, n)) + employment = np.maximum(1, np.round(np.exp(rng.normal(1.5, 1.4, n)))).astype( + np.int64 + ) + in_frame = rng.random(n) > 0.05 + return { + "sic": sic, + "turnover": turnover, + "employment": employment, + "in_frame": in_frame, + } + + +# -- constants agree with the generator ------------------------------------------ + + +def test_band_definitions_match_generator() -> None: + assert bt.UK_FIRM_TURNOVER_EMPLOYMENT_BANDS == fg.EMPLOYMENT_BANDS + values = np.arange(0, 3_000) + np.testing.assert_array_equal( + bt.uk_firm_employment_band_index(values), + fg.employment_band_index_array(values), + ) + lower, upper, _ = fg.ONS_TURNOVER_BANDS[fg.ONS_OPEN_TURNOVER_BAND] + assert bt.ONS_OPEN_TURNOVER_BAND_LABEL == fg.ONS_OPEN_TURNOVER_BAND + assert bt.OPEN_BAND_LOWER_K == lower + assert bt.OPEN_BAND_LOG_UNIFORM_UPPER_K == upper + edge = bt.HMRC_TOP_BAND_LOWER_K + assert fg.hmrc_band_name(edge, 90.0) != bt.HMRC_TOP_TURNOVER_BAND + assert fg.hmrc_band_name(np.nextafter(edge, np.inf), 90.0) == ( + bt.HMRC_TOP_TURNOVER_BAND + ) + + +def test_module_avoids_banned_guards() -> None: + text = (MODULE / "firm_bpe_turnover.py").read_text() + for banned in ("<" + "= 9", "<" + " 10", "fewer than " + "ten"): + assert banned not in text.lower() + assert not re.search(r"nunique|value_counts", text) + assert "import firm_generation" not in text + assert "firm_generation import" not in text + + +# -- A. re-pairing --------------------------------------------------------------- + + +@pytest.mark.parametrize("rho", [0.0, 0.5, 1.0]) +def test_repair_keeps_division_multisets_and_out_of_frame(rho: float) -> None: + d = _synthetic() + after = bt.repair_uk_firm_employment_turnover(**d, rho=rho, seed=3) + assert after.dtype == d["employment"].dtype + frame = d["in_frame"] + np.testing.assert_array_equal(after[~frame], d["employment"][~frame]) + for division in np.unique(d["sic"]): + rows = frame & (d["sic"] == division) + np.testing.assert_array_equal( + np.sort(after[rows]), np.sort(d["employment"][rows]) + ) + + +def test_repair_rho_one_is_monotone_within_division() -> None: + d = _synthetic() + after = bt.repair_uk_firm_employment_turnover(**d, rho=1.0, seed=3) + for division in np.unique(d["sic"]): + rows = np.flatnonzero(d["in_frame"] & (d["sic"] == division)) + ordered = after[rows[np.argsort(d["turnover"][rows])]] + assert np.all(np.diff(ordered) >= 0) + + +def test_repair_rho_zero_ignores_turnover() -> None: + d = _synthetic() + base = bt.repair_uk_firm_employment_turnover(**d, rho=0.0, seed=3) + other = dict(d, turnover=np.random.default_rng(9).random(len(d["sic"]))) + np.testing.assert_array_equal( + bt.repair_uk_firm_employment_turnover(**other, rho=0.0, seed=3), base + ) + # A random permutation: it moves values but not toward turnover rank. + assert np.mean(base != d["employment"]) > 0.3 + frame = d["in_frame"] + corr = np.corrcoef( + np.argsort(np.argsort(d["turnover"][frame])), + np.argsort(np.argsort(base[frame], kind="stable")), + )[0, 1] + assert abs(corr) < 0.05 + + +def test_repair_is_deterministic_and_row_order_free() -> None: + d = _synthetic() + ids = np.arange(100, 100 + len(d["sic"])) + first = bt.repair_uk_firm_employment_turnover(**d, rho=0.7, seed=5, firm_ids=ids) + again = bt.repair_uk_firm_employment_turnover(**d, rho=0.7, seed=5, firm_ids=ids) + np.testing.assert_array_equal(first, again) + perm = np.random.default_rng(1).permutation(len(ids)) + shuffled = bt.repair_uk_firm_employment_turnover( + **{k: v[perm] for k, v in d.items()}, rho=0.7, seed=5, firm_ids=ids[perm] + ) + np.testing.assert_array_equal(shuffled, first[perm]) + other_seed = bt.repair_uk_firm_employment_turnover( + **d, rho=0.7, seed=6, firm_ids=ids + ) + assert np.any(other_seed != first) + + +def test_repair_rejects_bad_inputs() -> None: + d = _synthetic(200) + with pytest.raises(ValueError, match="rho"): + bt.repair_uk_firm_employment_turnover(**d, rho=1.5, seed=0) + ids = np.zeros(200, dtype=np.int64) + with pytest.raises(ValueError, match="repeat"): + bt.repair_uk_firm_employment_turnover(**d, rho=0.5, seed=0, firm_ids=ids) + + +# -- B. rho fit ------------------------------------------------------------------ + + +def _shares(sic, turnover, employment, in_frame) -> np.ndarray: + mask = in_frame & ~np.isin(sic, bt.SIC_SECTION_K_DIVISIONS) + totals = np.bincount( + bt.uk_firm_employment_band_index(employment[mask]), + weights=turnover[mask], + minlength=7, + ) + return totals / totals.sum() + + +def test_fit_recovers_known_rho() -> None: + d = _synthetic(40_000, seed=11) + true_rho = 0.6 + truth = bt.repair_uk_firm_employment_turnover(**d, rho=true_rho, seed=101) + target = _shares(d["sic"], d["turnover"], truth, d["in_frame"]) + fit = bt.fit_uk_firm_employment_turnover_rho( + **d, base_weights=np.ones(len(d["sic"])), source=target, seed=202 + ) + assert abs(fit.rho - true_rho) < 0.05 + assert not fit.at_bound + np.testing.assert_allclose(fit.table["target_share"], target) + + +def test_fit_table_is_reproduced_by_repair_and_diagnostics() -> None: + d = _synthetic(8_000, seed=4) + weights = np.random.default_rng(2).uniform(0.5, 2.0, len(d["sic"])) + fit = bt.fit_uk_firm_employment_turnover_rho( + **d, base_weights=weights, source=_bpe(), seed=7 + ) + assert 0.0 <= fit.rho <= bt.RHO_UPPER + assert fit.sse == pytest.approx(fit.search["sse"].min()) + after = bt.repair_uk_firm_employment_turnover(**d, rho=fit.rho, seed=7) + diag = bt.uk_firm_turnover_by_employment_band( + d["sic"], d["turnover"], after, d["in_frame"], weights, _bpe() + ) + np.testing.assert_allclose(diag["model_share"], fit.table["model_share_fitted"]) + np.testing.assert_allclose(diag["bpe_share"], fit.table["target_share"]) + before = bt.uk_firm_turnover_by_employment_band( + d["sic"], d["turnover"], d["employment"], d["in_frame"], weights, _bpe() + ) + np.testing.assert_allclose(before["model_share"], fit.table["model_share_before"]) + + +def test_fit_flags_bound() -> None: + d = _synthetic(4_000, seed=8) + # Two headcounts, all target turnover in the top band: the error falls + # as the pairing tightens, so the search ends at its upper bound. + d["employment"] = np.where(np.arange(4_000) % 2 == 0, 1, 300) + target = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0] + fit = bt.fit_uk_firm_employment_turnover_rho( + **d, base_weights=np.ones(len(d["sic"])), source=target, seed=2 + ) + assert fit.rho == bt.RHO_UPPER + assert fit.at_bound + + +def test_fit_accepts_synthetic_bpe_source() -> None: + labels = [ + x + for band in bt.UK_FIRM_TURNOVER_EMPLOYMENT_BANDS + for x in bt.UK_FIRM_BPE_BANDS_BY_ONS_BAND[band] + ] + rows = [("Table 2", "whole_economy", label, 10.0) for label in labels] + rows += [ + ("Table 2", "whole_economy", "All", 10.0 * len(labels)), + ("Table 1", "private_sector", "With no employees (unregistered)", 5.0), + ] + size = pd.DataFrame( + rows, columns=["table", "sector", "size_band", "turnover_million"] + ) + source = UKFirmBPESource(legal_status=pd.DataFrame(), size_bands=size, sha256={}) + table = bt.uk_firm_bpe_turnover_by_band(source) + assert table["bpe_turnover_million"].iloc[0] == 15.0 + d = _synthetic(2_000) + fit = bt.fit_uk_firm_employment_turnover_rho( + **d, base_weights=np.ones(2_000), source=source, seed=1 + ) + np.testing.assert_allclose(fit.table["target_share"], table["bpe_share"]) + + +# -- C. open-band tail ----------------------------------------------------------- + + +@pytest.mark.parametrize("n", [1, 7, 5_000]) +def test_tail_draw_bounds_and_exact_mean(n: int) -> None: + alpha, cap, lower = 0.83, 6.2e6, 5_000.0 + uniforms = np.random.default_rng(n).random(n) + values = bt.draw_uk_firm_open_band_turnover(uniforms, alpha, cap, lower) + assert np.all((values >= lower) & (values <= cap)) + assert values.mean() == pytest.approx( + bt._truncated_pareto_mean(alpha, lower, cap), rel=1e-9 + ) + over = np.mean(values > bt.HMRC_TOP_BAND_LOWER_K) + implied = bt.truncated_pareto_exceedance( + bt.HMRC_TOP_BAND_LOWER_K, alpha, lower, cap + ) + assert abs(over - implied) <= 1.0 / n + 1e-12 + + +def test_tail_draw_uses_only_the_uniforms_ranks() -> None: + uniforms = np.random.default_rng(3).random(1_000) + state = np.random.get_state()[1].copy() + torch_state = torch.get_rng_state().clone() + values = bt.draw_uk_firm_open_band_turnover(uniforms, 0.9, 1e6) + np.testing.assert_array_equal(np.random.get_state()[1], state) + assert torch.equal(torch.get_rng_state(), torch_state) + np.testing.assert_array_equal( + bt.draw_uk_firm_open_band_turnover(uniforms**3, 0.9, 1e6), values + ) + assert np.all(np.diff(values[np.argsort(uniforms)]) > 0) + + +def test_tail_draw_strata_have_exact_means() -> None: + uniforms = np.random.default_rng(0).random(301) + strata = np.arange(301) % 3 == 0 + values = bt.draw_uk_firm_open_band_turnover(uniforms, 0.8, 1e6, strata=strata) + mean = bt._truncated_pareto_mean(0.8, 5_000.0, 1e6) + for flag in (True, False): + assert values[strata == flag].mean() == pytest.approx(mean, rel=1e-9) + + +def test_open_band_uniforms_invert_log_uniform_draw() -> None: + unit = np.linspace(0.0, 0.999, 50) + drawn = 5_000.0 * 10.0**unit + np.testing.assert_allclose(bt.uk_firm_open_band_uniforms(drawn), unit, atol=1e-12) + + +def _fixture_tail_inputs(): + data = _firm_data() + rng = np.random.default_rng(0) + sic = np.array([10, 47, 64, 10, 47, 64, 10, 10]) + turnover = np.array([20.0, 300.0, 4_000.0, 6_000.0, 9_000.0, 7_000.0, 0.0, 1e3]) + in_frame = np.array([True] * 6 + [False, True]) + open_band = turnover >= 5_000.0 + weights = rng.uniform(1_000.0, 5_000.0, sic.size) + return data, sic, turnover, in_frame, open_band, weights + + +def test_tail_parameters_follow_fixture_arithmetic() -> None: + data, sic, turnover, in_frame, open_band, weights = _fixture_tail_inputs() + hmrc = fg._hmrc_band_targets_for_vintage(data.hmrc_population_band, "2024-25") + tail = bt.uk_firm_open_band_tail_parameters( + data.ons_turnover, + hmrc, + _bpe(), + sic=sic, + turnover_k=turnover, + in_frame=in_frame, + open_band=open_band, + weights=weights, + ) + ons = pd.read_csv(FIRM / "ons_firm_turnover.csv") + ons_open = float(ons.loc[ons["SIC Code"].notna(), "5000+"].sum()) + assert ons_open == float(ons.loc[ons["Description"] == "Total", "5000+"].iloc[0]) + hmrc_csv = pd.read_csv(FIRM / "hmrc_vat_population_by_turnover_band.csv") + hmrc_top = float(hmrc_csv["Greater_than_£10m"].iloc[0]) + p = hmrc_top / ons_open + assert tail.p_over_10m == pytest.approx(p) + assert tail.alpha == pytest.approx(-math.log(p) / math.log(2.0)) + size = pd.read_csv(BPE / "bpe_size_bands.csv") + whole = size.query( + "table == 'Table 2' and sector == 'whole_economy' and size_band == 'All'" + )["turnover_million"].iloc[0] + unreg = size.query( + "table == 'Table 1' and size_band == 'With no employees (unregistered)'" + )["turnover_million"].iloc[0] + non_k = in_frame & ~np.isin(sic, [64, 65, 66]) + closed = (turnover * weights)[non_k & ~open_band].sum() + firms = weights[non_k & open_band].sum() + target = ((whole - unreg) * 1_000.0 - closed) / firms + assert tail.target_mean_k == pytest.approx(target) + assert bt._truncated_pareto_mean( + tail.alpha, tail.lower_k, tail.cap_k + ) == pytest.approx(target, rel=1e-10) + assert tail.model_p_over_10m == pytest.approx( + bt.truncated_pareto_exceedance(10_000.0, tail.alpha, 5_000.0, tail.cap_k) + ) + assert tail.model_p_over_10m < tail.p_over_10m + + +def test_tail_parameters_reject_unreachable_mean() -> None: + data, sic, turnover, in_frame, open_band, weights = _fixture_tail_inputs() + hmrc = {"Greater_than_£10m": 1.0} # p tiny -> alpha above one + with pytest.raises(ValueError, match="beyond any cap"): + bt.uk_firm_open_band_tail_parameters( + data.ons_turnover, + hmrc, + _bpe(), + sic=sic, + turnover_k=turnover, + in_frame=in_frame, + open_band=open_band, + weights=weights, + ) + + +# -- D. pins and BPE target ------------------------------------------------------ + + +def test_bpe_band_target_and_pins_equal_fixture_arithmetic() -> None: + size = pd.read_csv(BPE / "bpe_size_bands.csv") + whole = size[(size["table"] == "Table 2") & (size["sector"] == "whole_economy")] + turnover = whole.set_index("size_band")["turnover_million"] + unreg = float( + size.loc[ + size["size_band"] == "With no employees (unregistered)", "turnover_million" + ].iloc[0] + ) + expected = [ + turnover["Zero or 1 employee"] + turnover["2 to 4"] - unreg, + turnover["5 to 9"], + turnover["10 to 19"], + turnover["20 to 49"], + turnover["50 to 99"], + turnover["100 to 199"] + turnover["200 to 249"], + turnover["250 to 499"] + turnover["500 to 999"] + turnover["1000 or more"], + ] + table = bt.uk_firm_bpe_turnover_by_band(_bpe()) + np.testing.assert_allclose(table["bpe_turnover_million"], expected) + # The bands cover the whole-economy total up to BPE rounding. + assert sum(expected) + unreg == pytest.approx(turnover["All"], abs=5.0) + data = _firm_data() + pins = bt.uk_firm_bpe_turnover_pins(_bpe(), data.ons_turnover, data.hmrc_bands) + assert pins["bpe_whole_economy_turnover"]["value"] == turnover["All"] + assert pins["bpe_unregistered_turnover"]["value"] == unreg + for band, value in zip(bt.UK_FIRM_TURNOVER_EMPLOYMENT_BANDS, expected, strict=True): + assert pins[f"bpe_registered_turnover_{band}"]["value"] == value + ons = pd.read_csv(FIRM / "ons_firm_turnover.csv") + hmrc_csv = pd.read_csv(FIRM / "hmrc_vat_population_by_turnover_band.csv") + assert pins["ons_open_band_enterprises"]["value"] == float( + ons.loc[ons["SIC Code"].notna(), "5000+"].sum() + ) + assert pins["hmrc_over_10m_traders"]["value"] == float( + hmrc_csv["Greater_than_£10m"].iloc[-1] + ) + assert all(pin["source"] for pin in pins.values()) + + +def test_status_and_method_are_labelled() -> None: + assert bt.UK_FIRM_BPE_TURNOVER_STATUS == "assumed" + assert "Business population estimates 2025" in bt.UK_FIRM_BPE_TURNOVER_METHOD + assert "BPE_2025_detailed_tables.xlsx" in bt.__doc__ 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..41109a6c67 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_build.py @@ -0,0 +1,889 @@ +"""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_employment_allowance import ( + UK_FIRM_EMPLOYMENT_ALLOWANCE_COLUMNS, + UK_FIRM_EMPLOYMENT_ALLOWANCE_METHOD, + uk_firm_employment_allowance_flags, +) +from microcosm.build.uk_runtime.firm_generation import ( + LARGE_EMPLOYMENT_CAP, + LARGE_EMPLOYMENT_MEAN, + ONS_EMPLOYMENT_BANDS, + UKFirmGenerationConfig, +) +from microcosm.build.uk_runtime.firm_paybill import ( + UK_FIRM_PAYBILL_METHOD, + UK_FIRM_PAYBILL_STATUS, + UK_FIRM_PAYBILL_TAX_YEAR, +) +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, + UK_FIRM_PAYBILL_TABLE_COLUMNS, + uk_firm_table_columns, + validate_uk_firm_table, +) +from test_support.paths import paths_for + +PATHS = paths_for("microcosm-build") +FIXTURES = PATHS.tests / "fixtures" / "uk" +PROCESSED = FIXTURES / "firm_2024_25" +ATTRIBUTES = FIXTURES / "firm_attributes_2025" +PAYBILL = FIXTURES / "firm_paybill_2024" +SIZE = FIXTURES / "firm_2024_25_size" +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, + paybill_dir: Path | None = None, + employment_allowance: bool = False, + **sources: Path, +) -> dict: + rules = _StandardRateDouble() + return build_uk_firm_dataset( + processed_dir=PROCESSED, + attributes_dir=ATTRIBUTES, + output_dir=output_dir, + rules=rules, + config=_config(rules), + paybill_dir=paybill_dir, + employment_allowance=employment_allowance, + **sources, + ) + + +@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"} + # Without a paybill source nothing paybill-shaped is written. + assert receipt["output"]["columns"] == list(UK_FIRM_EXTENDED_TABLE_COLUMNS) + assert "paybill" not in receipt["inputs"] + assert "weighted_paybill_gbp" not in receipt["output"] + assert "uk_firm_paybill_fallback_counts" not in receipt + assert "uk_firm_paybill" not in receipt + assert "uk_firm_paybill_in_frame" not in receipt + + +def test_paybill_build_sets_firm_paybill_and_records_its_source( + builds, tmp_path: Path +) -> None: + built = _build(tmp_path / "paybill", paybill_dir=PAYBILL) + table = built["table"] + receipt = json.loads(built["receipt_path"].read_text(encoding="utf-8")) + base = builds[0]["table"] + + assert tuple(table.columns) == UK_FIRM_PAYBILL_TABLE_COLUMNS + validate_uk_firm_table(pd.read_parquet(built["table_path"])) + # The paybill adds a column and changes nothing else. + pd.testing.assert_frame_equal(table[list(UK_FIRM_EXTENDED_TABLE_COLUMNS)], base) + assert receipt["inputs"]["paybill"] == { + "ashe_section_annual_pay.csv": _sha256(PAYBILL / "ashe_section_annual_pay.csv") + } + weighted = float((table["firm_weight"] * table["firm_paybill"]).sum()) + assert receipt["output"]["weighted_paybill_gbp"] == pytest.approx(weighted) + levels = {row["level"]: row for row in receipt["uk_firm_paybill_fallback_counts"]} + assert set(levels) == {"section", "all_employees"} + assert sum(row["firms"] for row in levels.values()) == len(table) + assert sum(row["weighted_paybill_gbp"] for row in levels.values()) == pytest.approx( + weighted + ) + assert receipt["uk_firm_paybill"] == { + "status": UK_FIRM_PAYBILL_STATUS, + "method": UK_FIRM_PAYBILL_METHOD, + "tax_year": UK_FIRM_PAYBILL_TAX_YEAR, + } + assert receipt["uk_firm_paybill"]["status"] == "assumed" + split = {row["in_frame"]: row for row in receipt["uk_firm_paybill_in_frame"]} + assert set(split) == {True, False} + for flag, row in split.items(): + rows = table[table["in_frame"] == flag] + assert row["weighted_paybill_gbp"] == pytest.approx( + float((rows["firm_weight"] * rows["firm_paybill"]).sum()) + ) + assert row["weighted_employees"] == pytest.approx( + float((rows["firm_weight"] * rows["firm_employees"]).sum()) + ) + assert sum(row["weighted_paybill_gbp"] for row in split.values()) == pytest.approx( + weighted + ) + assert str(PAYBILL) not in built["receipt_path"].read_text(encoding="utf-8") + + +def _dbt_large_firms() -> pd.DataFrame: + return pd.read_csv(SIZE / "dbt_bpe_private_250plus.csv") + + +def test_dbt_large_firm_fixture_matches_its_provenance_and_the_mean() -> None: + provenance = json.loads((SIZE / ".provenance.json").read_text(encoding="utf-8")) + record = provenance["files"]["dbt_bpe_private_250plus.csv"] + assert _sha256(SIZE / "dbt_bpe_private_250plus.csv") == record["sha256"] + assert provenance["source"]["access_date"] == "2026-11-22" + assert len(provenance["source"]["sha256"]) == 64 + large = _dbt_large_firms() + assert int(large["businesses"].sum()) == 8_250 + mean = ( + 1_000.0 + * float(large["employment_thousand"].sum()) + / float(large["businesses"].sum()) + ) + assert LARGE_EMPLOYMENT_MEAN == pytest.approx(mean) + + +def test_large_firm_employment_matches_the_dbt_mean_without_a_clamp( + builds, tmp_path: Path +) -> None: + """With the DBT mean set, the in-frame 250+ band's weighted mean + headcount is DBT's within 15% and no clamp at 2,000 remains. Out-of-frame + rows draw below 250, which can move their legal status (drawn jointly + with the employment band); every other column, and every headcount the + default build draws below 250, matches the default build.""" + + rules = _StandardRateDouble() + built = build_uk_firm_dataset( + processed_dir=PROCESSED, + attributes_dir=ATTRIBUTES, + output_dir=tmp_path / "out", + rules=rules, + config=dataclasses.replace( + _config(rules), large_employment_mean=LARGE_EMPLOYMENT_MEAN + ), + ) + table = built["table"] + base = builds[0]["table"] + in_frame = base["in_frame"].to_numpy(bool) + np.testing.assert_array_equal(table["in_frame"].to_numpy(bool), in_frame) + band_dependent = [ + "firm_employees", + "firm_legal_form", + "firm_is_public_body", + "firm_is_charity", + "ons_legal_status", + ] + pd.testing.assert_frame_equal( + table.drop(columns=band_dependent), base.drop(columns=band_dependent) + ) + pd.testing.assert_frame_equal( + table.loc[in_frame, band_dependent[1:]], base.loc[in_frame, band_dependent[1:]] + ) + legacy = base["firm_employees"].to_numpy(dtype=np.float64) + assert legacy.max() <= 2_000 + employees = table["firm_employees"].to_numpy(dtype=np.float64) + weights = table["firm_weight"].to_numpy(dtype=np.float64) + large = employees >= 250 + np.testing.assert_array_equal(large, (legacy >= 250) & in_frame) + assert not large[~in_frame].any() + below = legacy < 250 + np.testing.assert_array_equal(employees[below], legacy[below]) + weighted_mean = float((weights * employees)[large].sum() / weights[large].sum()) + assert weighted_mean == pytest.approx(LARGE_EMPLOYMENT_MEAN, rel=0.15) + # The default clamps the band to [250, 2000]; no clamp at 2000 remains. + assert ONS_EMPLOYMENT_BANDS["250+"][1] == 2_000 < LARGE_EMPLOYMENT_CAP + assert employees.max() > 2_000 + assert employees.max() <= LARGE_EMPLOYMENT_CAP + assert float((employees == 2_000).sum()) < 0.01 * float(large.sum()) + + +def test_paybill_build_refuses_another_vintage(tmp_path: Path) -> None: + """The ASHE 2025 table is tax year 2024-25; another vintage is refused + before anything is generated or written.""" + + rules = _StandardRateDouble() + config = _config(rules).with_vintage("2023-24") + with pytest.raises(ValueError, match="tax year 2024-25"): + build_uk_firm_dataset( + processed_dir=PROCESSED, + attributes_dir=ATTRIBUTES, + output_dir=tmp_path / "out", + rules=rules, + config=config, + paybill_dir=PAYBILL, + ) + assert not (tmp_path / "out").exists() + + +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_employment_allowance_build_adds_only_the_assumed_flags( + builds, tmp_path: Path +) -> None: + built = _build(tmp_path / "allowance", employment_allowance=True) + table = built["table"] + receipt = json.loads(built["receipt_path"].read_text(encoding="utf-8")) + base = builds[0]["table"] + + assert tuple(table.columns) == uk_firm_table_columns( + ["attributes", "employment_allowance"] + ) + validate_uk_firm_table(pd.read_parquet(built["table_path"])) + # The flags read no random numbers: every other column is unchanged. + pd.testing.assert_frame_equal(table[list(UK_FIRM_EXTENDED_TABLE_COLUMNS)], base) + flags = uk_firm_employment_allowance_flags( + table["ons_legal_status"].to_numpy(), table["firm_employees"].to_numpy() + ) + for column, values in flags.items(): + assert table[column].to_numpy(bool).tolist() == values.tolist() + record = receipt["uk_firm_employment_allowance"] + assert record["status"] == "assumed" + assert record["method"] == UK_FIRM_EMPLOYMENT_ALLOWANCE_METHOD + weight = table["firm_weight"].to_numpy(float) + for column in UK_FIRM_EMPLOYMENT_ALLOWANCE_COLUMNS: + assert record["weighted_firms_where_true"][column] == pytest.approx( + float(weight[table[column].to_numpy(bool)].sum()) + ) + assert "uk_firm_employment_allowance" not in builds[0]["receipt"] + + +def test_full_opt_in_build_adds_the_assumed_inputs(builds, tmp_path: Path) -> None: + """Every opt-in source at once: public sector headcounts change only + central government and local authority rows, and profit and rateable + value add one column each.""" + + rules = _StandardRateDouble() + built = build_uk_firm_dataset( + processed_dir=PROCESSED, + attributes_dir=ATTRIBUTES, + output_dir=tmp_path / "out", + rules=rules, + config=_config(rules), + paybill_dir=PAYBILL, + employment_allowance=True, + public_sector_dir=FIXTURES / "firm_public_sector_2025", + profit_dir=FIXTURES / "firm_ct_2024", + rateable_value_dir=FIXTURES / "firm_rateable_value_2024", + pay_distribution_dir=FIXTURES / "firm_pay_distribution_2024", + ) + table = built["table"] + receipt = built["receipt"] + for key in ( + "ashe_paybill", + "ons_public_sector_employment", + "ashe_pay_distribution", + "hmrc_ct_statistics", + "voa_rating_list", + ): + assert receipt["data_years"][key] == UK_FIRM_INPUT_DATA_YEARS[key] + base = builds[0]["table"] + assert tuple(table.columns) == uk_firm_table_columns( + [ + "attributes", + "paybill", + "employment_allowance", + "pay_distribution", + "profit", + "rateable_value", + ] + ) + validate_uk_firm_table(pd.read_parquet(built["table_path"])) + public = base["ons_legal_status"].isin([5, 6]).to_numpy() + pd.testing.assert_frame_equal( + table.loc[~public, list(base.columns)], base.loc[~public] + ) + pd.testing.assert_frame_equal( + table.loc[public, list(base.columns)].drop(columns="firm_employees"), + base.loc[public].drop(columns="firm_employees"), + ) + weight = table["firm_weight"].to_numpy(float) + for status, sector in ((5, "central_government"), (6, "local_government")): + rows = table["ons_legal_status"].to_numpy() == status + record = next( + row + for row in receipt["uk_firm_public_sector"]["sectors"].values() + if row["ons_legal_status"] == status + ) + assert float((weight * table["firm_employees"])[rows].sum()) == ( + pytest.approx(record["target_weighted_employment"], rel=1e-3) + ), sector + profit = table["firm_taxable_trading_profit"].to_numpy(float) + assert profit.max() > 0 + assert not profit[table["ons_legal_status"].to_numpy() != 1].any() + assert receipt["uk_firm_profit"]["status"] == "assumed" + assert receipt["uk_firm_profit"]["weighted_profit_gbp"] == pytest.approx( + float((weight * profit).sum()) + ) + value = table["firm_rateable_value"].to_numpy(float) + assert value.max() > 0 + assert not value[~table["firm_in_england"].to_numpy(bool)].any() + assert receipt["uk_firm_rateable_value"]["status"] == "assumed" + below = table["firm_employees_below_secondary_threshold"].to_numpy() + assert 0 < below.sum() and (below <= table["firm_employees"].to_numpy()).all() + assert receipt["uk_firm_pay_distribution"]["threshold_gbp"] == 9_100.0 + for role in ("public_sector", "profit", "rateable_value", "pay_distribution"): + assert len(receipt["inputs"][role]) == 1 + for key in ("uk_firm_public_sector", "uk_firm_profit", "uk_firm_rateable_value"): + assert key not in builds[0]["receipt"] + + +def test_labour_link_build_sets_employees_and_draws_allowance_takeup( + builds, tmp_path: Path +) -> None: + """BPE redraws only 0-4 band headcounts of statuses 1-3; firm_employees + drops the assumed working proprietors; the take-up draw stays within the + rule flag.""" + + rules = _StandardRateDouble() + built = build_uk_firm_dataset( + processed_dir=PROCESSED, + attributes_dir=ATTRIBUTES, + output_dir=tmp_path / "out", + rules=rules, + config=_config(rules), + paybill_dir=PAYBILL, + employment_allowance=True, + bpe_dir=FIXTURES / "firm_bpe_2025", + employment_allowance_takeup_dir=FIXTURES + / "firm_employment_allowance_takeup_2024_25", + ) + table = built["table"] + receipt = built["receipt"] + assert receipt["data_years"]["dbt_bpe"] == "start of 2025" + assert receipt["data_years"]["hmrc_employment_allowance_takeup"] == "2024-25" + base = builds[0]["table"] + assert tuple(table.columns) == uk_firm_table_columns( + [ + "attributes", + "paybill", + "employment_allowance", + "sic_division", + "labour_link", + "employment_allowance_takeup", + ] + ) + validate_uk_firm_table(pd.read_parquet(built["table_path"])) + pd.testing.assert_series_equal(table["firm_id"], base["firm_id"]) + before = base["firm_employees"].to_numpy() + after = table["ons_employment"].to_numpy() + status = table["ons_legal_status"].to_numpy() + changed = before != after + assert changed.any() + small = (before >= 1) & (before <= 4) & np.isin(status, [1, 2, 3]) + assert not changed[~small].any() + assert ((after[small] >= 1) & (after[small] <= 4)).all() + employees = table["firm_employees"].to_numpy() + assert (employees <= after).all() + assert (employees[status == 1] == after[status == 1]).all() + assert (employees[status == 2] == after[status == 2] - 1).all() + claims = table["firm_claims_employment_allowance"].to_numpy(bool) + rule = table["firm_employment_allowance_rule_claims"].to_numpy(bool) + assert not (claims & ~rule).any() + assert receipt["uk_firm_headcount"]["status"] == "assumed" + assert receipt["uk_firm_employment_allowance_takeup"]["status"] == "assumed" + for key in ("uk_firm_headcount", "uk_firm_employment_allowance_takeup"): + assert key not in builds[0]["receipt"] + + +def test_consumption_build_splits_turnover_only(builds, tmp_path: Path) -> None: + built = _build( + tmp_path / "consumption", consumption_dir=FIXTURES / "firm_supply_use_2024" + ) + table = built["table"] + base = builds[0]["table"] + assert tuple(table.columns) == uk_firm_table_columns( + ["attributes", "sic_division", "consumption"] + ) + validate_uk_firm_table(pd.read_parquet(built["table_path"])) + assert built["receipt"]["data_years"]["ons_supply_use"] == "2024" + pd.testing.assert_frame_equal(table[list(base.columns)], base) + parts = table[ + ["firm_household_sales", "firm_intermediate_sales", "firm_other_final_sales"] + ].sum(axis=1) + np.testing.assert_allclose(parts, table["firm_turnover"], rtol=1e-9) + assert (table["firm_household_sales"] > 0).any() + record = built["receipt"]["uk_firm_consumption"] + assert record["status"] == "assumed" + assert all( + abs(row["difference"]) <= 0.5 for row in record["table3_consumer_trends"] + ) + shares = pd.read_csv( + built["table_path"].parent / record["division_coicop_shares_file"], + index_col="sic_division", + ) + coicop = [f"{k:02d}" for k in range(1, 13)] + np.testing.assert_allclose(shares[coicop].sum(axis=1), 1.0, rtol=1e-9) + assert set(table["firm_sic_division"]) <= set(shares.index) + split = record["household_purchases_by_supply_gbp_million"] + assert split["domestic_basic"] > split["imports"] > 0 + assert "uk_firm_consumption" not in builds[0]["receipt"] + + +def test_vat_composition_build_adds_share_columns_only(builds, tmp_path: Path) -> None: + consumption = _build( + tmp_path / "consumption", consumption_dir=FIXTURES / "firm_supply_use_2024" + )["table"] + built = _build( + tmp_path / "vat", + consumption_dir=FIXTURES / "firm_supply_use_2024", + vat_composition_dir=FIXTURES / "firm_vat_composition_2024", + ) + table = built["table"] + assert tuple(table.columns) == uk_firm_table_columns( + ["attributes", "sic_division", "consumption", "vat_composition"] + ) + validate_uk_firm_table(pd.read_parquet(built["table_path"])) + # Columns only: every column the build had without the group, weights and + # scored VAT inputs included, is unchanged. + pd.testing.assert_frame_equal(table[list(consumption.columns)], consumption) + shares = table[ + [ + "firm_sut_standard_rated_share", + "firm_sut_reduced_rated_share", + "firm_sut_zero_rated_share", + "firm_sut_exempt_share", + ] + ].sum(axis=1) + np.testing.assert_allclose(shares, 1.0, atol=1e-9) + record = built["receipt"]["uk_firm_vat_composition"] + assert record["status"] == "assumed" and record["mode"] == "columns_only" + assert {row["relief"] for row in record["relief_checks"]} >= {"NS7 food (zero)"} + assert built["receipt"]["data_years"]["ons_abs"] == "2024" + assert "uk_firm_vat_composition" not in builds[0]["receipt"] + + +def test_vat_composition_needs_consumption_and_anchor_needs_paybill( + tmp_path: Path, +) -> None: + with pytest.raises(ValueError, match="vat_composition_dir needs consumption_dir"): + _build( + tmp_path / "a", vat_composition_dir=FIXTURES / "firm_vat_composition_2024" + ) + with pytest.raises(ValueError, match="paybill_anchor_dir needs paybill_dir"): + _build(tmp_path / "b", paybill_anchor_dir=FIXTURES / "firm_paybill_anchor_2024") + + +def test_paybill_anchor_is_reported_only(builds, tmp_path: Path) -> None: + paybill = FIXTURES / "firm_paybill_2024" + plain = _build(tmp_path / "plain", paybill_dir=paybill) + built = _build( + tmp_path / "anchor", + paybill_dir=paybill, + paybill_anchor_dir=FIXTURES / "firm_paybill_anchor_2024", + ) + pd.testing.assert_frame_equal(built["table"], plain["table"]) + record = built["receipt"]["uk_firm_paybill_anchor"] + assert record["status"] == "report_only" + weight = built["table"]["firm_weight"].to_numpy() + paybill_total = float((built["table"]["firm_paybill"].to_numpy() * weight).sum()) + assert record["paybill_over_ons_d11"] == pytest.approx(paybill_total / 1_162_752e6) + + +def test_mid_headcount_and_out_of_frame_switches(builds, tmp_path: Path) -> None: + built = _build( + tmp_path / "mid", + paybill_dir=PAYBILL, + bpe_dir=FIXTURES / "firm_bpe_2025", + bpe_mid_headcount=True, + out_of_frame_no_employees=True, + ) + table = built["table"] + base = builds[0]["table"] + validate_uk_firm_table(pd.read_parquet(built["table_path"])) + before = base["firm_employees"].to_numpy() + after = table["ons_employment"].to_numpy() + outside = ~table["in_frame"].to_numpy(bool) + assert (after[outside] == 0).all() + status = table["ons_legal_status"].to_numpy() + mid = (before >= 5) & (before <= 249) & np.isin(status, [1, 2, 3, 4]) & ~outside + edges = [5, 10, 20, 50, 100, 250] + assert ( + np.searchsorted(edges, before[mid], side="right") + == np.searchsorted(edges, after[mid], side="right") + ).all() + assert (after[mid] != before[mid]).any() + record = built["receipt"]["uk_firm_headcount"] + assert record["mid_band_remap"]["weighted_rows_changed"] > 0 + assert record["out_of_frame_employment_removed"] > 0 + + +def test_bpe_turnover_lifts_the_cap_and_pairs_turnover_with_employment( + builds, tmp_path: Path +) -> None: + """The thinned test build keeps different rows once turnover changes, so + only properties are compared, not rows.""" + + built = _build( + tmp_path / "bpe_turnover", + paybill_dir=PAYBILL, + bpe_dir=FIXTURES / "firm_bpe_2025", + bpe_turnover=True, + ) + table = built["table"] + base = builds[0]["table"] + validate_uk_firm_table(pd.read_parquet(built["table_path"])) + assert base["firm_turnover"].max() < 50e6 + assert table["firm_turnover"].max() > 50e6 + record = built["receipt"]["uk_firm_headcount"]["bpe_turnover"] + assert 0.0 < record["rho"] < 1.0 + assert record["cap_k"] > 50_000 + + def corr(frame_table: pd.DataFrame, headcount: str) -> float: + rows = frame_table[ + frame_table["in_frame"].to_numpy(bool) & (frame_table["firm_turnover"] > 0) + ] + return float( + np.corrcoef(np.log1p(rows["firm_turnover"]), np.log1p(rows[headcount]))[ + 0, 1 + ] + ) + + assert corr(table, "ons_employment") > corr(base, "firm_employees") + 0.2 + assert "bpe_turnover" not in builds[0]["receipt"]["config"] + assert "bpe_turnover" in built["receipt"]["config"] + + +def test_rd_tax_credits_and_large_headcount_build(builds, tmp_path: Path) -> None: + built = _build( + tmp_path / "rd", + paybill_dir=PAYBILL, + bpe_dir=FIXTURES / "firm_bpe_2025", + bpe_large_headcount=True, + rd_tax_credits_dir=FIXTURES / "firm_rd_tax_credits_2024_25", + ) + table = built["table"] + base = builds[0]["table"] + validate_uk_firm_table(pd.read_parquet(built["table_path"])) + spend = table["firm_qualifying_rd_expenditure"].to_numpy() + assert spend.max() > 0 + assert not spend[table["ons_legal_status"].to_numpy() != 1].any() + assert (spend <= table["firm_turnover"].to_numpy()).all() + receipt = built["receipt"] + assert receipt["uk_firm_rd_tax_credits"]["status"] == "assumed" + assert receipt["data_years"]["hmrc_rd_statistics"] == "2024-25" + large = receipt["uk_firm_headcount"]["large_band_remap"] + assert large["weighted_employment_after"] > large["weighted_employment_before"] + before = base["firm_employees"].to_numpy() + after = table["ons_employment"].to_numpy() + assert ((after >= 250) == (before >= 250)).all() + assert "uk_firm_rd_tax_credits" not in builds[0]["receipt"] + + +def test_labour_link_sources_need_their_prerequisites(tmp_path: Path) -> None: + rules = _StandardRateDouble() + with pytest.raises(ValueError, match="bpe_dir needs paybill_dir"): + build_uk_firm_dataset( + processed_dir=PROCESSED, + attributes_dir=ATTRIBUTES, + output_dir=tmp_path / "out", + rules=rules, + config=_config(rules), + bpe_dir=FIXTURES / "firm_bpe_2025", + ) + with pytest.raises(ValueError, match="needs bpe_dir and employment_allowance"): + build_uk_firm_dataset( + processed_dir=PROCESSED, + attributes_dir=ATTRIBUTES, + output_dir=tmp_path / "out", + rules=rules, + config=_config(rules), + paybill_dir=PAYBILL, + bpe_dir=FIXTURES / "firm_bpe_2025", + employment_allowance_takeup_dir=FIXTURES + / "firm_employment_allowance_takeup_2024_25", + ) + assert not (tmp_path / "out").exists() + + +@pytest.mark.parametrize( + ("argument", "fixture"), + [ + ("bpe_dir", "firm_bpe_2025"), + ("consumption_dir", "firm_supply_use_2024"), + ("paybill_anchor_dir", "firm_paybill_anchor_2024"), + ("vat_composition_dir", "firm_vat_composition_2024"), + ("rd_tax_credits_dir", "firm_rd_tax_credits_2024_25"), + ("employment_allowance_takeup_dir", "firm_employment_allowance_takeup_2024_25"), + ("public_sector_dir", "firm_public_sector_2025"), + ("profit_dir", "firm_ct_2024"), + ("rateable_value_dir", "firm_rateable_value_2024"), + ("pay_distribution_dir", "firm_pay_distribution_2024"), + ], +) +def test_opt_in_sources_refuse_another_vintage( + argument: str, fixture: str, tmp_path: Path +) -> None: + rules = _StandardRateDouble() + with pytest.raises(ValueError, match="tax year 2024-25"): + build_uk_firm_dataset( + processed_dir=PROCESSED, + attributes_dir=ATTRIBUTES, + output_dir=tmp_path / "out", + rules=rules, + config=_config(rules).with_vintage("2023-24"), + **{argument: FIXTURES / fixture}, + ) + assert not (tmp_path / "out").exists() + + +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, "dbt_bpe": False}) == { + "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_capex_fixture.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_capex_fixture.py new file mode 100644 index 0000000000..238be73182 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_capex_fixture.py @@ -0,0 +1,29 @@ +"""UK business capex fixture (fixture only; no build reads it).""" + +from __future__ import annotations + +import hashlib +import json + +import pandas as pd + +from test_support.paths import paths_for + +FIXTURE = paths_for("microcosm-build").tests / "fixtures" / "uk" / "firm_capex_2024" + + +def test_capex_fixture_is_pinned_and_adds_up(): + provenance = json.loads((FIXTURE / "provenance.json").read_text()) + for name, meta in provenance["files"].items(): + assert ( + hashlib.sha256((FIXTURE / name).read_bytes()).hexdigest() == meta["sha256"] + ) + bi = pd.read_csv(FIXTURE / "business_investment_by_asset.csv").set_index( + "series_id" + ) + assert bi.loc["NPEK", "value_gbp_million"] == 309068 + assert bi.drop(index="NPEK")["value_gbp_million"].sum() == 309068 + abs_capex = pd.read_csv(FIXTURE / "abs_capex_by_section.csv").set_index( + "sic_section" + ) + assert abs_capex.loc["A-S (part)", "acquisitions_gbp_million"] == 243900 diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_consumption.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_consumption.py new file mode 100644 index 0000000000..29ffeb37da --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_consumption.py @@ -0,0 +1,291 @@ +"""UK firm consumption links from the ONS Supply and Use Tables 2024.""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import sys +from functools import cache + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.uk_runtime.firm_consumption import ( + UK_COICOP_DIVISIONS, + UK_FIRM_CONSUMPTION_COLUMNS, + UK_FIRM_CONSUMPTION_STATUS, + UK_FIRM_SUT_FILES, + UK_FIRM_TABLE3_GATE_TOLERANCE_GBP_MILLION, + UK_FIRM_TRADE_DIVISIONS, + UKFirmSupplyUseSource, + check_uk_table3_consumer_trends, + read_uk_firm_supply_use_source, + uk_firm_consumption_sales, + uk_firm_division_coicop_shares, + uk_firm_division_use_shares, + uk_firm_household_sales_by_coicop, + uk_household_purchases_supply_decomposition, + uk_table3_consumer_trends_comparison, +) +from test_support.paths import paths_for + +PATHS = paths_for("microcosm-build") +FIXTURE = PATHS.tests / "fixtures" / "uk" / "firm_supply_use_2024" +PROVENANCE = FIXTURE / "firm_supply_use_2024.provenance.json" +TOOL = PATHS.repository / "tools" / "extract_uk_firm_supply_use_tables.py" +SHARES = ("household_share", "intermediate_share", "other_final_share") + + +@cache +def _source() -> UKFirmSupplyUseSource: + return read_uk_firm_supply_use_source(FIXTURE) + + +@cache +def _uses() -> pd.DataFrame: + return uk_firm_division_use_shares(_source()) + + +@cache +def _provenance() -> dict: + return json.loads(PROVENANCE.read_text(encoding="utf-8")) + + +@cache +def _load_tool(): + name = "extract_uk_firm_supply_use_tables" + 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 test_fixture_hashes_match_provenance(): + record = _provenance() + assert record["source"]["sha256"] == _load_tool().XLSX_SHA256 + assert "October 2026" in record["source"]["edition"] + assert record["accessed"] == "2026-11-22" + for name in UK_FIRM_SUT_FILES: + payload = (FIXTURE / name).read_bytes() + digest = hashlib.sha256(payload).hexdigest() + assert record["files"][name]["sha256"] == digest + assert _source().sha256[name] == digest + + +def test_fixture_shape_and_identities(): + uses = _source().uses + assert len(uses) == 103 + # Supply side adds up to total supply, which equals total demand. + supply = uses[ + ["domestic_output", "imports", "distributors_margins", "taxes_less_subsidies"] + ].sum(axis=1) + assert np.array_equal(supply, uses["total_supply"]) + assert np.array_equal(uses["total_supply"], uses["total_demand"]) + assert uses["distributors_margins"].sum() == 0 + # Table 2 households is the national concept: 1,708,930 million pounds. + assert uses["households"].sum() == 1_708_930 + # Table 3 classes (domestic concept) total 1,692,413 million pounds. + assert _source().hhfce["value_gbp_million"].sum() == 1_692_413 + + +def test_trade_margins_are_negative_only_on_trade_products(): + uses = _source().uses + negative = uses.index[uses["distributors_margins"] < 0].tolist() + assert negative == ["CPA_G45", "CPA_G46", "CPA_G47"] + assert uses.loc["CPA_G47", "total_demand"] == 0 + + +def test_product_division_parse(): + divisions = _source().divisions + of = divisions.groupby("product_code")["sic_division"].apply(list) + assert of["CPA_C102_3"] == [10] + assert of["CPA_B05 & B06"] == [5, 6] + assert of["CPA_C11.01-6 & C12"] == [11, 12] + assert of["CPA_F41, F42 & F43"] == [41, 42, 43] + assert of["CPA_K65.1-2 & K65.3"] == [65] + assert of["CPA_L68A"] == [68] + assert 98 not in set(divisions["sic_division"]) + + +def test_shares_in_unit_interval_and_sum_to_one(): + shares = _uses()[list(SHARES)] + assert ((shares >= 0) & (shares <= 1)).all().all() + assert np.allclose(shares.sum(axis=1), 1.0, rtol=0, atol=1e-12) + + +def test_aggregation_sums_numerators_and_denominators(): + uses = _source().uses + products = [f"CPA_C10{k}" for k in (1, 4, 5, 6, 7, 8, 9)] + ["CPA_C102_3"] + rows = uses.loc[products] + floored = rows.drop(columns=["product_label", "total_demand"]).iloc[:, :9] + denominator = floored.clip(lower=0).sum().sum() + expected = rows["households"].sum() / denominator + assert _uses().loc[10, "household_share"] == pytest.approx(expected, rel=1e-12) + mean_of_shares = (rows["households"] / rows["total_demand"]).mean() + assert _uses().loc[10, "household_share"] != pytest.approx(mean_of_shares) + + +def test_imputed_rent_left_out_of_division_68(): + uses = _source().uses + kept = uses.loc[["CPA_L68BXL683", "CPA_L683"]] + assert _uses().loc[68, "total_demand_gbp_million"] == kept["total_demand"].sum() + + +def test_trade_divisions_are_margin_weighted(): + uses = _source().uses + goods = uses[uses["distributors_margins"] > 0] + other = goods[ + [ + "npish", + "central_government", + "local_government", + "gfcf", + "valuables", + "exports", + ] + ].sum(axis=1) + goods["changes_in_inventories"].clip(lower=0) + total = goods["households"] + goods["intermediate_consumption"] + other + margin = goods["distributors_margins"] + expected = (margin * goods["households"] / total).sum() / margin.sum() + for division in UK_FIRM_TRADE_DIVISIONS: + row = _uses().loc[division] + assert row["basis"] == "trade_margin" + assert row["household_share"] == pytest.approx(expected, rel=1e-12) + assert row["total_demand_gbp_million"] == pytest.approx(margin.sum()) + + +def test_firm_columns_sum_to_turnover(): + rng = np.random.default_rng(7) + divisions = rng.choice(np.arange(1, 100), size=5000) + turnover = rng.normal(2e6, 5e6, size=5000) + turnover[:10] = 0.0 + result = uk_firm_consumption_sales(divisions, turnover, _source()) + columns = result.columns + assert tuple(columns.columns) == UK_FIRM_CONSUMPTION_COLUMNS + assert result.status == UK_FIRM_CONSUMPTION_STATUS == "assumed" + total = columns.sum(axis=1).to_numpy() + assert np.allclose(total, turnover, rtol=1e-15, atol=1e-6) + assert (columns.iloc[:10] == 0).all().all() + # Positive turnover gives non-negative columns, negative gives non-positive. + assert (columns[turnover > 0] >= -1e-6).all().all() + assert (columns[turnover < 0] <= 1e-6).all().all() + + +def test_firm_columns_use_division_shares(): + result = uk_firm_consumption_sales([56, 47], [100.0, 1000.0], _source()) + assert result.columns.loc[0, "firm_household_sales"] == pytest.approx( + 100.0 * _uses().loc[56, "household_share"] + ) + assert result.columns.loc[1, "firm_intermediate_sales"] == pytest.approx( + 1000.0 * _uses().loc[47, "intermediate_share"] + ) + + +def test_fallbacks_are_counted(): + divisions = [10, "47", 98, 99, 4, 0, None, "x"] + result = uk_firm_consumption_sales(divisions, np.ones(8), _source()) + # 98 takes section T (division 97); 99 (section U, no product), 4 (not a + # SIC division), 0, missing and unreadable take the economy. + assert dict(result.fallback_counts) == {"division": 2, "section": 1, "economy": 5} + assert result.columns.loc[2, "firm_household_sales"] == pytest.approx( + _uses().loc[97, "household_share"] + ) + + +def test_coicop_shares_sum_to_one_per_division(): + shares = uk_firm_division_coicop_shares(_source()) + values = shares[list(UK_COICOP_DIVISIONS)] + assert ((values >= 0) & (values <= 1)).all().all() + assert np.allclose(values.sum(axis=1), 1.0, rtol=0, atol=1e-12) + assert set(shares.index) == set(_uses().index) + assert shares.loc[56, "11"] == pytest.approx(1.0) + assert shares.loc[64, "12"] == pytest.approx(1.0) + for division in UK_FIRM_TRADE_DIVISIONS: + assert shares.loc[division, "basis"] == "trade_margin" + # Divisions without Table 3 household purchases fall back to the section. + assert shares.loc[63, "basis"] == "section" + + +def test_table3_matches_consumer_trends(): + frame = check_uk_table3_consumer_trends(_source()) + assert list(frame.index) == list(UK_COICOP_DIVISIONS) + assert frame["difference"].abs().max() <= UK_FIRM_TABLE3_GATE_TOLERANCE_GBP_MILLION + assert frame.loc["02", "excluded"] == "02.3" + assert frame.loc["04", "excluded"] == "04.2" + assert frame["consumer_trends"].sum() == pytest.approx(1_692_413 - 3_044 - 291_626) + + +def test_household_sales_diagnostic_runs(): + result = uk_firm_consumption_sales([56, 64], [1e9, 2e9], _source()) + frame = uk_firm_household_sales_by_coicop( + [56, 64], result.columns["firm_household_sales"], [1.0, 2.0], _source() + ) + assert frame.loc["11", "firm_household_sales"] == pytest.approx( + 1e3 * _uses().loc[56, "household_share"] + ) + assert frame.loc["12", "firm_household_sales"] == pytest.approx( + 4e3 * _uses().loc[64, "household_share"] + ) + assert frame.loc["01", "firm_household_sales"] == 0 + + +def test_deterministic(): + first = read_uk_firm_supply_use_source(FIXTURE) + pd.testing.assert_frame_equal( + uk_firm_division_use_shares(first), uk_firm_division_use_shares(_source()) + ) + pd.testing.assert_frame_equal( + uk_firm_division_coicop_shares(first), + uk_firm_division_coicop_shares(_source()), + ) + pd.testing.assert_frame_equal( + uk_table3_consumer_trends_comparison(first), + uk_table3_consumer_trends_comparison(_source()), + ) + + +def test_wrong_columns_refused(tmp_path): + for name in UK_FIRM_SUT_FILES: + (tmp_path / name).write_bytes((FIXTURE / name).read_bytes()) + uses = pd.read_csv(tmp_path / UK_FIRM_SUT_FILES[0]) + uses.drop(columns="exports").to_csv(tmp_path / UK_FIRM_SUT_FILES[0], index=False) + with pytest.raises(ValueError, match="columns"): + read_uk_firm_supply_use_source(tmp_path) + + +def test_tool_parses_product_codes(): + tool = _load_tool() + assert tool.product_divisions("CPA_C11.01-6 & C12") == [("C", "11"), ("C", "12")] + assert tool.product_divisions("CPA_L68BXL683") == [("L", "68")] + assert tool.table3_products("CPA_C27 & C28", ["CPA_C27", "CPA_C28"]) == [ + "CPA_C27", + "CPA_C28", + ] + + +def test_household_purchases_split_by_supply_sums_to_table_2() -> None: + """Domestic, imports, margins and taxes add up to each non-trade + product's household purchases; imputed rent is left out and trade rows + keep their own demand.""" + + parts = uk_household_purchases_supply_decomposition(_source()) + uses = _source().uses + assert "CPA_L68A" not in parts.index + split = parts[ + ["domestic_basic", "imports", "distributors_margins", "taxes_less_subsidies"] + ].sum(axis=1) + trade = parts["trade_own_demand"] > 0 + np.testing.assert_allclose( + split[~trade], parts.loc[~trade, "households"], rtol=1e-9, atol=1e-9 + ) + assert not split[trade].any() + expected = uses["households"].drop("CPA_L68A").sum() + assert parts["households"].sum() == pytest.approx(expected) + assert split.sum() + parts["trade_own_demand"].sum() == pytest.approx(expected) + assert set(parts.index[trade]) <= {c for c in uses.index if c.startswith("CPA_G4")} diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_employment_allowance.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_employment_allowance.py new file mode 100644 index 0000000000..6c54262618 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_employment_allowance.py @@ -0,0 +1,122 @@ +"""Assumed Employment Allowance flags and their held-out HMRC check.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.uk_runtime.firm_employment_allowance import ( + UK_FIRM_EMPLOYMENT_ALLOWANCE_CHECK_FILE, + UK_FIRM_EMPLOYMENT_ALLOWANCE_COLUMNS, + UK_FIRM_EMPLOYMENT_ALLOWANCE_STATUS, + assign_uk_firm_employment_allowance, + read_uk_firm_employment_allowance_check, + uk_firm_employment_allowance_comparison, + uk_firm_employment_allowance_flags, +) +from microcosm.build.uk_runtime.firm_table import UK_FIRM_POLICYENGINE_UK_INPUT_STATUS + +FIXTURE = ( + Path(__file__).resolve().parents[2] + / "fixtures" + / "uk" + / "firm_employment_allowance_2024_25" +) + + +def test_flags_follow_legal_status_and_employment() -> None: + # company, sole proprietor, partnership, central government, non-profit + status = np.array([1, 1, 2, 2, 3, 3, 3, 5, 7]) + employment = np.array([1, 2, 1, 2, 1, 2, 3, 1, 1]) + flags = uk_firm_employment_allowance_flags(status, employment) + assert flags["firm_claims_employment_allowance"].tolist() == [ + True, + True, + False, + True, + False, + False, + True, + True, + True, + ] + assert flags["firm_is_single_director_company"].tolist() == [ + True, + False, + False, + False, + False, + False, + False, + False, + False, + ] + assert all(values.dtype == bool for values in flags.values()) + # No headcount at all: neither a sole proprietor nor a partnership claims. + none = uk_firm_employment_allowance_flags(np.array([2, 3, 1]), np.array([0, 0, 0])) + assert none["firm_claims_employment_allowance"].tolist() == [False, False, True] + assert not none["firm_is_single_director_company"].any() + + +def test_flags_refuse_bad_input() -> None: + with pytest.raises(ValueError, match="same shape"): + uk_firm_employment_allowance_flags(np.array([1, 2]), np.array([1])) + with pytest.raises(ValueError, match="non-negative"): + uk_firm_employment_allowance_flags(np.array([1]), np.array([-1])) + with pytest.raises(ValueError, match="ONS attributes first"): + assign_uk_firm_employment_allowance(pd.DataFrame({"employment": [1]})) + + +def test_assign_adds_only_the_flags() -> None: + firms = pd.DataFrame( + {"ons_legal_status": [1, 2, 3], "employment": [1, 1, 5], "x": [1.0, 2.0, 3.0]} + ) + out = assign_uk_firm_employment_allowance(firms) + assert list(out.columns) == [*firms.columns, *UK_FIRM_EMPLOYMENT_ALLOWANCE_COLUMNS] + pd.testing.assert_frame_equal(out[list(firms.columns)], firms) + assert out["firm_claims_employment_allowance"].tolist() == [True, False, True] + assert out["firm_is_single_director_company"].tolist() == [True, False, False] + + +def test_flags_are_assumed_inputs() -> None: + assert UK_FIRM_EMPLOYMENT_ALLOWANCE_STATUS == "assumed" + for column in UK_FIRM_EMPLOYMENT_ALLOWANCE_COLUMNS: + assert UK_FIRM_POLICYENGINE_UK_INPUT_STATUS[column] == "assumed" + + +def test_held_out_check_fixture_is_sourced() -> None: + check = read_uk_firm_employment_allowance_check(FIXTURE) + assert check.tax_year == "2024-25" + assert check.claimants == 1_223_000 + assert check.cost_gbp == 3_300_000_000 + csv_path = FIXTURE / UK_FIRM_EMPLOYMENT_ALLOWANCE_CHECK_FILE + assert check.sha256 == hashlib.sha256(csv_path.read_bytes()).hexdigest() + provenance = json.loads( + ( + FIXTURE / f"{UK_FIRM_EMPLOYMENT_ALLOWANCE_CHECK_FILE}.provenance.json" + ).read_text() + ) + assert provenance["period"] == "2024-25" + assert provenance["accessed"] == "2026-11-22" + assert "Never a calibration target" in provenance["use"] + (source,) = provenance["sources"].values() + assert source["url"].startswith("https://assets.publishing.service.gov.uk/") + assert source["edition"] == "Tax relief statistics, January 2026" + assert len(source["sha256"]) == 64 + + +def test_comparison_weights_claimants_and_cost() -> None: + check = read_uk_firm_employment_allowance_check(FIXTURE) + allowance = np.array([5_000.0, 0.0, 2_000.0]) + weight = np.array([100.0, 50.0, 200.0]) + result = uk_firm_employment_allowance_comparison(allowance, weight, check) + assert result["model_claimants"] == 300.0 + assert result["model_cost_gbp"] == 900_000.0 + assert result["model_cost_per_claimant_gbp"] == 3_000.0 + assert result["claimants_ratio"] == pytest.approx(300.0 / 1_223_000) + assert result["cost_ratio"] == pytest.approx(900_000.0 / 3.3e9) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_employment_allowance_takeup.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_employment_allowance_takeup.py new file mode 100644 index 0000000000..c421046bc3 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_employment_allowance_takeup.py @@ -0,0 +1,265 @@ +"""Opt-in Employment Allowance claim draw at HMRC's 2024-25 take-up by size.""" + +from __future__ import annotations + +import dataclasses +import hashlib +import json + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.uk_runtime.firm_employment_allowance_takeup import ( + UK_FIRM_EA_LIABILITY_LIMIT_GBP, + UK_FIRM_EA_PROXY_SECONDARY_RATE, + UK_FIRM_EA_PROXY_SECONDARY_THRESHOLD_GBP, + UK_FIRM_EA_TAKEUP_FILES, + UK_FIRM_EA_TAKEUP_STATUS, + assign_uk_firm_employment_allowance_takeup, + draw_uk_firm_employment_allowance_takeup, + read_uk_firm_employment_allowance_takeup, + uk_firm_employer_nic_proxy, + uk_firm_employment_allowance_eligible, + uk_firm_employment_allowance_takeup_bands, + uk_firm_employment_allowance_takeup_held_out, +) +from test_support.paths import paths_for + +FIXTURE = ( + paths_for("microcosm-build").package + / "tests" + / "fixtures" + / "uk" + / "firm_employment_allowance_takeup_2024_25" +) +SOURCE_SHA256 = "3848abed310515a0882c5f59a34b0b5e2f350155965f22ff3b173b55a0ceaaf0" + + +@pytest.fixture(scope="module") +def tables(): + return read_uk_firm_employment_allowance_takeup(FIXTURE) + + +def _firms(n: int, employees, *, seed: int = 0, **overrides) -> pd.DataFrame: + rng = np.random.default_rng(seed) + employees = np.broadcast_to(np.asarray(employees), (n,)).astype(np.int64) + frame = pd.DataFrame( + { + "firm_id": np.arange(n, dtype=np.int64) * 7 + 3, + "firm_weight": np.full(n, 1.0), + "firm_employees": employees, + "firm_claims_employment_allowance": np.ones(n, dtype=bool), + "firm_is_single_director_company": np.zeros(n, dtype=bool), + "firm_is_public_body": np.zeros(n, dtype=bool), + "firm_paybill": employees * 20_000.0, + "firm_sic_section": rng.choice(["A", "C", "F", "B", "UNKNOWN"], n), + "firm_region": rng.choice(["LONDON", "WALES", "SCOTLAND"], n), + } + ) + return frame.assign(**overrides) + + +def test_fixture_matches_provenance_and_source(tables) -> None: + for name in UK_FIRM_EA_TAKEUP_FILES.values(): + data = (FIXTURE / name).read_bytes() + record = json.loads((FIXTURE / f"{name}.provenance.json").read_text()) + assert record["sha256"] == SOURCE_SHA256 + assert record["published"] == "2025-06-25" + assert record["accessed"] == "2026-11-22" + assert record["file"]["sha256"] == hashlib.sha256(data).hexdigest() + assert tables.sha256[name] == record["file"]["sha256"] + assert tables.total == 1_223_000 + assert [row[:3] for row in tables.size] == [ + ("1-9", "1-9", 1_049_000.0), + ("10-49", "10-49", 166_000.0), + ("50-249", "50-249", 7_000.0), + ("250+", "250+", None), + ] + assert len(tables.sector) == 17 and len(tables.region) == 12 + + +def test_suppressed_marker_is_kept_not_a_number(tables) -> None: + top = tables.size[-1] + assert top[2] is None and top[3] == "<500" + assert all(row[3] is None for row in tables.size[:-1]) + other = next(row for row in tables.sector if row[0] == "B,D,E,O,U") + assert other[2] == 6_000.0 + + +def test_bands_pool_from_fifty_and_ignore_the_suppressed_count(tables) -> None: + bands = uk_firm_employment_allowance_takeup_bands(tables) + assert [b.lower for b in bands] == [1, 10, 50] + assert [b.hmrc_claimants for b in bands] == [1_049_000, 166_000, 7_000] + assert bands[-1].pooled == ("50-249", "250+") + assert bands[-1].ignored_suppressed == (("250+", "<500"),) + # Pooling below a suppressed band would need a number for it: refused. + with pytest.raises(ValueError, match="suppressed"): + uk_firm_employment_allowance_takeup_bands(tables, pooled_from=250) + with pytest.raises(ValueError, match="band edge"): + uk_firm_employment_allowance_takeup_bands(tables, pooled_from=20) + + +def test_nic_proxy() -> None: + threshold = UK_FIRM_EA_PROXY_SECONDARY_THRESHOLD_GBP + rate = UK_FIRM_EA_PROXY_SECONDARY_RATE + proxy = uk_firm_employer_nic_proxy( + np.array([0.0, 5_000.0, 50_000.0]), np.array([0, 1, 2]) + ) + assert proxy == pytest.approx([0.0, 0.0, rate * (50_000 - 2 * threshold)]) + # One of three employees below the threshold, paid 4,000. + with_below = uk_firm_employer_nic_proxy( + np.array([64_000.0]), np.array([3]), np.array([4_000.0]), np.array([1]) + ) + assert with_below == pytest.approx([rate * (60_000 - 2 * threshold)]) + with pytest.raises(ValueError): + uk_firm_employer_nic_proxy(np.ones(1), np.ones(1), np.ones(1), None) + + +def test_eligibility_rules() -> None: + limit_pay = UK_FIRM_EA_LIABILITY_LIMIT_GBP / UK_FIRM_EA_PROXY_SECONDARY_RATE + firms = pd.DataFrame( + { + "firm_employees": [3, 0, 3, 3, 3, 3, 1], + "firm_claims_employment_allowance": [1, 1, 0, 1, 1, 1, 1], + "firm_is_single_director_company": [0, 0, 0, 1, 0, 0, 0], + "firm_is_public_body": [0, 0, 0, 0, 1, 0, 0], + "firm_paybill": [60_000, 0, 60_000, 60_000, 60_000, 0, 0], + } + ).astype( + { + "firm_claims_employment_allowance": bool, + "firm_is_single_director_company": bool, + "firm_is_public_body": bool, + "firm_paybill": float, + } + ) + firms.loc[5, "firm_paybill"] = 3 * UK_FIRM_EA_PROXY_SECONDARY_THRESHOLD_GBP + ( + limit_pay * 1.01 + ) + firms.loc[6, "firm_paybill"] = UK_FIRM_EA_PROXY_SECONDARY_THRESHOLD_GBP + ( + limit_pay * 0.99 + ) + parts = uk_firm_employment_allowance_eligible(firms) + assert parts["eligible"].tolist() == [True, False, False, False, False, False, True] + assert parts["no_employees"].tolist()[1] + assert parts["proxy_nic_over_limit"].tolist() == [0, 0, 0, 0, 0, 1, 0] + with pytest.raises(ValueError, match="firm_paybill"): + uk_firm_employment_allowance_eligible(firms.drop(columns="firm_paybill")) + + +def test_band_totals_match_hmrc_on_a_large_frame(tables) -> None: + # 300,000 rows; weights chosen so every band holds more weighted eligible + # firms than HMRC's claimants. + n = 300_000 + employees = np.repeat([1, 5, 12, 30, 60, 400], n // 6) + firms = _firms(n, employees, firm_weight=np.repeat([30.0, 30, 8, 8, 2, 2], n // 6)) + draw = draw_uk_firm_employment_allowance_takeup(firms, tables, seed=11) + bands = {row["band"]: row for row in draw.diagnostics["bands"]} + for label, hmrc in (("1-9", 1_049_000), ("10-49", 166_000), ("50+", 7_000)): + row = bands[label] + assert not row["capped"] and row["cap_shortfall"] == 0 + assert 0 < row["propensity"] < 1 + assert row["weighted_claimants"] == pytest.approx(hmrc, rel=0.05) + assert draw.diagnostics["hmrc_band_sum"] == 1_222_000 + assert draw.diagnostics["hmrc_total"] == 1_223_000 + assert draw.diagnostics["status"] == UK_FIRM_EA_TAKEUP_STATUS == "assumed" + + +def test_propensity_caps_at_one_and_reports_the_shortfall(tables) -> None: + firms = _firms(1_000, 3) + draw = draw_uk_firm_employment_allowance_takeup(firms, tables, seed=1) + small = draw.diagnostics["bands"][0] + assert small["capped"] and small["propensity"] == 1.0 + assert small["cap_shortfall"] == pytest.approx(1_049_000 - 1_000) + assert draw.claims.all() + empty = draw.diagnostics["bands"][-1] + assert empty["weighted_eligible"] == 0 and empty["propensity"] == 0 + assert empty["cap_shortfall"] == 7_000 + assert ((draw.propensity >= 0) & (draw.propensity <= 1)).all() + + +def test_drawn_claims_are_a_subset_of_the_rule_flag(tables) -> None: + n = 20_000 + rng = np.random.default_rng(5) + firms = _firms( + n, + rng.integers(0, 80, n), + firm_weight=np.full(n, 40.0), + firm_claims_employment_allowance=rng.random(n) < 0.8, + firm_is_public_body=rng.random(n) < 0.05, + ) + out, diagnostics = assign_uk_firm_employment_allowance_takeup(firms, tables, seed=2) + drawn = out["firm_claims_employment_allowance"].to_numpy() + rule = firms["firm_claims_employment_allowance"].to_numpy() + assert not (drawn & ~rule).any() + assert not (drawn & firms["firm_is_public_body"].to_numpy()).any() + assert diagnostics["rule_claimants_ineligible_weighted"]["public_body"] > 0 + assert diagnostics["rule_claimants_ineligible_weighted"]["no_employees"] > 0 + assert out.drop(columns="firm_claims_employment_allowance").equals( + firms.drop(columns="firm_claims_employment_allowance") + ) + + +def test_draw_is_deterministic_and_row_order_independent(tables) -> None: + n = 5_000 + firms = _firms(n, np.random.default_rng(3).integers(1, 70, n), firm_weight=300.0) + first = draw_uk_firm_employment_allowance_takeup(firms, tables, seed=9) + again = draw_uk_firm_employment_allowance_takeup(firms, tables, seed=9) + assert np.array_equal(first.claims, again.claims) + other = draw_uk_firm_employment_allowance_takeup(firms, tables, seed=10) + assert not np.array_equal(first.claims, other.claims) + shuffled = firms.sample(frac=1.0, random_state=4) + drawn = draw_uk_firm_employment_allowance_takeup(shuffled, tables, seed=9) + by_id = dict(zip(firms["firm_id"], first.claims, strict=True)) + assert [by_id[i] for i in shuffled["firm_id"]] == drawn.claims.tolist() + with pytest.raises(ValueError, match="unique"): + draw_uk_firm_employment_allowance_takeup( + firms.assign(firm_id=1), tables, seed=9 + ) + + +def test_held_out_sector_and_region_mapping(tables) -> None: + firms = _firms(6, 3, firm_weight=[1.0, 2, 4, 8, 16, 32]) + firms["firm_sic_section"] = ["A", "B", "D", "UNKNOWN", "F", "F"] + firms["firm_region"] = ["LONDON", "WALES", "SCOTLAND", "NORTHERN_IRELAND"] + [ + "NORTH_EAST", + "LONDON", + ] + claims = np.array([True, True, True, True, True, False]) + result = uk_firm_employment_allowance_takeup_held_out(firms, claims, tables) + assert result["model_weighted_claimants"] == 31 + sector = {row["hmrc_code"]: row for row in result["sector"]["rows"]} + assert sector["A"]["model_weighted_claimants"] == 1 + assert sector["B,D,E,O,U"]["model_weighted_claimants"] == 6 + assert sector["F"]["model_weighted_claimants"] == 16 + assert result["sector"]["unmapped_model_labels"] == {"UNKNOWN": 8.0} + assert result["sector"]["unmapped_hmrc_codes"] == [] + region = {row["hmrc_code"]: row for row in result["region"]["rows"]} + assert region["W99999999"]["model_weighted_claimants"] == 2 + assert region["S99999999"]["model_weighted_claimants"] == 4 + assert region["N99999999"]["model_weighted_claimants"] == 8 + assert region["E12000007"]["model_weighted_claimants"] == 1 + assert region["E12000007"]["hmrc_claimants"] == 219_000 + assert result["region"]["unmapped_model_labels"] == {} + assert result["region"]["unmapped_hmrc_codes"] == [] + + +def test_a_large_low_pay_employer_falls_in_the_pooled_band(tables) -> None: + # 400 employees at the threshold: no proxy NIC, so eligible, and pooled + # with the 50-249 band whose published count is the only one used. + firms = _firms( + 2, + [400, 60], + firm_paybill=[400 * UK_FIRM_EA_PROXY_SECONDARY_THRESHOLD_GBP, 0.0], + ) + draw = draw_uk_firm_employment_allowance_takeup(firms, tables, seed=0) + pooled = draw.diagnostics["bands"][-1] + assert pooled["band"] == "50+" and pooled["eligible_rows"] == 2 + assert pooled["hmrc_claimants"] == 7_000 and pooled["propensity"] == 1.0 + assert draw.claims.tolist() == [True, True] + + +def test_tables_are_frozen(tables) -> None: + with pytest.raises(dataclasses.FrozenInstanceError): + tables.total = 0 # type: ignore[misc] diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_empty_property.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_empty_property.py new file mode 100644 index 0000000000..0b36f93c33 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_empty_property.py @@ -0,0 +1,128 @@ +"""UK firm empty property: an opt-in draw of unoccupied properties.""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import sys +from functools import cache + +import pytest + +from microcosm.build.uk_runtime.firm_empty_property import ( + UK_FIRM_EMPTY_FILES, + UK_FIRM_EMPTY_STATUS, + UKFirmEmptyPropertySource, + read_uk_firm_empty_property_source, + uk_firm_empty_property_published_figures, +) +from test_support.paths import paths_for + +PATHS = paths_for("microcosm-build") +FIXTURE = PATHS.tests / "fixtures" / "uk" / "firm_empty_property_2024_25" +TOOL = PATHS.repository / "tools" / "extract_uk_firm_empty_property_tables.py" + + +@cache +def _source() -> UKFirmEmptyPropertySource: + return read_uk_firm_empty_property_source(FIXTURE) + + +@cache +def _tool(): + name = "extract_uk_firm_empty_property_tables" + 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 test_source_reads_published_values() -> None: + source = _source() + dec_2024 = source.hereditaments["2024-12-31"] + assert dec_2024["hdit_mr_empty"] == 178_507 + assert dec_2024["hdit_mr_emptyind"] == 12_873 + assert dec_2024["hdit_mr_emptyabove"] == 39_759 + assert source.hereditaments["2023-12-31"]["hdit_mr_empty"] == 175_870 + assert source.relief_gbp["2025-26"]["value_empty"] == 1_084_979_229 + assert source.nndr3["empty_premises_relief"] == pytest.approx(1275.504353) + assert source.nndr3["hereditaments_30_sept"] == 2011 + assert source.nndr3["small_business_multiplier"] == 49.9 + assert source.nndr3["standard_multiplier"] == 54.6 + + +def test_provenance_hashes_match_fixture() -> None: + record = json.loads((FIXTURE / "provenance.json").read_text(encoding="utf-8")) + assert record["accessed"] == "2026-11-23" + assert "none was filled from memory" in record["method"] + assert set(record["sources"]) == {"nndr1_2024_25", "nndr1_2025_26", "nndr3_2024_25"} + for name in UK_FIRM_EMPTY_FILES: + payload = (FIXTURE / name).read_bytes() + assert record["files"][name]["sha256"] == hashlib.sha256(payload).hexdigest() + + +def test_supplementary_extraction_keys_on_variable_names() -> None: + tool = _tool() + names = (tool.HEREDITAMENT_TOTAL, *tool.HEREDITAMENT_PARTS) + values = (21, 1, 2, 3, 4, 5, 6) + hereditaments = [ + ("Hereditaments qualifying ... in England as at 31 December 2024",), + (None, None, None, None, "Variable name", *names), + ( + None, + None, + None, + None, + "Notes", + "Mandatory Relief for empty premises", + *"abcdef", + ), + ("Eng", "E92000001", "England ", "TE", None, *values), + ] + relief_names = (tool.RELIEF_TOTAL, *tool.RELIEF_PARTS) + relief = [ + ("Estimated cost of empty property relief ... in 2025-26 [note 7]",), + (None, None, None, None, "Estimated value of empty property relief", *"abcdef"), + (None, None, None, None, *relief_names), + ("Eng", "Eng", "England", None, 7, 1, 1, 1, 1, 1, 1), + ] + h, r = tool.extract_supplementary(hereditaments, relief) + assert h[0] == ( + "2024-12-31", + "hdit_mr_empty", + "Mandatory Relief for empty premises", + "21", + ) + assert r[0][:2] == ("2025-26", "value_empty") + broken = [*hereditaments[:3], ("Eng", "E", "England", "TE", None, 22, *values[1:])] + with pytest.raises(ValueError, match="do not sum"): + tool.extract_supplementary(broken, relief) + + +def test_published_figures_and_gap() -> None: + figures = uk_firm_empty_property_published_figures(_source()) + assert figures["status"] == UK_FIRM_EMPTY_STATUS == "not_set" + assert "firm_property_occupied" in figures["gap"] + assert figures["empty_relief_hereditaments"] == 178_507 + assert figures["empty_relief_hereditaments_above_threshold"] == 52_632 + assert figures["hereditaments_on_list"] == 2_011_000 + assert figures["empty_relief_share_of_hereditaments"] == pytest.approx( + 178_507 / 2_011_000 + ) + assert figures["empty_relief_above_threshold_forecast_gbp"] == 301_645_624 + assert figures["empty_relief_outturn_gbp"] == pytest.approx(1_275_504_353) + assert figures["empty_relief_share_of_gross_rates"] == pytest.approx( + 1275.504353 / 35439.30771 + ) + + +def test_module_assigns_nothing() -> None: + import microcosm.build.uk_runtime.firm_empty_property as module + + assert not [name for name in module.__all__ if name.startswith("assign")] + assert not hasattr(module, "draw_uk_firm_empty_property") 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..3c19f8e1bb --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_extended_export.py @@ -0,0 +1,315 @@ +"""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 +import pytest + +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_paybill import ( + assign_uk_firm_paybill, + read_uk_firm_paybill_source, + uk_firm_paybill_fallback_counts, +) +from microcosm.build.uk_runtime.firm_rules import UKFirmRuleOutputs +from microcosm.build.uk_runtime.firm_table import ( + UK_FIRM_EXTENDED_TABLE_COLUMNS, + UK_FIRM_PAYBILL_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 + + +def test_paybill_export_tracks_ashe_jobs_times_mean_pay() -> None: + """A coarse headcount check: weighted paybill near ASHE jobs x mean pay. + + Not calibrated: headcount x section mean, with proprietors and + out-of-frame traders included. ASHE 2025's all-employees row gives + 24,889 thousand jobs at a mean of 40,444.9 pounds, about 1.007 trillion + pounds; the band only catches gross failures, such as a headcount or + unit error. Every firm here has a published section, so none falls back + to the all-employees mean. + """ + + source = read_uk_firm_paybill_source(FIXTURES / "firm_paybill_2024") + firms = _with_attributes() + firms = firms.assign(firm_paybill=assign_uk_firm_paybill(firms, source)) + table = to_policyengine_uk_firm_table( + firms, threshold_k=_generated().config.vat_threshold + ) + + assert tuple(table.columns) == UK_FIRM_PAYBILL_TABLE_COLUMNS + validate_uk_firm_table(table) + weighted = float((table["firm_weight"] * table["firm_paybill"]).sum()) + ashe = 24_889_000 * 40_444.9 + assert 0.85 < weighted / ashe < 1.25 + counts = uk_firm_paybill_fallback_counts(table, source).set_index("level") + assert float(counts["weighted_paybill_gbp"].sum()) == pytest.approx(weighted) + assert int(counts.loc["all_employees", "firms"]) == 0 + + +#: The three 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"), +) +_PAYBILL_POLICYENGINE_UK = (("firm_paybill", "float"),) +_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, + ), + "paybill": ( + *_BASE_POLICYENGINE_UK, + *_ATTRIBUTE_POLICYENGINE_UK, + *_PAYBILL_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() + source = read_uk_firm_paybill_source(FIXTURES / "firm_paybill_2024") + paybill = attributed.assign(firm_paybill=assign_uk_firm_paybill(attributed, source)) + return { + layout: to_policyengine_uk_firm_table(firms, threshold_k=threshold_k) + for layout, firms in ( + ("base", _generated().firms), + ("extended", attributed), + ("paybill", paybill), + ) + } + + +def test_export_layouts_match_the_pre_registry_constants() -> None: + """Same-seed builds export the three layouts the named constants gave. + + Columns, their order and dtypes are the literal pre-registry layouts; + the named constants still spell them; the extended and paybill exports + equal the base export assembled with their 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"] + ) + assert UK_FIRM_PAYBILL_TABLE_COLUMNS == tuple( + c for c, _ in _LEGACY_LAYOUTS["paybill"] + ) + 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, paybill = (exports[k] for k in ("base", "extended", "paybill")) + 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) + source = read_uk_firm_paybill_source(FIXTURES / "firm_paybill_2024") + legacy_paybill = legacy_extended.assign( + firm_paybill=np.asarray(assign_uk_firm_paybill(rows, source), np.float64) + )[[column for column, _ in _LEGACY_LAYOUTS["paybill"]]] + pd.testing.assert_frame_equal(paybill, legacy_paybill, 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..98fdbd9b75 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,62 @@ 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, + LARGE_EMPLOYMENT_CAP, + LARGE_EMPLOYMENT_MEAN, 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, + large_employment_mean_range, + large_employment_pareto_shape, + large_employment_slice_means, 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 +140,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 +186,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 +197,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 +232,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 +272,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 +361,521 @@ 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_large_employment_slices_hit_the_mean_inside_the_band() -> None: + shape = large_employment_pareto_shape() + # DBT's 250-499 / 500-999 / 1000+ shares are 0.51 / 0.26 / 0.23. + tail = 1.0 - (250.0 / LARGE_EMPLOYMENT_CAP) ** shape + above_1000 = ((250.0 / 1_000.0) ** shape - (1.0 - tail)) / tail + assert 1.0 < shape < 1.3 + assert above_1000 == pytest.approx(0.234, abs=0.04) + for masses in (np.ones(1), np.ones(2_000), np.linspace(0.5, 50.0, 997)): + means = large_employment_slice_means(masses) + assert np.all(np.diff(means) > 0) + assert means.min() >= 250.0 + assert means.max() <= LARGE_EMPLOYMENT_CAP + weighted = float((masses * means).sum() / masses.sum()) + assert weighted == pytest.approx(LARGE_EMPLOYMENT_MEAN, rel=1e-9) + # A zero-mass slice takes its quantile rather than dividing by zero. + assert np.isfinite(large_employment_slice_means(np.array([1.0, 0.0, 1.0]))).all() + with pytest.raises(ValueError, match="non-negative"): + large_employment_slice_means(np.array([-1.0, 1.0])) + + +def test_assign_employment_weights_the_large_band_mean() -> None: + ons_employment = pd.DataFrame( + [{"SIC Code": 2, "Description": "Large", "0-4": 0, "250+": 5}] + ) + torch.manual_seed(0) + sic = torch.full((400,), 2, dtype=torch.int64) + weights = np.linspace(1.0, 40.0, 400) + + employment = assign_employment( + sic, + ons_employment, + weights=weights, + large_employment_mean=LARGE_EMPLOYMENT_MEAN, + ).numpy() + torch.manual_seed(0) + legacy = assign_employment(sic, ons_employment, weights=weights).numpy() + + assert employment.min() >= 250 and employment.max() > 2_000 + weighted = float((weights * employment).sum() / weights.sum()) + assert weighted == pytest.approx(LARGE_EMPLOYMENT_MEAN, rel=1e-3) + # The default keeps the paper's draw, clamped to [250, 2000], and both + # rank the rows by the same lognormal draw. + assert legacy.min() >= 250 and legacy.max() <= 2_000 + inside = (legacy > 250) & (legacy < 2_000) + order = np.argsort(legacy[inside], kind="stable") + ranked = employment[inside][order] + distinct = np.diff(legacy[inside][order]) > 0 + assert np.all(np.diff(ranked)[distinct] >= 0) + with pytest.raises(ValueError, match="large_employment_mean"): + UKFirmGenerationConfig(large_employment_mean=100.0) + + +def test_assign_employment_keeps_out_of_frame_rows_below_the_large_band() -> None: + """With a large-employment mean, only ONS-frame rows reach 250+, and the + mean is theirs; without one, ``in_frame`` changes nothing.""" + + ons_employment = pd.DataFrame( + [ + {"SIC Code": 2, "Description": "Mixed", "0-4": 6, "20-49": 2, "250+": 2}, + {"SIC Code": 3, "Description": "Large", "0-4": 0, "20-49": 0, "250+": 5}, + ] + ) + sic = torch.cat([torch.full((3_000,), 2), torch.full((1_000,), 3)]).to(torch.int64) + in_frame = np.arange(len(sic)) % 3 != 0 + weights = np.linspace(1.0, 20.0, len(sic)) + + torch.manual_seed(0) + legacy = assign_employment(sic, ons_employment, weights=weights).numpy() + legacy_state = torch.get_rng_state() + torch.manual_seed(0) + masked = assign_employment( + sic, ons_employment, weights=weights, in_frame=in_frame + ).numpy() + # The default draw ignores the frame mask: out-of-frame rows reach 250+. + np.testing.assert_array_equal(masked, legacy) + assert torch.equal(torch.get_rng_state(), legacy_state) + assert (legacy[~in_frame] >= 250).any() + + torch.manual_seed(0) + employment = assign_employment( + sic, + ons_employment, + weights=weights, + large_employment_mean=LARGE_EMPLOYMENT_MEAN, + in_frame=in_frame, + ).numpy() + # The option takes no draws of its own from the generator. + assert torch.equal(torch.get_rng_state(), legacy_state) + + outside = employment[~in_frame] + assert outside.min() >= 1 and outside.max() <= 249 + large = employment >= 250 + np.testing.assert_array_equal(large, (legacy >= 250) & in_frame) + # Rows the default draws below 250 keep their headcount. + np.testing.assert_array_equal(employment[legacy < 250], legacy[legacy < 250]) + weighted = float((weights * employment)[large].sum() / weights[large].sum()) + assert weighted == pytest.approx(LARGE_EMPLOYMENT_MEAN, rel=1e-3) + + moved = ~in_frame & (legacy >= 250) + # A sector with smaller bands redraws from its own shares of them (0-4 + # and 20-49 here); a sector with only the open band uses the national + # shares, which are the same two bands. + for sector in (2, 3): + redrawn = employment[moved & (sic.numpy() == sector)] + assert len(redrawn) > 0 + assert set(employment_band_name(value) for value in redrawn) == { + "0-4", + "20-49", + } + small_share = float((employment[moved & (sic.numpy() == 2)] <= 4).mean()) + assert small_share == pytest.approx(0.75, abs=0.08) + + with pytest.raises(ValueError, match="in_frame"): + assign_employment( + sic, + ons_employment, + large_employment_mean=LARGE_EMPLOYMENT_MEAN, + in_frame=in_frame[:-1], + ) + + +def test_employment_below_large_band_covers_each_closed_band() -> None: + below = firm_generation._employment_below_large_band + scores = np.linspace(-6.0, 6.0, 4_001) + shares = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 5.0]) + values = below(scores, 0.0, 1.0, shares, np.ones(7)) + # Monotone in the score, whole numbers, inside the closed bands with mass. + assert np.all(np.diff(values) >= 0) + np.testing.assert_array_equal(values, np.round(values)) + assert {employment_band_name(value) for value in values} == { + "0-4", + "5-9", + "20-49", + "100-249", + } + assert values.min() == 1 and values.max() == 249 + # No mass below the open band: the fallback shares, then equal shares. + only_large = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]) + fallback = below(scores, 0.0, 1.0, only_large, np.array([0, 0, 1.0, 0, 0, 0, 3])) + assert fallback.min() == 10 and fallback.max() == 19 + equal = below(scores, 0.0, 1.0, only_large, only_large) + assert equal.min() == 1 and equal.max() == 249 + + +@pytest.mark.parametrize("mean", [255.0, 100_000.0]) +def test_large_employment_mean_outside_the_reachable_range_raises( + mean: float, +) -> None: + """Means a bracketed Pareto shape cannot reach raise, not saturate.""" + + smallest, largest = large_employment_mean_range() + assert not smallest <= mean <= largest + with pytest.raises(ValueError, match="outside"): + large_employment_pareto_shape(mean) + with pytest.raises(ValueError, match="large_employment_mean"): + UKFirmGenerationConfig(large_employment_mean=mean) + # The DBT mean is well inside the range. + assert smallest < LARGE_EMPLOYMENT_MEAN < largest + + +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 +889,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 +912,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_headcount.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_headcount.py new file mode 100644 index 0000000000..858e9abd30 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_headcount.py @@ -0,0 +1,465 @@ +"""UK firm headcount: proprietors, employees and the BPE small-firm redraw.""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import re +import sys +from functools import cache + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.uk_runtime import firm_headcount +from microcosm.build.uk_runtime.firm_headcount import ( + UK_FIRM_BPE_LEGAL_STATUS_COLUMNS, + UK_FIRM_BPE_LEGAL_STATUS_FILE, + UK_FIRM_BPE_SIZE_BANDS_COLUMNS, + UK_FIRM_BPE_SIZE_BANDS_FILE, + UK_FIRM_EMPLOYEE_SIZE_BANDS, + UK_FIRM_HEADCOUNT_STATUS, + UK_FIRM_ONS_SMALL_BAND, + UK_FIRM_SMALL_HEADCOUNT_STATUSES, + UKFirmBPESource, + fit_truncated_geometric, + read_uk_firm_bpe_source, + redraw_uk_firm_small_headcount, + uk_firm_assumed_proprietors, + uk_firm_bpe_size_band_reconciliation, + uk_firm_employee_size_bands, + uk_firm_employees, + uk_firm_small_headcount_diagnostics, + uk_firm_small_headcount_fits, + uk_firm_small_headcount_targets, +) +from test_support.paths import paths_for + +PATHS = paths_for("microcosm-build") +FIXTURE = PATHS.tests / "fixtures" / "uk" / "firm_bpe_2025" +PROVENANCE = FIXTURE / "firm_bpe_2025.provenance.json" +TOOL = PATHS.repository / "tools" / "extract_uk_firm_bpe_tables.py" +MODULE = ( + PATHS.package / "src" / "microcosm" / "build" / "uk_runtime" / ("firm_headcount.py") +) +WORKBOOK_SHA256 = "223790dfd61d41d5866b747f2ea24535cef0db754ee261ae9a2d88bba9f478d7" + + +@cache +def _source() -> UKFirmBPESource: + return read_uk_firm_bpe_source(FIXTURE) + + +@cache +def _provenance() -> dict: + return json.loads(PROVENANCE.read_text(encoding="utf-8")) + + +@cache +def _load_tool(): + name = "extract_uk_firm_bpe_tables" + 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 _table_3(section: str, band: str) -> tuple[float, float]: + frame = _source().legal_status + row = frame[(frame["legal_status"] == section) & (frame["size_band"] == band)] + assert len(row) == 1 + return ( + float(row["business_number"].iloc[0]), + float(row["employment_thousand"].iloc[0]) * 1000, + ) + + +def _frame(n: int, seed: int = 0) -> pd.DataFrame: + """A synthetic generator frame: every status, employment 1 to 300.""" + + rng = np.random.default_rng(seed) + status = rng.integers(1, 8, n) + employment = np.where( + rng.random(n) < 0.7, rng.integers(1, 5, n), rng.integers(5, 300, n) + ) + ids = rng.permutation(n).astype(np.int64) + 1 + return pd.DataFrame( + { + "firm_id": ids, + "source_firm_id": ids, + "ons_legal_status": status.astype(np.int64), + "employment": employment.astype(int), + "firm_weight": rng.uniform(0.5, 5.0, n).astype(np.float32), + "other": rng.random(n), + } + ) + + +# -- fixture ------------------------------------------------------------------- + + +def test_fixture_hashes_match_provenance() -> None: + record = _provenance() + assert record["source"]["sha256"] == WORKBOOK_SHA256 + assert "none was filled from memory" in record["method"] + assert record["accessed"] == "2026-11-22" + for name in (UK_FIRM_BPE_LEGAL_STATUS_FILE, UK_FIRM_BPE_SIZE_BANDS_FILE): + payload = (FIXTURE / name).read_bytes() + entry = record["files"][name] + assert hashlib.sha256(payload).hexdigest() == entry["sha256"] + assert _source().sha256[name] == entry["sha256"] + assert len(payload) == entry["bytes"] + + +def test_fixture_reads_with_columns_and_suppression() -> None: + source = _source() + assert tuple(source.legal_status.columns) == UK_FIRM_BPE_LEGAL_STATUS_COLUMNS + assert tuple(source.size_bands.columns) == UK_FIRM_BPE_SIZE_BANDS_COLUMNS + assert set(source.legal_status["legal_status"]) == { + "private_sector", + "companies", + "ordinary_partnerships", + "sole_proprietorships", + } + suppressed = source.legal_status["employment_flag"] == "[c]" + assert suppressed.any() + assert source.legal_status.loc[suppressed, "employment_thousand"].isna().all() + assert source.legal_status.loc[~suppressed, "employment_thousand"].notna().all() + assert set(source.size_bands["sector"]) == { + "private_sector", + "whole_economy", + "central_and_local_government", + "non_profit", + } + # Table 1 and Table 2 publish the same private sector. + t1 = source.size_bands[source.size_bands["table"] == "Table 1"] + t2 = source.size_bands[ + (source.size_bands["table"] == "Table 2") + & (source.size_bands["sector"] == "private_sector") + ] + assert ( + t1.loc[t1["size_band"] == "All businesses", "business_number"].iloc[0] + == t2.loc[t2["size_band"] == "All", "business_number"].iloc[0] + ) + + +def test_reader_rejects_value_with_suppressed_flag(tmp_path) -> None: + for name in (UK_FIRM_BPE_LEGAL_STATUS_FILE, UK_FIRM_BPE_SIZE_BANDS_FILE): + (tmp_path / name).write_bytes((FIXTURE / name).read_bytes()) + path = tmp_path / UK_FIRM_BPE_LEGAL_STATUS_FILE + text = path.read_text(encoding="utf-8").replace(",,[c]", ",1,[c]", 1) + path.write_text(text, encoding="utf-8") + with pytest.raises(ValueError, match="empty exactly"): + read_uk_firm_bpe_source(tmp_path) + + +def test_tool_flags_suppressed_cells_and_headers_agree() -> None: + tool = _load_tool() + assert tool.LEGAL_STATUS_HEADER == UK_FIRM_BPE_LEGAL_STATUS_COLUMNS + assert tool.SIZE_BANDS_HEADER == UK_FIRM_BPE_SIZE_BANDS_COLUMNS + assert tool._cell("[c]", "x") == ("", "[c]") + assert tool._cell(1749, "x") == ("1749", "") + assert tool._band("With no employees (registered) [Note 2] [Note 6]") == ( + "With no employees (registered)" + ) + with pytest.raises(ValueError): + tool._cell("n/a", "x") + + +def test_bpe_employment_already_counts_working_proprietors() -> None: + """Single-value rows' means sit on the proprietor rule's employment.""" + + fits = uk_firm_small_headcount_fits(_source()) + single = fits[(fits["support_low"] == fits["support_high"]) & (fits.businesses > 0)] + assert len(single) >= 4 + assert np.allclose(single["mean_employment"], single["support_low"], atol=0.06) + + +# -- proprietors, employees and bands ------------------------------------------ + + +def test_proprietor_rules() -> None: + status = np.array([1, 1, 2, 2, 3, 3, 3, 4, 5, 6, 7]) + employment = np.array([1, 5, 1, 3, 1, 2, 7, 3, 3, 3, 3]) + assert uk_firm_assumed_proprietors(status, employment).tolist() == [ + 0, + 0, + 1, + 1, + 1, + 2, + 2, + 0, + 0, + 0, + 0, + ] + employees = uk_firm_employees(status, employment) + assert employees.dtype == np.int64 + assert employees.tolist() == [1, 5, 0, 2, 0, 0, 5, 3, 3, 3, 3] + assert (employees >= 0).all() + with pytest.raises(ValueError): + uk_firm_employees(np.array([8]), np.array([1])) + with pytest.raises(ValueError): + uk_firm_employees(np.array([1]), np.array([1.5])) + + +def test_employee_size_bands() -> None: + lowers = [ + int(re.match(r"\d+", band).group()) for band in UK_FIRM_EMPLOYEE_SIZE_BANDS + ] + labels = uk_firm_employee_size_bands(np.array(lowers)) + assert labels.tolist() == list(UK_FIRM_EMPLOYEE_SIZE_BANDS) + uppers = [edge - 1 for edge in lowers[1:]] + assert uk_firm_employee_size_bands(np.array(uppers)).tolist() == list( + UK_FIRM_EMPLOYEE_SIZE_BANDS[:-1] + ) + assert uk_firm_employee_size_bands(np.array([123456])).tolist() == ["1000+"] + assert len(UK_FIRM_EMPLOYEE_SIZE_BANDS) == 12 + assert UK_FIRM_EMPLOYEE_SIZE_BANDS[:3] == ("0", "1", "2-4") + + +# -- the target ---------------------------------------------------------------- + + +def test_geometric_fit_matches_mean_and_clips() -> None: + for low, high, mean in ((2, 4, 2.3), (3, 5, 4.8), (1, 4, 2.5), (4, 6, 4.01)): + ratio, fitted, clipped = fit_truncated_geometric(low, high, mean) + assert not clipped + assert fitted == pytest.approx(mean, abs=1e-9) + assert ratio > 0 + _, fitted, clipped = fit_truncated_geometric(2, 4, 4.5) + assert clipped and fitted == pytest.approx(4, abs=1e-5) + _, fitted, clipped = fit_truncated_geometric(2, 4, 1.0) + assert clipped and fitted == pytest.approx(2, abs=1e-5) + + +def test_fits_match_published_means() -> None: + fits = uk_firm_small_headcount_fits(_source()) + multi = fits[fits["support_high"] > fits["support_low"]] + assert len(multi) == 3 + assert not multi["clipped"].any() + assert np.allclose(multi["fitted_mean"], multi["mean_employment"], atol=1e-8) + for _, row in multi.iterrows(): + section = UK_FIRM_SMALL_HEADCOUNT_STATUSES[row["ons_legal_status"]] + businesses, employment = _table_3(section, row["bpe_size_band"]) + assert row["mean_employment"] == pytest.approx(employment / businesses) + # Companies' "2 to 4" stays in band; sole and partnership rows spill over. + company = multi[multi["ons_legal_status"] == 1].iloc[0] + assert company["in_band_share"] == pytest.approx(1.0) + assert (multi.loc[multi["ons_legal_status"] != 1, "in_band_share"] < 1).all() + + +def test_targets_follow_table_3() -> None: + targets = uk_firm_small_headcount_targets(_source()) + assert np.allclose(targets.groupby("ons_legal_status")["share"].sum(), 1.0) + by = targets.set_index(["ons_legal_status", "employment"])["businesses"] + registered = "With no employees (registered)" + assert by[(1, 1)] == _table_3("companies", registered)[0] + assert by[(1, 2)] + by[(1, 3)] + by[(1, 4)] == pytest.approx( + _table_3("companies", "2 to 4")[0] + ) + assert by[(2, 1)] == _table_3("sole_proprietorships", registered)[0] + assert by[(2, 2)] == _table_3("sole_proprietorships", "1")[0] + assert by[(3, 1)] == 0 + assert by[(3, 2)] == _table_3("ordinary_partnerships", registered)[0] + assert by[(3, 3)] == _table_3("ordinary_partnerships", "1")[0] + # Geometric shape decreasing for companies (mean below the midpoint). + assert by[(1, 2)] > by[(1, 3)] > by[(1, 4)] + + +def test_module_hard_codes_no_bpe_number() -> None: + text = MODULE.read_text(encoding="utf-8") + literals = { + int(m) + for m in re.findall(r"(?= 100} + # Band edges in labels are not statistics. + edges = { + int(e) for band in UK_FIRM_EMPLOYEE_SIZE_BANDS for e in re.findall(r"\d+", band) + } + assert (literals & published) - edges == set() + + +# -- the redraw ---------------------------------------------------------------- + + +def test_redraw_touches_only_small_status_1_to_3_rows() -> None: + before = _frame(20_000) + after = redraw_uk_firm_small_headcount(before, _source(), seed=7) + low, high = UK_FIRM_ONS_SMALL_BAND + eligible = before["ons_legal_status"].isin([1, 2, 3]) & before[ + "employment" + ].between(low, high) + pd.testing.assert_frame_equal( + after.loc[~eligible], before.loc[~eligible], check_exact=True + ) + pd.testing.assert_frame_equal( + after.drop(columns="employment"), before.drop(columns="employment") + ) + assert after["employment"].dtype == before["employment"].dtype + assert after.loc[eligible, "employment"].between(low, high).all() + assert ( + after.loc[eligible, "employment"] != before.loc[eligible, "employment"] + ).any() + # ONS employment bands never change. + edges = [0, 4, 9, 19, 49, 99, 249, np.inf] + assert ( + pd.cut(after["employment"], edges).astype(str) + == pd.cut(before["employment"], edges).astype(str) + ).all() + # Partnerships never redraw to employment 1. + partnership = eligible & (before["ons_legal_status"] == 3) + assert (after.loc[partnership, "employment"] != 1).all() + assert UK_FIRM_HEADCOUNT_STATUS == "assumed" + + +def test_redraw_is_deterministic_and_row_order_free() -> None: + frame = _frame(5_000, seed=3) + one = redraw_uk_firm_small_headcount(frame, _source(), seed=11) + two = redraw_uk_firm_small_headcount(frame, _source(), seed=11) + pd.testing.assert_frame_equal(one, two) + shuffled = frame.sample(frac=1.0, random_state=5) + three = redraw_uk_firm_small_headcount(shuffled, _source(), seed=11) + pd.testing.assert_frame_equal(three.loc[one.index], one) + other = redraw_uk_firm_small_headcount(frame, _source(), seed=12) + assert not other["employment"].equals(one["employment"]) + # Without id columns the index orders the draws. + bare = frame.drop(columns=["firm_id", "source_firm_id"]).set_index(frame["firm_id"]) + four = redraw_uk_firm_small_headcount(bare, _source(), seed=11) + assert four["employment"].tolist() == one["employment"].tolist() + + +def test_redraw_rejects_repeated_ids() -> None: + frame = _frame(10) + frame.loc[1, "source_firm_id"] = frame.loc[0, "source_firm_id"] + with pytest.raises(ValueError, match="repeat"): + redraw_uk_firm_small_headcount(frame, _source(), seed=1) + + +def test_weighted_shares_converge_to_targets() -> None: + # Every row eligible: about 200,000 weighted draws per status. + before = _frame(600_000, seed=9) + rng = np.random.default_rng(1) + before["ons_legal_status"] = rng.integers(1, 4, len(before)) + before["employment"] = rng.integers(1, 5, len(before)) + after = redraw_uk_firm_small_headcount(before, _source(), seed=2) + table = uk_firm_small_headcount_diagnostics(before, after, _source()) + assert set(table["ons_legal_status"]) == {1, 2, 3} + assert np.allclose(table["share_after"], table["target_share"], atol=0.006) + # Before: the generator's even spread is far from the target. + assert not np.allclose(table["share_before"], table["target_share"], atol=0.05) + assert np.allclose( + table.groupby("ons_legal_status")["weight_before"].sum(), + table.groupby("ons_legal_status")["weight_after"].sum(), + rtol=1e-6, + ) + + +# -- reconciliation ------------------------------------------------------------ + + +def test_size_band_reconciliation() -> None: + frame = _frame(20_000, seed=4) + table = uk_firm_bpe_size_band_reconciliation(frame, _source(), "firm_weight") + assert set(table["scope"]) == {"private_sector", "whole_economy"} + weight = frame["firm_weight"].to_numpy(np.float64) + whole = table[table["scope"] == "whole_economy"].set_index("size_band") + assert whole.loc["All", "modelled_businesses"] == pytest.approx(weight.sum()) + assert whole.drop(index="All")["modelled_businesses"].sum() == pytest.approx( + weight.sum() + ) + employees = uk_firm_employees(frame["ons_legal_status"], frame["employment"]) + assert whole.loc["All", "modelled_employees"] == pytest.approx(weight @ employees) + private = table[table["scope"] == "private_sector"].set_index("size_band") + keep = frame["ons_legal_status"].isin([1, 2, 3, 4]).to_numpy() + assert private.loc["All", "modelled_businesses"] == pytest.approx( + weight[keep].sum() + ) + # Unregistered businesses come out of the first band and the total only. + gap = private["bpe_businesses"] - private["bpe_registered_businesses"] + assert gap.loc["All"] == gap.loc["Zero or 1 employee"] > 0 + assert (gap.drop(index=["All", "Zero or 1 employee"]) == 0).all() + assert list(private.index[:2]) == ["Zero or 1 employee", "2 to 4"] + + +def test_firm_headcount_exports() -> None: + for name in firm_headcount.__all__: + assert hasattr(firm_headcount, name) + + +def _mid_frame(n: int = 200_000, seed: int = 3) -> pd.DataFrame: + rng = np.random.default_rng(seed) + bands = [(5, 9), (10, 19), (20, 49), (50, 99), (100, 249), (250, 400)] + choice = rng.integers(0, len(bands), n) + low = np.array([b[0] for b in bands])[choice] + high = np.array([b[1] for b in bands])[choice] + return pd.DataFrame( + { + "firm_id": np.arange(1, n + 1), + "ons_legal_status": rng.choice([1, 2, 3, 4, 5, 7], n), + "employment": rng.integers(low, high + 1), + "firm_weight": rng.uniform(0.5, 2.0, n), + } + ) + + +def test_mid_remap_keeps_bands_ranks_and_other_rows() -> None: + firms = _mid_frame() + out = firm_headcount.remap_uk_firm_mid_headcount(firms, _source(), seed=1) + before = firms["employment"].to_numpy() + after = out["employment"].to_numpy() + eligible = np.isin(firms["ons_legal_status"], [1, 2, 3, 4]) & (before <= 249) + assert (after[~eligible] == before[~eligible]).all() + pd.testing.assert_frame_equal( + out.drop(columns="employment"), firms.drop(columns="employment") + ) + edges = [5, 10, 20, 50, 100, 250] + band_before = np.searchsorted(edges, before, side="right") + band_after = np.searchsorted(edges, after, side="right") + assert (band_before == band_after).all() + for band in range(1, 6): + rows = eligible & (band_before == band) + frame = pd.DataFrame({"before": before[rows], "after": after[rows]}) + span = frame.groupby("before")["after"].agg(["min", "max"]) + # A larger headcount never maps below a smaller one. + assert (span["max"].to_numpy()[:-1] <= span["min"].to_numpy()[1:]).all() + + +def test_mid_remap_weighted_means_match_bpe() -> None: + firms = _mid_frame() + out = firm_headcount.remap_uk_firm_mid_headcount(firms, _source(), seed=1) + targets = firm_headcount.uk_firm_mid_headcount_targets(_source()) + expected = ( + targets.assign(m=targets["employment"] * targets["probability"]) + .groupby("ons_band")["m"] + .sum() + ) + eligible = np.isin(out["ons_legal_status"], [1, 2, 3, 4]) + for band_low, band_high, _ in firm_headcount.UK_FIRM_MID_BANDS: + rows = eligible & out["employment"].between(band_low, band_high) + w = out.loc[rows, "firm_weight"] + mean = float((w * out.loc[rows, "employment"]).sum() / w.sum()) + assert mean == pytest.approx(expected[f"{band_low}-{band_high}"], rel=0.01) + + +def test_mid_remap_is_deterministic_and_row_order_free() -> None: + firms = _mid_frame(20_000) + once = firm_headcount.remap_uk_firm_mid_headcount(firms, _source(), seed=7) + shuffled = firms.sample(frac=1.0, random_state=4) + again = firm_headcount.remap_uk_firm_mid_headcount(shuffled, _source(), seed=7) + pd.testing.assert_frame_equal(once, again.sort_index()) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_large_employment.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_large_employment.py new file mode 100644 index 0000000000..e71ae4436d --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_large_employment.py @@ -0,0 +1,139 @@ +"""The opt-in large-firm headcount tail against the default 2024-25 draw. + +``UKFirmGenerationConfig.large_employment_mean`` replaces the default 250+ +headcount draw with a truncated Pareto tail fitted to a published mean. That +mean describes businesses in the ONS frame, so with the option on the +out-of-frame stratum (the HMRC zero-turnover traders) draws below 250 and +the 250+ band holds frame rows only. The default build is pinned by +``test_uk_firm_paper_parity.py``; these tests show the option changes +headcounts only, and only where the default draws 250 or more. +""" + +from __future__ import annotations + +import dataclasses +from functools import cache + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.uk_runtime.firm_generation import ( + LARGE_EMPLOYMENT_CAP, + LARGE_EMPLOYMENT_MEAN, + UKFirmGenerationConfig, + generate_uk_firm_population, + read_uk_firm_source_data, +) +from microcosm.build.uk_runtime.firm_rules import UKFirmRuleOutputs +from test_support.paths import paths_for + +FIXTURE_DIR = paths_for("microcosm-build").tests / "fixtures" / "uk" / "firm_2024_25" +EPOCHS = 20 + + +class _StandardRateDouble: + """Test-only rules double: 0.20 x (turnover - inputs), in pounds.""" + + def evaluate(self, firms: pd.DataFrame, *, period: object) -> 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() -> UKFirmGenerationConfig: + return UKFirmGenerationConfig( + data_vintage="2024-25", + seed=42, + n_iterations=EPOCHS, + sample_window_fraction=0.05, + sample_tail_fraction=0.01, + firm_rules=_StandardRateDouble(), + ) + + +@cache +def _firms(large_employment_mean: float | None) -> pd.DataFrame: + data = read_uk_firm_source_data(FIXTURE_DIR) + config = dataclasses.replace(_config(), large_employment_mean=large_employment_mean) + return generate_uk_firm_population(data, config).firms + + +def _ons_large_firm_count() -> float: + table = read_uk_firm_source_data(FIXTURE_DIR).ons_employment + sectors = table[~table["Description"].astype(str).str.contains("Total", na=False)] + return float(sectors["250+"].fillna(0).sum()) + + +def test_default_config_leaves_the_large_employment_mean_off() -> None: + assert UKFirmGenerationConfig().large_employment_mean is None + assert _config().large_employment_mean is None + default = _firms(None) + # The default keeps the paper's clamp, and its out-of-frame rows reach + # the open band: the behaviour the option removes. + assert default["employment"].max() <= 2_000 + outside = default.loc[~default["in_frame"], "employment"] + assert (outside >= 250).any() + + +def test_the_option_changes_headcounts_only_where_the_default_draws_large() -> None: + default = _firms(None) + large = _firms(LARGE_EMPLOYMENT_MEAN) + + # Weights, turnover, registration and every other column are the + # default's: employment target rows count frame rows only, and the frame + # rows keep their bands. + pd.testing.assert_frame_equal( + large.drop(columns="employment"), default.drop(columns="employment") + ) + legacy = default["employment"].to_numpy() + employment = large["employment"].to_numpy() + np.testing.assert_array_equal(employment[legacy < 250], legacy[legacy < 250]) + in_frame = large["in_frame"].to_numpy(dtype=bool) + np.testing.assert_array_equal(employment >= 250, (legacy >= 250) & in_frame) + + +def test_out_of_frame_rows_draw_below_the_large_band() -> None: + large = _firms(LARGE_EMPLOYMENT_MEAN) + outside = large.loc[~large["in_frame"], "employment"].to_numpy() + + assert len(outside) > 0 + assert outside.min() >= 1 + assert outside.max() <= 249 + + +def test_weighted_large_firm_count_and_mean() -> None: + default = _firms(None) + large = _firms(LARGE_EMPLOYMENT_MEAN) + employment = large["employment"].to_numpy(dtype=np.float64) + weights = large["firm_weight"].to_numpy(dtype=np.float64) + base_weights = large["base_weight"].to_numpy(dtype=np.float64) + in_frame = large["in_frame"].to_numpy(dtype=bool) + band = employment >= 250 + + # The weighted 250+ count is the frame's alone: the default's in-frame + # 250+ weight, which the solve holds near the ONS 250+ enterprise count. + legacy_band = default["employment"].to_numpy() >= 250 + legacy_weights = default["firm_weight"].to_numpy(dtype=np.float64) + count = float(weights[band].sum()) + assert count == pytest.approx(float(legacy_weights[legacy_band & in_frame].sum())) + assert count < float(legacy_weights[legacy_band].sum()) + assert count == pytest.approx(_ons_large_firm_count(), rel=0.10) + + # The tail is fitted at base weights over the frame's 250+ rows, so + # their base-weighted mean is the configured mean; calibration moves the + # weighted mean a little. + base_mean = float( + (base_weights * employment)[band].sum() / base_weights[band].sum() + ) + assert base_mean == pytest.approx(LARGE_EMPLOYMENT_MEAN, rel=1e-3) + mean = float((weights * employment)[band].sum() / weights[band].sum()) + assert mean == pytest.approx(LARGE_EMPLOYMENT_MEAN, rel=0.10) + assert 2_000 < employment.max() <= LARGE_EMPLOYMENT_CAP 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_pay_distribution.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_pay_distribution.py new file mode 100644 index 0000000000..134c47c1c5 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_pay_distribution.py @@ -0,0 +1,179 @@ +"""UK firm employees at or below the secondary threshold, from ASHE percentiles.""" + +from __future__ import annotations + +import hashlib +import json + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.uk_runtime.firm_pay_distribution import ( + UK_FIRM_PAY_DISTRIBUTION_FILE, + UK_FIRM_PAY_DISTRIBUTION_SOURCE_COLUMNS, + assign_uk_firm_pay_below_secondary_threshold, + read_uk_firm_pay_distribution_source, + uk_firm_pay_below_threshold_by_section, +) +from microcosm.build.uk_runtime.firm_paybill import read_uk_firm_paybill_source +from test_support.paths import paths_for + +PATHS = paths_for("microcosm-build") +FIXTURES = PATHS.tests / "fixtures" / "uk" +SOURCE_DIR = FIXTURES / "firm_pay_distribution_2024" +#: policyengine-uk gov.hmrc.national_insurance.class_1.employer_scale +#: bracket 1 threshold for 2024-25: 175 pounds a week x 52 weeks. +THRESHOLD = 175 * 52 + + +@pytest.fixture(scope="module") +def source(): + return read_uk_firm_pay_distribution_source(SOURCE_DIR) + + +def test_fixture_matches_provenance_and_paybill_table(source): + csv_path = SOURCE_DIR / UK_FIRM_PAY_DISTRIBUTION_FILE + record = json.loads( + (SOURCE_DIR / (UK_FIRM_PAY_DISTRIBUTION_FILE + ".provenance.json")).read_text() + ) + assert record["accessed"] == "2026-11-22" + assert ( + record["files"][UK_FIRM_PAY_DISTRIBUTION_FILE]["sha256"] + == hashlib.sha256(csv_path.read_bytes()).hexdigest() + == source.sha256 + ) + ons = record["sources"]["ons_ashe_table_4"] + paybill_record = json.loads( + (FIXTURES / "firm_paybill_2024" / ".provenance.json").read_text() + ) + assert ons["sha256"] == paybill_record["source"]["zip_sha256"] + assert ons["url"] == paybill_record["source"]["download_url"] + for key in ("landing_page", "edition", "sha256", "url"): + assert ons[key] + assert record["method"] + + frame = pd.read_csv(csv_path, dtype=str, keep_default_na=False) + assert tuple(frame.columns) == UK_FIRM_PAY_DISTRIBUTION_SOURCE_COLUMNS + paybill = read_uk_firm_paybill_source(FIXTURES / "firm_paybill_2024") + means = frame.set_index("sic_section")["mean"] + for section, mean in paybill.section_mean.items(): + assert float(means[section]) == mean + assert float(means["ALL"]) == paybill.all_employees_mean + for section, marker in paybill.unpublished.items(): + assert means[section] == marker + # ONS markers are kept, never written as 0 or blank. + assert frame.set_index("sic_section").loc["A", "p10"] == "x" + assert not (frame == "").to_numpy().any() + assert not source.section_percentiles["U"] + + +def test_share_and_mean_follow_the_piecewise_line(source): + table = uk_firm_pay_below_threshold_by_section( + source, threshold_gbp=THRESHOLD + ).set_index("sic_section") + # ALL: p10 = 11412.1 is above 9,100, so the line is 0 -> p10. + p10 = source.section_percentiles["ALL"][10] + assert table.loc["ALL", "share_at_or_below"] == pytest.approx(0.1 * THRESHOLD / p10) + assert table.loc["ALL", "mean_pay_at_or_below_gbp"] == pytest.approx(THRESHOLD / 2) + # I: p20 = 8180.7 < 9,100 <= p25 = 9610.5. + curve = source.section_percentiles["I"] + share = 0.20 + 0.05 * (THRESHOLD - curve[20]) / (curve[25] - curve[20]) + area = ( + 0.10 * curve[10] / 2 + + 0.10 * (curve[10] + curve[20]) / 2 + + (share - 0.20) * (curve[20] + THRESHOLD) / 2 + ) + assert table.loc["I", "share_at_or_below"] == pytest.approx(share) + assert table.loc["I", "mean_pay_at_or_below_gbp"] == pytest.approx(area / share) + # A has no p10: the line runs 0 -> p20. + assert table.loc["A", "share_at_or_below"] == pytest.approx( + 0.2 * THRESHOLD / source.section_percentiles["A"][20] + ) + # U and UNKNOWN take the all-employees row. + for key in ("U", "UNKNOWN"): + assert table.loc[key, "level"] == "all_employees" + assert ( + table.loc[key, "share_at_or_below"] == table.loc["ALL", "share_at_or_below"] + ) + assert (table["share_at_or_below"].between(0, 1)).all() + assert (table["mean_pay_at_or_below_gbp"] <= THRESHOLD).all() + zero = uk_firm_pay_below_threshold_by_section(source, threshold_gbp=0) + assert (zero["share_at_or_below"] == 0).all() + with pytest.raises(ValueError, match="above the highest"): + uk_firm_pay_below_threshold_by_section(source, threshold_gbp=1e6) + + +def test_assignment_is_integer_deterministic_and_bounded(source): + rng = np.random.default_rng(0) + n = 20_000 + sections = rng.choice(["I", "G", "K", "U", "UNKNOWN", "A"], size=n) + employees = rng.integers(0, 40, size=n) + table = pd.DataFrame( + { + "firm_employees": employees, + "firm_sic_section": sections, + "firm_paybill": employees * 3_000.0, + } + ) + out = assign_uk_firm_pay_below_secondary_threshold( + table, source, threshold_gbp=THRESHOLD + ) + count = out["firm_employees_below_secondary_threshold"] + paybill = out["firm_paybill_below_secondary_threshold"] + assert count.dtype == np.int64 and paybill.dtype == np.float64 + assert (count >= 0).all() and (count <= employees).all() + assert (paybill >= 0).all() and (paybill <= table["firm_paybill"]).all() + assert (paybill <= count * THRESHOLD).all() + again = assign_uk_firm_pay_below_secondary_threshold( + table, source, threshold_gbp=THRESHOLD + ) + assert np.array_equal(count, again["firm_employees_below_secondary_threshold"]) + + shares = ( + uk_firm_pay_below_threshold_by_section(source, threshold_gbp=THRESHOLD) + .set_index("sic_section")["share_at_or_below"] + .reindex(sections) + .to_numpy() + ) + expected = employees * shares + assert np.all(np.abs(count - expected) < 1) + assert count.sum() == pytest.approx(expected.sum(), rel=0.01) + + # Without firm_paybill the paybill is count x section mean below. + uncapped = assign_uk_firm_pay_below_secondary_threshold( + table.drop(columns="firm_paybill"), source, threshold_gbp=THRESHOLD + ) + assert (uncapped["firm_paybill_below_secondary_threshold"] >= paybill).all() + + # Generator rows: employment and sic_code (division 56 is section I). + firms = pd.DataFrame({"employment": [100, 0], "sic_code": ["00056", "00056"]}) + generated = assign_uk_firm_pay_below_secondary_threshold( + firms, source, threshold_gbp=THRESHOLD + ) + share_i = ( + uk_firm_pay_below_threshold_by_section(source, threshold_gbp=THRESHOLD) + .set_index("sic_section") + .loc["I", "share_at_or_below"] + ) + assert ( + abs(generated["firm_employees_below_secondary_threshold"][0] - 100 * share_i) + < 1 + ) + assert generated["firm_employees_below_secondary_threshold"][1] == 0 + with pytest.raises(ValueError, match="needs firm_employees"): + assign_uk_firm_pay_below_secondary_threshold( + pd.DataFrame({"x": [1]}), source, threshold_gbp=THRESHOLD + ) + + +def test_reader_rejects_bad_tables(tmp_path): + good = (SOURCE_DIR / UK_FIRM_PAY_DISTRIBUTION_FILE).read_text() + bad = tmp_path / UK_FIRM_PAY_DISTRIBUTION_FILE + bad.write_text(good.replace(",p90\n", ",p95\n")) + with pytest.raises(ValueError, match="columns"): + read_uk_firm_pay_distribution_source(tmp_path) + lines = good.splitlines() + bad.write_text("\n".join(lines[:-1]) + "\n") + with pytest.raises(ValueError, match="once each"): + read_uk_firm_pay_distribution_source(tmp_path) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_paybill.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_paybill.py new file mode 100644 index 0000000000..79e1f2424b --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_paybill.py @@ -0,0 +1,370 @@ +"""UK firm paybill: headcount x ONS ASHE section mean annual gross pay.""" + +from __future__ import annotations + +import argparse +import hashlib +import importlib.util +import io +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_paybill import ( + UK_FIRM_PAYBILL_ALL_EMPLOYEES, + UK_FIRM_PAYBILL_FILE, + UK_FIRM_PAYBILL_LEVELS, + UK_FIRM_PAYBILL_SOURCE_COLUMNS, + UK_FIRM_PAYBILL_TAX_YEAR, + assign_uk_firm_paybill, + read_uk_firm_paybill_source, + uk_firm_paybill_fallback_counts, + uk_firm_paybill_mean_pay, +) +from microcosm.build.uk_runtime.firm_table import ( + UK_FIRM_EXTENDED_TABLE_COLUMNS, + UK_FIRM_PAYBILL_TABLE_COLUMNS, + to_policyengine_uk_firm_table, + validate_uk_firm_table, +) +from microcosm.build.uk_runtime.occupation_constants import ( + UK_SIC2007_SECTION_DIVISIONS, +) +from test_support.paths import paths_for + +PATHS = paths_for("microcosm-build") +PAYBILL = PATHS.tests / "fixtures" / "uk" / "firm_paybill_2024" +TOOL = PATHS.repository / "tools" / "extract_uk_firm_paybill_table.py" + +#: ASHE 2025 Table 4.7a, sheet All, column Mean, read off the workbook. +_SPOT_MEANS = { + "C": 43879.2, + "G": 31679.1, + "I": 21528.1, + "K": 84079.9, + "Q": 34429.7, + "T": 16061.1, +} +_ALL_EMPLOYEES_MEAN = 40444.9 + + +@cache +def _source(): + return read_uk_firm_paybill_source(PAYBILL) + + +@cache +def _provenance() -> dict: + return json.loads((PAYBILL / ".provenance.json").read_text(encoding="utf-8")) + + +@cache +def _load_tool(): + if "extract_uk_firm_paybill_table" in sys.modules: + return sys.modules["extract_uk_firm_paybill_table"] + spec = importlib.util.spec_from_file_location("extract_uk_firm_paybill_table", 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_fixture_reads_as_the_published_section_means() -> None: + source = _source() + + assert set(source.section_mean) == set(UK_SIC2007_SECTION_DIVISIONS) - {"U"} + assert dict(source.unpublished) == {"U": "x"} + for section, mean in _SPOT_MEANS.items(): + assert source.section_mean[section] == mean + assert source.all_employees_mean == _ALL_EMPLOYEES_MEAN + assert all(mean > 0 for mean in source.section_mean.values()) + + +def test_provenance_pins_the_source_and_the_csv() -> None: + provenance = _provenance() + payload = (PAYBILL / UK_FIRM_PAYBILL_FILE).read_bytes() + record = provenance["files"][UK_FIRM_PAYBILL_FILE] + + assert record["sha256"] == hashlib.sha256(payload).hexdigest() + assert record["sha256"] == _source().sha256 + assert record["bytes"] == len(payload) + assert tuple(record["columns"]) == UK_FIRM_PAYBILL_SOURCE_COLUMNS + source = provenance["source"] + assert source["download_url"].startswith("https://www.ons.gov.uk/file?uri=") + assert source["download_url"].endswith("/2025revised/ashetable42025revised.zip") + assert source["edition"] == "2025 revised" + assert source["sheet"] == "All" + assert source["access_date"] == "2026-11-22" + assert len(source["zip_sha256"]) == 64 + assert len(source["member_sha256"]) == 64 + assert "Table 4.7a" in source["member"] + assert UK_FIRM_PAYBILL_TAX_YEAR == "2024-25" + assert UK_FIRM_PAYBILL_TAX_YEAR in provenance["reference_period"] + assert provenance["unpublished"]["markers"] == {"U": "x"} + + +def test_tool_access_date_defaults_to_the_recorded_one() -> None: + """``--access-date`` defaults to the fixture's date, so a re-extraction + without it reproduces the committed provenance; a bad date is refused.""" + + tool = _load_tool() + assert tool.ACCESS_DATE == _provenance()["source"]["access_date"] + assert tool._iso_date("2027-01-05") == "2027-01-05" + with pytest.raises(argparse.ArgumentTypeError, match="YYYY-MM-DD"): + tool._iso_date("5 January 2027") + + +def test_tool_rebuilds_the_csv_from_sheet_rows() -> None: + """The extractor on rows shaped like the 2025 sheet writes the fixture's + layout, keeps an ``x`` section blank and refuses a missing section.""" + + tool = _load_tool() + rows: list[tuple] = [ + ( + "SIC2007 Table 4 .7a Annual pay - Gross (£) - For all employee " + "jobsa: United Kingdom 2025", + ) + + (None,) * 7, + (None,) * 8, + (None, None, "Number", None, "Annual", None, "Annual", None), + (None, None, "of jobsb", None, "percentage", None, "percentage", "P"), + ("Description", "Code", "(thousand)", "Median", "change", "Mean", "change", 10), + ("ALL EMPLOYEES", None, 24889, 32856.6, 4, 40444.9, 6, 1.0), + ] + for section in UK_SIC2007_SECTION_DIVISIONS: + if section == "U": + rows.append(("EXTRATERRITORIAL ", "'U ", "x", "x", None, "x", None, "x")) + else: + rows.append((f"{section} SECTION ", f"'{section} ", 10, 1.0, 0, 2.5, 0, 0)) + rows.append(("A division ", "'01", 5, 1.0, 0, 9.0, 0, 0)) + table = tool.extract_rows(rows) + frame = pd.read_csv( + io.BytesIO(table.to_csv_bytes()), + dtype=str, + keep_default_na=False, + ) + + assert tuple(frame.columns) == UK_FIRM_PAYBILL_SOURCE_COLUMNS + assert frame["sic_section"].tolist() == [ + *UK_SIC2007_SECTION_DIVISIONS, + UK_FIRM_PAYBILL_ALL_EMPLOYEES, + ] + by_section = frame.set_index("sic_section") + assert by_section.loc["U", "mean_annual_gross_pay_gbp"] == "" + assert by_section.loc["U", "marker"] == "x" + assert by_section.loc["A", "mean_annual_gross_pay_gbp"] == "2.5" + assert by_section.loc["ALL", "mean_annual_gross_pay_gbp"] == "40444.9" + with pytest.raises(ValueError, match="sections"): + tool.extract_rows([row for row in rows if row[1] != "'Q "]) + + +def _write_source(tmp_path: Path, edit) -> Path: + frame = pd.read_csv( + PAYBILL / UK_FIRM_PAYBILL_FILE, dtype=str, keep_default_na=False + ) + frame = edit(frame) + path = tmp_path / UK_FIRM_PAYBILL_FILE + frame.to_csv(path, index=False) + return path + + +def _set(section: str, column: str, value: str): + def edit(frame: pd.DataFrame) -> pd.DataFrame: + frame.loc[frame["sic_section"] == section, column] = value + return frame + + return edit + + +@pytest.mark.parametrize( + ("edit", "match"), + [ + (lambda f: f[f["sic_section"] != "Q"], "sections A-U"), + (lambda f: f[f["sic_section"] != "ALL"], "sections A-U"), + (lambda f: pd.concat([f, f.iloc[[0]]]), "sections A-U"), + (_set("U", "mean_annual_gross_pay_gbp", "1000"), "has a mean and marker"), + (_set("C", "mean_annual_gross_pay_gbp", "0"), "must be positive"), + (_set("C", "mean_annual_gross_pay_gbp", "n/a"), "not a number"), + (_set("ALL", "marker", "x"), "has a mean and marker"), + (lambda f: f.drop(columns="marker"), "columns"), + ], +) +def test_source_refuses_a_broken_table(tmp_path: Path, edit, match) -> None: + path = _write_source(tmp_path, edit) + with pytest.raises(ValueError, match=match): + read_uk_firm_paybill_source(path) + + +def test_source_refuses_a_missing_all_employees_mean(tmp_path: Path) -> None: + def edit(frame: pd.DataFrame) -> pd.DataFrame: + frame.loc[frame["sic_section"] == "ALL", "mean_annual_gross_pay_gbp"] = "" + frame.loc[frame["sic_section"] == "ALL", "marker"] = ":" + return frame + + with pytest.raises(ValueError, match="all-employees"): + read_uk_firm_paybill_source(_write_source(tmp_path, edit)) + + +def _table() -> pd.DataFrame: + return pd.DataFrame( + { + "firm_employees": np.array([3, 0, 2, 5, 1], dtype=np.int64), + "firm_sic_section": ["C", "K", "U", "UNKNOWN", "I"], + "firm_weight": [2.0, 1.0, 1.0, 0.5, 4.0], + } + ) + + +def test_paybill_is_headcount_times_section_mean() -> None: + source = _source() + paybill = assign_uk_firm_paybill(_table(), source) + + assert paybill.dtype == np.float64 + np.testing.assert_allclose( + paybill, + [ + 3 * 43879.2, + 0.0, + # U is unpublished and UNKNOWN has no row: the all-employees mean. + 2 * _ALL_EMPLOYEES_MEAN, + 5 * _ALL_EMPLOYEES_MEAN, + 1 * 21528.1, + ], + ) + np.testing.assert_allclose( + uk_firm_paybill_mean_pay(_table(), source), + [43879.2, 84079.9, _ALL_EMPLOYEES_MEAN, _ALL_EMPLOYEES_MEAN, 21528.1], + ) + + +def test_generator_rows_map_divisions_to_sections() -> None: + firms = pd.DataFrame( + { + "employment": np.array([4, 1, 2]), + # Divisions 64 (K), 99 (U) and 0 (no section). + "sic_code": ["00064", "00099", "00000"], + } + ) + np.testing.assert_allclose( + assign_uk_firm_paybill(firms, _source()), + [4 * 84079.9, _ALL_EMPLOYEES_MEAN, 2 * _ALL_EMPLOYEES_MEAN], + ) + + +def test_fallback_counts_report_each_level() -> None: + counts = uk_firm_paybill_fallback_counts(_table(), _source()) + + assert tuple(counts["level"]) == UK_FIRM_PAYBILL_LEVELS + by_level = counts.set_index("level") + assert by_level.loc["section", "firms"] == 3 + assert by_level.loc["section", "firms_with_employees"] == 2 + assert by_level.loc["all_employees", "firms"] == 2 + assert by_level.loc["all_employees", "weight"] == pytest.approx(1.5) + assert by_level.loc["all_employees", "weighted_paybill_gbp"] == pytest.approx( + 2 * _ALL_EMPLOYEES_MEAN + 0.5 * 5 * _ALL_EMPLOYEES_MEAN + ) + assert counts["weighted_paybill_gbp"].sum() == pytest.approx( + float( + ( + _table()["firm_weight"] * assign_uk_firm_paybill(_table(), _source()) + ).sum() + ) + ) + + +@pytest.mark.parametrize( + ("column", "value", "match"), + [ + ("firm_employees", -1, "non-negative whole"), + ("firm_employees", 1.5, "non-negative whole"), + ("firm_sic_section", "Z", "SICSection"), + ], +) +def test_paybill_refuses_bad_rows(column, value, match) -> None: + table = _table().astype({column: object}) + table.loc[0, column] = value + with pytest.raises(ValueError, match=match): + assign_uk_firm_paybill(table, _source()) + + +def test_paybill_needs_headcount_and_section() -> None: + with pytest.raises(ValueError, match="needs firm_employees"): + assign_uk_firm_paybill(_table().drop(columns="firm_sic_section"), _source()) + + +def _attributed_firms() -> pd.DataFrame: + """Generator rows out of firm_id order, with ONS attribute draws.""" + + return pd.DataFrame( + { + "firm_id": np.array([4, 2, 1, 3], dtype=np.int64), + "source_firm_id": np.array([4, 2, 1, 3], dtype=np.int64), + "source_firm_key": [ + f"2024-25:experimental_uk_firm:{i}" for i in (4, 2, 1, 3) + ], + "data_vintage": "2024-25", + "sic_code": ["00011", "00047", "00004", "00086"], + "annual_turnover_k": np.array([120.0, 90.0, 0.0, 40.0]), + "annual_input_k": np.array([80.0, 30.0, 0.0, 10.0]), + "employment": np.array([12, 3, 0, 1]), + "firm_weight": [2.5, 10.0, 0.0, 4.0], + "vat_scope": [True, True, False, False], + "vat_registered": [True, True, False, True], + "in_frame": [True, True, False, True], + "base_weight": [1.0, 2.0, 1.0, 1.0], + "ons_legal_status": np.array([1, 2, 5, 7], dtype=np.int64), + "ons_region_code": ["E12000007", "W92000004", "S92000003", "N92000002"], + } + ) + + +def test_export_carries_paybill_aligned_by_firm_id() -> None: + firms = _attributed_firms() + firms["firm_paybill"] = assign_uk_firm_paybill(firms, _source()) + table = to_policyengine_uk_firm_table(firms, threshold_k=90.0) + + assert tuple(table.columns) == UK_FIRM_PAYBILL_TABLE_COLUMNS + validate_uk_firm_table(table) + # Ordered by firm_id: 1 (division 4, B, no employees), 2 (47, G), + # 3 (86, Q), 4 (11, C). + np.testing.assert_allclose( + table["firm_paybill"], + [0.0, 3 * 31679.1, 1 * 34429.7, 12 * 43879.2], + ) + np.testing.assert_allclose( + table["firm_paybill"], assign_uk_firm_paybill(table, _source()) + ) + pd.testing.assert_frame_equal( + table[list(UK_FIRM_EXTENDED_TABLE_COLUMNS)], + to_policyengine_uk_firm_table(_attributed_firms(), threshold_k=90.0), + ) + + +def test_export_refuses_paybill_without_attributes() -> None: + firms = _attributed_firms().drop(columns=["ons_legal_status", "ons_region_code"]) + firms["firm_paybill"] = 0.0 + with pytest.raises(ValueError, match="firm_paybill without"): + to_policyengine_uk_firm_table(firms, threshold_k=90.0) + + +@pytest.mark.parametrize( + ("row", "value", "match"), + [ + (1, -1.0, "finite and non-negative"), + (1, np.inf, "finite and non-negative"), + (0, 5.0, "zero without employees"), + ], +) +def test_validator_checks_the_paybill(row, value, match) -> None: + firms = _attributed_firms() + firms["firm_paybill"] = assign_uk_firm_paybill(firms, _source()) + table = to_policyengine_uk_firm_table(firms, threshold_k=90.0) + table.loc[row, "firm_paybill"] = value + with pytest.raises(ValueError, match=match): + validate_uk_firm_table(table) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_paybill_anchor.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_paybill_anchor.py new file mode 100644 index 0000000000..3e6a4427bb --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_paybill_anchor.py @@ -0,0 +1,45 @@ +"""UK paybill anchors (ONS D.11, PAYE RTI): report-only ratios.""" + +from __future__ import annotations + +import numpy as np +import pytest + +from microcosm.build.uk_runtime.firm_paybill_anchor import ( + read_uk_firm_paybill_anchors, + uk_firm_paybill_anchor_ratios, +) +from test_support.paths import paths_for + +FIXTURE = ( + paths_for("microcosm-build").tests / "fixtures" / "uk" / "firm_paybill_anchor_2024" +) + + +def test_anchors_are_the_published_values(): + anchors = read_uk_firm_paybill_anchors(FIXTURE) + assert anchors.values["ons_d11_wages_and_salaries"] == 1_162_752e6 + assert anchors.values["paye_rti_aggregate_pay"] == pytest.approx(1_189_583_389_662) + assert anchors.values["paye_rti_payrolled_employees"] == pytest.approx( + 30_430_260.17 + ) + + +def test_reader_refuses_an_edited_file(tmp_path): + for name in ("paybill_anchors.csv", "provenance.json"): + (tmp_path / name).write_bytes((FIXTURE / name).read_bytes()) + path = tmp_path / "paybill_anchors.csv" + path.write_text(path.read_text().replace("1162752", "1162753")) + with pytest.raises(ValueError, match="sha256"): + read_uk_firm_paybill_anchors(tmp_path) + + +def test_ratios_are_weighted_and_report_only(): + anchors = read_uk_firm_paybill_anchors(FIXTURE) + got = uk_firm_paybill_anchor_ratios( + np.array([30_000.0, 50_000.0]), np.array([1, 2]), np.array([2.0, 1.0]), anchors + ) + assert got["weighted_paybill_gbp"] == 110_000.0 + assert got["weighted_employees"] == 4.0 + assert got["paybill_over_ons_d11"] == pytest.approx(110_000 / 1_162_752e6) + assert got["status"] == "report_only" 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..b7aec3de0c --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_policyengine_uk_schema.py @@ -0,0 +1,180 @@ +"""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_PAYBILL_TABLE_COLUMNS, + 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, paybill: 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"] + if paybill: + # Headcount x a pay per head; the source is test_uk_firm_paybill's. + firms["firm_paybill"] = firms["employment"].to_numpy(np.float64) * 30000.0 + 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", "paybill", "expected", "groups"), + [ + (False, False, UK_FIRM_TABLE_COLUMNS, ()), + (True, False, UK_FIRM_EXTENDED_TABLE_COLUMNS, ("attributes",)), + (True, True, UK_FIRM_PAYBILL_TABLE_COLUMNS, ("attributes", "paybill")), + ], +) +def test_export_loads_as_policyengine_uk_firm_inputs( + attributes, paybill, expected, groups +) -> None: + table = to_policyengine_uk_firm_table( + _firms(attributes=attributes, paybill=paybill), 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_profit.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_profit.py new file mode 100644 index 0000000000..028b3dcf94 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_profit.py @@ -0,0 +1,317 @@ +"""UK firm taxable profit: HMRC liability bands through the CT schedule.""" + +from __future__ import annotations + +import hashlib +import json +from functools import cache + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.uk_runtime.firm_profit import ( + UK_FIRM_PROFIT_CT_SCHEDULE, + UK_FIRM_PROFIT_FILE, + UK_FIRM_PROFIT_SEED, + UK_FIRM_PROFIT_SOURCE_COLUMNS, + UK_FIRM_PROFIT_STATUS, + UKFirmProfitBand, + UKFirmProfitSource, + assign_uk_firm_taxable_profit, + read_uk_firm_profit_source, + uk_corporation_tax_liability, + uk_corporation_tax_profit, + uk_firm_profit_bands, + uk_firm_profit_diagnostics, + uk_firm_profit_section_liability, +) +from test_support.paths import paths_for + +PATHS = paths_for("microcosm-build") +FIXTURE = PATHS.tests / "fixtures" / "uk" / "firm_ct_2024" +SECTIONS_FILE = "ct_sic_sections.csv" +ODS_SHA256 = "d1a1ea0e9ae5c8e3045c99d5b1aad242b659d955d9569df4d202feac9b24aa21" + + +@cache +def _source() -> UKFirmProfitSource: + return read_uk_firm_profit_source(FIXTURE) + + +def _small_source() -> UKFirmProfitSource: + """Three made-up bands, small enough for a unit-weight frame.""" + + bands = ( + UKFirmProfitBand("low", 0.0, 5_000.0, 40.0, 40 * 2_000.0), + UKFirmProfitBand("mid", 5_000.0, 80_000.0, 25.0, 25 * 30_000.0), + UKFirmProfitBand("top", 80_000.0, np.inf, 5.0, 5 * 400_000.0), + ) + return UKFirmProfitSource( + bands=bands, + zero_companies=100.0, + positive_companies=70.0, + positive_liability=sum(band.liability for band in bands), + all_returns=170.0, + file="synthetic", + sha256="", + ) + + +def _frame(n: int = 160, seed: int = 3) -> pd.DataFrame: + rng = np.random.default_rng(seed) + status = np.where(np.arange(n) % 4 == 3, 2, 1) + status[5] = 3 + status[9] = 7 + return pd.DataFrame( + { + "firm_id": np.arange(1, n + 1), + "firm_weight": np.ones(n), + "annual_turnover_k": np.round(rng.lognormal(5.0, 1.5, n), 0), + "sic_code": rng.choice([1, 25, 47, 62, 64, 86], n), + "employment": rng.integers(1, 50, n), + "ons_legal_status": status, + } + ) + + +def test_fixture_is_well_formed() -> None: + source = _source() + frame = pd.read_csv(FIXTURE / UK_FIRM_PROFIT_FILE, dtype=str, keep_default_na=False) + assert tuple(frame.columns) == UK_FIRM_PROFIT_SOURCE_COLUMNS + assert len(source.bands) == 13 + assert source.bands[0].lower == 0.0 + assert np.isinf(source.bands[-1].upper) + for band, following in zip(source.bands, source.bands[1:], strict=False): + assert band.upper == following.lower + # Read off Tables 9A and 9B, column 2024-25. + assert source.zero_companies == 1_676_855 + assert source.positive_companies == 1_637_230 + assert source.all_returns == 3_314_085 + assert source.positive_liability == 87_945e6 + assert (source.bands[-1].companies, source.bands[-1].liability) == (155, 19_248e6) + # Counts are rounded to 5 and amounts to GBP 1 million, band by band. + counts = sum(band.companies for band in source.bands) + assert abs(counts - source.positive_companies) <= 2.5 * len(source.bands) + assert abs(counts + source.zero_companies - source.all_returns) <= 2.5 * 15 + liability = sum(band.liability for band in source.bands) + assert abs(liability - source.positive_liability) <= 0.5e6 * len(source.bands) + + +def test_fixture_provenance() -> None: + for name in (UK_FIRM_PROFIT_FILE, SECTIONS_FILE): + record = json.loads( + (FIXTURE / f"{name}.provenance.json").read_text(encoding="utf-8") + ) + payload = (FIXTURE / name).read_bytes() + assert record["file"]["sha256"] == hashlib.sha256(payload).hexdigest() + assert record["sha256"] == ODS_SHA256 + assert record["accessed"] == "2026-11-22" + assert record["url"].startswith("https://assets.publishing.service.gov.uk/") + assert record["landing_page"].startswith("https://www.gov.uk/") + for key in ("edition", "method", "period"): + assert record[key] + + +def test_held_out_sector_table_is_well_formed() -> None: + frame = pd.read_csv(FIXTURE / SECTIONS_FILE) + assert list(frame["hmrc_section"]) == [*"ABCDEFGHIJKLMNOPQRSTU", "ALL"] + sections, total = frame.iloc[:-1], frame.iloc[-1] + assert total["liability_gbp_million"] == _source().positive_liability / 1e6 + assert total["companies_with_liability"] == _source().positive_companies + assert abs(sections["liability_gbp_million"].sum() - 87_945) <= 0.5 * 21 + assert abs(sections["companies_with_liability"].sum() - 1_637_230) <= 2.5 * 21 + + +def test_inversion_round_trips_on_the_band_edges() -> None: + schedule = UK_FIRM_PROFIT_CT_SCHEDULE + bands = uk_firm_profit_bands(_source()) + edges = np.unique( + np.concatenate( + [ + bands["liability_lower_gbp"], + bands["liability_upper_gbp"][:-1], + bands["mean_liability_gbp"], + # The schedule's own kinks, as liabilities. + [ + schedule.small_profits_rate * schedule.lower_limit, + schedule.main_rate * schedule.upper_limit, + ], + ] + ) + ) + profit = uk_corporation_tax_profit(edges) + np.testing.assert_allclose( + uk_corporation_tax_liability(profit), edges, rtol=1e-12, atol=1e-6 + ) + assert np.all(np.diff(profit) > 0) + assert np.isinf(bands["profit_upper_gbp"].iloc[-1]) + assert (bands["profit_lower_gbp"] < bands["mean_profit_gbp"]).all() + assert (bands["mean_profit_gbp"] < bands["profit_upper_gbp"]).all() + # And from the profit side, through the limits. + profits = np.array([0.0, 1.0, 50_000.0, 50_000.01, 150_000.0, 250_000.0, 1e9]) + np.testing.assert_allclose( + uk_corporation_tax_profit(uk_corporation_tax_liability(profits)), + profits, + rtol=1e-12, + atol=1e-6, + ) + + +def test_ct_formula_matches_the_statute() -> None: + # Small profits rate, marginal relief of 3/200 x (250,000 - profit), main rate. + np.testing.assert_allclose( + uk_corporation_tax_liability(np.array([40_000.0, 100_000.0, 300_000.0])), + [0.19 * 40_000, 0.25 * 100_000 - 0.015 * 150_000, 0.25 * 300_000], + ) + assert uk_corporation_tax_liability(-5.0) == 0.0 + + +def test_assignment_matches_band_counts_and_totals() -> None: + firms, source = _frame(), _small_source() + profit = assign_uk_firm_taxable_profit(firms, source) + table = uk_firm_profit_diagnostics(firms, source) + companies = int((firms["ons_legal_status"] == 1).sum()) + assert list(table["band"]) == ["0", "low", "mid", "top"] + np.testing.assert_allclose(table["weighted_companies"][1:], [40, 25, 5]) + assert table["weighted_companies"][0] == companies - 70 + np.testing.assert_allclose( + table["weighted_liability_gbp"][1:], table["table_liability_gbp"][1:] + ) + assert not table["table_mean_used"].any() + np.testing.assert_allclose( + table["weighted_profit_gbp"].sum(), (profit * firms["firm_weight"]).sum() + ) + # Each liability sits inside its band. + tax = uk_corporation_tax_liability(profit) + for band, n in zip(source.bands, (40, 25, 5), strict=True): + inside = (tax > band.lower) & (tax <= band.upper) + assert inside.sum() == n + + +def test_profit_rises_with_turnover_within_a_section() -> None: + firms, source = _frame(), _small_source() + firms = firms.assign(profit=assign_uk_firm_taxable_profit(firms, source)) + companies = firms[firms["ons_legal_status"] == 1] + for _, group in companies.groupby("sic_code"): + ordered = group.sort_values("annual_turnover_k") + strict = ordered.drop_duplicates("annual_turnover_k", keep=False) + assert strict["profit"].is_monotonic_increasing + + +def test_non_companies_get_zero() -> None: + firms = _frame() + profit = assign_uk_firm_taxable_profit(firms, _small_source()) + others = firms["ons_legal_status"].to_numpy() != 1 + assert others.any() + assert np.all(profit[others] == 0.0) + assert np.all(profit >= 0.0) + assert (profit[~others] > 0).sum() == 70 + + +def test_deterministic_and_row_order_free() -> None: + firms, source = _frame(), _small_source() + first = assign_uk_firm_taxable_profit(firms, source) + np.testing.assert_array_equal(first, assign_uk_firm_taxable_profit(firms, source)) + shuffled = firms.sample(frac=1.0, random_state=11) + again = pd.Series( + assign_uk_firm_taxable_profit(shuffled, source), index=shuffled.index + ) + np.testing.assert_allclose(again.sort_index().to_numpy(), first, rtol=1e-12) + # The stream is the module's own: the global state is left alone. + state = np.random.get_state()[1].copy() + assign_uk_firm_taxable_profit(firms, source, seed=UK_FIRM_PROFIT_SEED) + np.testing.assert_array_equal(np.random.get_state()[1], state) + + +def test_firm_table_columns_give_the_same_profit() -> None: + firms, source = _frame(), _small_source() + sections = {1: "A", 25: "C", 47: "G", 62: "J", 64: "K", 86: "Q"} + forms = {1: "COMPANY", 2: "SOLE_TRADER", 3: "PARTNERSHIP", 7: "OTHER"} + table = pd.DataFrame( + { + "firm_id": firms["firm_id"], + "firm_weight": firms["firm_weight"], + "firm_turnover": firms["annual_turnover_k"] * 1_000.0, + "firm_sic_section": firms["sic_code"].map(sections), + "firm_legal_form": firms["ons_legal_status"].map(forms), + } + ) + np.testing.assert_allclose( + assign_uk_firm_taxable_profit(table, source), + assign_uk_firm_taxable_profit(firms, source), + ) + by_section = uk_firm_profit_section_liability(table, source) + assert set(by_section["sic_section"]) <= set(sections.values()) + np.testing.assert_allclose( + by_section["weighted_liability_gbp"].sum(), source.positive_liability + ) + assert by_section["weighted_companies_with_liability"].sum() == 70 + + +def test_weights_and_shortfall() -> None: + # Too few companies for the bands: the top bands fill first, the lowest + # band is short and no company is left without a liability. + firms = _frame(40).assign(ons_legal_status=1, firm_weight=1.5) + table = uk_firm_profit_diagnostics(firms, _small_source()) + np.testing.assert_allclose(table["weighted_companies"], [0.0, 30.0, 25.5, 4.5]) + assert table["weighted_companies"].sum() == 60.0 + + +def test_real_table_on_a_weighted_frame() -> None: + source = _source() + n = 40_000 + rng = np.random.default_rng(5) + firms = pd.DataFrame( + { + "firm_id": np.arange(n), + "firm_weight": np.full(n, 2_000_000 / n), + "annual_turnover_k": rng.lognormal(5.0, 2.0, n), + "sic_code": rng.choice([10, 41, 47, 62, 64, 70], n), + "ons_legal_status": np.ones(n, dtype=np.int64), + } + ) + table = uk_firm_profit_diagnostics(firms, source) + positive = table.iloc[1:] + # A row is 50 companies: each band is within a row of the table. + assert ( + (positive["weighted_companies"] - positive["table_companies"]).abs() <= 50 + ).all() + assert table["weighted_companies"].sum() == pytest.approx(2_000_000) + matched = ~positive["table_mean_used"] + assert matched.all() + np.testing.assert_allclose( + positive.loc[matched, "weighted_liability_gbp"], + positive.loc[matched, "table_liability_gbp"], + rtol=1e-9, + ) + + +def test_refusals() -> None: + firms, source = _frame(), _small_source() + with pytest.raises(ValueError, match="one row per firm_id"): + assign_uk_firm_taxable_profit(firms.assign(firm_id=1), source) + with pytest.raises(ValueError, match="ons_legal_status or firm_legal_form"): + assign_uk_firm_taxable_profit(firms.drop(columns="ons_legal_status"), source) + with pytest.raises(ValueError, match="annual_turnover_k or firm_turnover"): + assign_uk_firm_taxable_profit(firms.drop(columns="annual_turnover_k"), source) + + +def test_source_refusals(tmp_path) -> None: + text = (FIXTURE / UK_FIRM_PROFIT_FILE).read_text(encoding="utf-8") + path = tmp_path / UK_FIRM_PROFIT_FILE + path.write_text(text.replace("band,lower_gbp", "bands,lower_gbp"), "utf-8") + with pytest.raises(ValueError, match="columns"): + read_uk_firm_profit_source(tmp_path) + path.write_text( + text.replace(">50m,50000000,,", ">50m,50000000,900000000,"), "utf-8" + ) + with pytest.raises(ValueError, match="open band"): + read_uk_firm_profit_source(path) + path.write_text(text.replace(">5m-10m,5000000,", ">5m-10m,6000000,"), "utf-8") + with pytest.raises(ValueError, match="does not follow on"): + read_uk_firm_profit_source(path) + + +def test_status_is_assumed() -> None: + assert UK_FIRM_PROFIT_STATUS == "assumed" diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_public_sector.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_public_sector.py new file mode 100644 index 0000000000..5944ff142e --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_public_sector.py @@ -0,0 +1,355 @@ +"""UK firm public sector employment: an opt-in rescale to ONS headcounts.""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import sys +from functools import cache + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.uk_runtime.firm_public_sector import ( + UK_FIRM_PUBLIC_SECTOR_FILE, + UK_FIRM_PUBLIC_SECTOR_PERIOD, + UK_FIRM_PUBLIC_SECTOR_SERIES, + UK_FIRM_PUBLIC_SECTOR_SOURCE_COLUMNS, + UK_FIRM_PUBLIC_SECTOR_STATUS, + UK_FIRM_PUBLIC_SECTOR_STATUSES, + UKFirmPublicSectorSource, + read_uk_firm_public_sector_source, + scale_uk_firm_public_sector_employment, + uk_firm_public_sector_diagnostics, +) +from test_support.paths import paths_for + +PATHS = paths_for("microcosm-build") +FIXTURE = PATHS.tests / "fixtures" / "uk" / "firm_public_sector_2025" +CSV = FIXTURE / UK_FIRM_PUBLIC_SECTOR_FILE +PROVENANCE = FIXTURE / (UK_FIRM_PUBLIC_SECTOR_FILE + ".provenance.json") +TOOL = PATHS.repository / "tools" / "extract_uk_firm_public_sector_table.py" + +#: ONS Public sector employment, UK: March 2025, Table 1, row Mar 2025 +#: (thousands, seasonally adjusted), read off the workbook. +_CENTRAL_THOUSAND = 4020 +_LOCAL_THOUSAND = 1977 + + +@cache +def _source() -> UKFirmPublicSectorSource: + return read_uk_firm_public_sector_source(FIXTURE) + + +@cache +def _provenance() -> dict: + return json.loads(PROVENANCE.read_text(encoding="utf-8")) + + +@cache +def _load_tool(): + name = "extract_uk_firm_public_sector_table" + 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 _firms(seed: int = 7) -> pd.DataFrame: + """A small generator-like frame with every ONS legal status.""" + + rng = np.random.default_rng(seed) + status = np.array( + [1] * 40 + [2] * 10 + [3] * 5 + [4] * 3 + [5] * 12 + [6] * 25 + [7] * 5 + ) + rows = len(status) + return pd.DataFrame( + { + "firm_id": np.arange(1, rows + 1), + "employment": rng.integers(1, 400, size=rows).astype(np.int64), + "firm_weight": rng.uniform(0.5, 9.0, size=rows), + "ons_legal_status": status, + "turnover": rng.uniform(10.0, 5000.0, size=rows), + }, + index=np.arange(100, 100 + rows), + ) + + +def _weighted(frame: pd.DataFrame, status: int, column: str = "employment") -> float: + rows = frame["ons_legal_status"] == status + return float((frame.loc[rows, "firm_weight"] * frame.loc[rows, column]).sum()) + + +def test_fixture_reads_as_the_published_headcounts() -> None: + source = _source() + + assert dict(source.headcount) == { + 5: _CENTRAL_THOUSAND * 1000.0, + 6: _LOCAL_THOUSAND * 1000.0, + } + assert dict(source.series) == {5: "G6NQ", 6: "G6NT"} + assert source.period == UK_FIRM_PUBLIC_SECTOR_PERIOD == "Mar 2025" + assert source.file == UK_FIRM_PUBLIC_SECTOR_FILE + assert source.sha256 == hashlib.sha256(CSV.read_bytes()).hexdigest() + assert read_uk_firm_public_sector_source(CSV) == source + assert UK_FIRM_PUBLIC_SECTOR_STATUS == "assumed" + + +def test_fixture_csv_layout() -> None: + frame = pd.read_csv(CSV, dtype=str, keep_default_na=False) + + assert tuple(frame.columns) == UK_FIRM_PUBLIC_SECTOR_SOURCE_COLUMNS + assert frame["sector"].tolist() == list(UK_FIRM_PUBLIC_SECTOR_STATUSES) + assert frame["series_id"].tolist() == list(UK_FIRM_PUBLIC_SECTOR_SERIES.values()) + assert sorted(path.name for path in FIXTURE.iterdir()) == [ + CSV.name, + PROVENANCE.name, + ] + + +def test_provenance_is_well_formed() -> None: + record = _provenance() + source = record["source"] + + assert record["kind"] == "uk_firm_public_sector_employment_fixture" + assert record["accessed"] == "2026-11-22" + assert "none was filled from memory" in record["method"] + assert source["landing_page"].startswith("https://www.ons.gov.uk/") + assert source["url"].startswith("https://www.ons.gov.uk/file?uri=") + assert source["url"].endswith("/march2025/datasets8.xlsx") + assert "Public sector employment, UK: March 2025" in source["edition"] + assert len(source["sha256"]) == 64 + int(source["sha256"], 16) + assert source["sheet"] == "Table 1" + assert "seasonally adjusted" in source["table"] + assert source["series"] == dict(UK_FIRM_PUBLIC_SECTOR_SERIES) + assert "not the dataset's latest" in record["edition_note"] + entry = record["files"][UK_FIRM_PUBLIC_SECTOR_FILE] + payload = CSV.read_bytes() + assert entry["sha256"] == hashlib.sha256(payload).hexdigest() + assert entry["bytes"] == len(payload) + assert entry["columns"] == list(UK_FIRM_PUBLIC_SECTOR_SOURCE_COLUMNS) + later = record["later_edition"] + assert len(later["sha256"]) == 64 and later["sha256"] != source["sha256"] + assert set(later["headcount_thousand"]) == set(UK_FIRM_PUBLIC_SECTOR_STATUSES) + + +def test_tool_names_the_fixture_and_rebuilds_its_bytes() -> None: + tool = _load_tool() + record = _provenance() + + assert tool.CSV_NAME == UK_FIRM_PUBLIC_SECTOR_FILE + assert tool.PROVENANCE_NAME == PROVENANCE.name + assert tool.DEFAULT_OUT == FIXTURE + assert tool.HEADER == UK_FIRM_PUBLIC_SECTOR_SOURCE_COLUMNS + assert tool.XLSX_URL == record["source"]["url"] + assert tool.LANDING_PAGE == record["source"]["landing_page"] + assert tool.PERIOD == UK_FIRM_PUBLIC_SECTOR_PERIOD + assert {(s, c, i) for s, c, i, _ in tool.SECTORS} == { + (sector, code, UK_FIRM_PUBLIC_SECTOR_SERIES[sector]) + for sector, code in UK_FIRM_PUBLIC_SECTOR_STATUSES.items() + } + # The sheet's shape, cut to the cells the extractor reads. + sheet = [ + (tool.TITLE_PREFIX + " 1 2 3", None, None, None), + (None, None, None, " " + tool.UNITS), + ( + None, + "Central \ngovernment 4", + "Local\ngovernment 4 ", + "Total general government", + ), + (None, None, None, None), + (None, "G6NQ", "G6NT", "G6NW"), + ("Dec 2024 [r]", 4001, 1986, 5987), + ("Mar 2025", _CENTRAL_THOUSAND, _LOCAL_THOUSAND, 5997), + ("Change on quarter", 19, -9, 10), + ] + rows = tool.extract_rows(sheet) + assert tool.to_csv_bytes(rows) == CSV.read_bytes() + + with pytest.raises(ValueError, match="found 0x"): + tool.extract_rows([row for row in sheet if row[0] != "Mar 2025"]) + swapped = [*sheet] + swapped[4] = (None, "G6NT", "G6NQ", "G6NW") + with pytest.raises(ValueError, match="sits under"): + tool.extract_rows(swapped) + + +def test_scaling_hits_the_published_totals_with_whole_headcounts() -> None: + firms = _firms() + source = _source() + + scaled = scale_uk_firm_public_sector_employment(firms, source) + + for status in (5, 6): + rows = scaled["ons_legal_status"] == status + largest_weight = float(scaled.loc[rows, "firm_weight"].max()) + miss = abs(_weighted(scaled, status) - source.headcount[status]) + assert miss <= largest_weight / 2 + 1e-6 + assert miss / source.headcount[status] < 1e-5 + assert int(scaled.loc[rows, "employment"].min()) >= 1 + assert scaled["employment"].dtype == firms["employment"].dtype + + +def test_scaling_keeps_rows_and_everything_else() -> None: + firms = _firms() + before = firms.copy(deep=True) + + scaled = scale_uk_firm_public_sector_employment(firms, _source()) + + pd.testing.assert_frame_equal(firms, before) + assert len(scaled) == len(firms) + assert scaled.index.equals(firms.index) + assert list(scaled.columns) == list(firms.columns) + pd.testing.assert_frame_equal( + scaled.drop(columns="employment"), firms.drop(columns="employment") + ) + others = ~firms["ons_legal_status"].isin([5, 6]) + assert others.sum() == 63 + pd.testing.assert_series_equal( + scaled.loc[others, "employment"], firms.loc[others, "employment"] + ) + assert _weighted(scaled, 4) == _weighted(firms, 4) + # One factor per status keeps the order of headcounts within it. + for status in (5, 6): + rows = firms["ons_legal_status"] == status + order = np.argsort(firms.loc[rows, "employment"].to_numpy(), kind="stable") + assert np.all(np.diff(scaled.loc[rows, "employment"].to_numpy()[order]) >= 0) + + +def test_scaling_is_deterministic() -> None: + firms = _firms() + source = _source() + + first = scale_uk_firm_public_sector_employment(firms, source) + second = scale_uk_firm_public_sector_employment(firms.copy(), source) + pd.testing.assert_frame_equal(first, second) + + +def test_scaling_can_shrink_and_never_goes_below_one() -> None: + firms = pd.DataFrame( + { + "employment": np.array([900_000, 3, 1, 700_000, 2, 5], dtype=np.int64), + "firm_weight": [10.0, 4.0, 2.0, 8.0, 3.0, 1.0], + "ons_legal_status": [5, 5, 5, 6, 6, 1], + } + ) + + scaled = scale_uk_firm_public_sector_employment(firms, _source()) + + assert scaled["employment"].tolist()[1:3] == [1, 1] + assert scaled["employment"].tolist()[4:] == [1, 5] + assert scaled["employment"].iloc[0] < 900_000 + assert scaled["employment"].iloc[3] < 700_000 + + +def test_scaling_reads_a_named_headcount_column() -> None: + firms = _firms().rename(columns={"employment": "firm_employees"}) + source = _source() + + scaled = scale_uk_firm_public_sector_employment( + firms, source, employment_column="firm_employees" + ) + + assert _weighted(scaled, 5, "firm_employees") == pytest.approx( + source.headcount[5], rel=1e-5 + ) + with pytest.raises(ValueError, match="needs columns"): + scale_uk_firm_public_sector_employment(firms, source) + + +def test_diagnostics_report_before_and_after() -> None: + firms = _firms() + source = _source() + + report = uk_firm_public_sector_diagnostics(firms, source) + scaled = scale_uk_firm_public_sector_employment(firms, source) + + assert report["status"] == "assumed" + assert report["source_sha256"] == source.sha256 + assert report["rows"] == len(firms) + assert list(report["sectors"]) == list(UK_FIRM_PUBLIC_SECTOR_STATUSES) + for sector, status in UK_FIRM_PUBLIC_SECTOR_STATUSES.items(): + entry = report["sectors"][sector] + rows = firms["ons_legal_status"] == status + assert entry["ons_legal_status"] == status + assert entry["series_id"] == UK_FIRM_PUBLIC_SECTOR_SERIES[sector] + assert entry["rows"] == int(rows.sum()) + assert entry["target_weighted_employment"] == source.headcount[status] + assert entry["weighted_employment_before"] == pytest.approx( + _weighted(firms, status) + ) + assert entry["weighted_employment_after"] == pytest.approx( + _weighted(scaled, status) + ) + assert entry["scale_factor"] == pytest.approx( + source.headcount[status] / _weighted(firms, status) + ) + assert entry["largest_headcount_after"] == int( + scaled.loc[rows, "employment"].max() + ) + assert report["total_weighted_employment_after"] == pytest.approx( + float((scaled["firm_weight"] * scaled["employment"]).sum()) + ) + json.dumps(report) + + +@pytest.mark.parametrize("status", [5, 6]) +def test_scaling_refuses_a_frame_without_a_status(status: int) -> None: + firms = _firms() + firms = firms[firms["ons_legal_status"] != status] + + with pytest.raises(ValueError, match=f"no rows with ons_legal_status {status}"): + scale_uk_firm_public_sector_employment(firms, _source()) + with pytest.raises(ValueError, match=f"no rows with ons_legal_status {status}"): + uk_firm_public_sector_diagnostics(firms, _source()) + + +def test_scaling_refuses_bad_frames() -> None: + firms = _firms() + source = _source() + + with pytest.raises(ValueError, match="needs columns"): + scale_uk_firm_public_sector_employment( + firms.drop(columns="firm_weight"), source + ) + with pytest.raises(ValueError, match="whole numbers"): + scale_uk_firm_public_sector_employment( + firms.assign(employment=firms["employment"] + 0.5), source + ) + with pytest.raises(ValueError, match="firm_weight"): + scale_uk_firm_public_sector_employment( + firms.assign(firm_weight=-firms["firm_weight"]), source + ) + empty = firms.assign( + employment=firms["employment"].where(firms["ons_legal_status"] != 5, 0) + ) + with pytest.raises(ValueError, match="cannot scale ons_legal_status 5"): + scale_uk_firm_public_sector_employment(empty, source) + + +def test_reader_refuses_malformed_sources(tmp_path) -> None: + text = CSV.read_text(encoding="utf-8") + cases = { + "columns": text.replace("headcount_thousand", "headcount"), + "once each": text.replace("local_government", "central_government"), + "ons_legal_status": text.replace( + "central_government,5", "central_government,6" + ), + "series": text.replace("G6NQ", "G7AR"), + "period": text.replace("Mar 2025", "Jun 2025", 1), + "not a number": text.replace(str(_CENTRAL_THOUSAND), "x"), + "positive": text.replace(str(_LOCAL_THOUSAND), "0"), + } + for match, payload in cases.items(): + path = tmp_path / UK_FIRM_PUBLIC_SECTOR_FILE + path.write_text(payload, encoding="utf-8") + with pytest.raises(ValueError, match=match): + read_uk_firm_public_sector_source(tmp_path) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_rateable_value.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_rateable_value.py new file mode 100644 index 0000000000..0c070231ed --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_rateable_value.py @@ -0,0 +1,389 @@ +"""UK firm rateable value: VOA 2023-list band fixture and the assumed mapping.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import importlib.util +import io +import json +import sys +import zipfile +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.uk_runtime.firm_rateable_value import ( + UK_FIRM_RATEABLE_VALUE_FILE, + UK_FIRM_RATEABLE_VALUE_SOURCE_COLUMNS, + UK_FIRM_RATEABLE_VALUE_STATUS, + assign_uk_firm_rateable_value, + read_uk_firm_rateable_value_source, + uk_firm_rateable_value_of_top, + uk_firm_rateable_value_summary, +) +from test_support.paths import paths_for + +PATHS = paths_for("microcosm-build") +FIXTURE = PATHS.tests / "fixtures" / "uk" / "firm_rateable_value_2024" +TOOL = PATHS.repository / "tools" / "extract_uk_firm_rateable_value_tables.py" + +#: VOA stock of properties, March 2026, Tables SOP2.1-SOP2.3 ``Total`` rows, +#: all sectors: (hereditaments, total rateable value in GBP thousand). +_TOTALS = { + "england_and_wales": (2138260, 70853994), + "england": (2013470, 68437352), + "wales": (124790, 2416641), +} +#: England, all sectors, read off Table SOP2.2. +_ENGLAND_BANDS = { + "0 - 999": (144660, 70131), + "12,001 - 13,999": (77680, 1006689), + "50,000 - 50,999": (4370, 219463), + "1,000,000 and over": (6790, 16070230), +} + + +def _load_tool(): + name = "extract_uk_firm_rateable_value_tables" + 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 _provenance() -> dict: + return json.loads((FIXTURE / ".provenance.json").read_text(encoding="utf-8")) + + +def _bands() -> pd.DataFrame: + return pd.read_csv( + FIXTURE / UK_FIRM_RATEABLE_VALUE_FILE, dtype=str, keep_default_na=False + ) + + +def _source(): + return read_uk_firm_rateable_value_source(FIXTURE) + + +def test_band_fixture_holds_the_published_totals_and_bands() -> None: + frame = _bands() + assert tuple(frame.columns) == UK_FIRM_RATEABLE_VALUE_SOURCE_COLUMNS + everything = frame[frame["sector"] == "all"].set_index(["geography", "rv_band"]) + for geography, (count, value) in _TOTALS.items(): + row = everything.loc[(geography, "Total")] + assert (int(row["hereditaments"]), int(row["total_rv_gbp_thousand"])) == ( + count, + value, + ) + for band, (count, value) in _ENGLAND_BANDS.items(): + row = everything.loc[("england", band)] + assert (int(row["hereditaments"]), int(row["total_rv_gbp_thousand"])) == ( + count, + value, + ) + + +def test_band_fixture_adds_up_within_the_source_rounding() -> None: + """Bands sum to the ``Total`` row and sectors to ``all``, to the VOA's + rounding (counts to the nearest ten, values to the nearest thousand).""" + + frame = _bands().astype( + {"hereditaments": np.int64, "total_rv_gbp_thousand": np.int64} + ) + numbers = ["hereditaments", "total_rv_gbp_thousand"] + for (_, sector), rows in frame.groupby(["geography", "sector"]): + total = rows[rows["rv_band"] == "Total"][numbers].iloc[0] + summed = rows[rows["rv_band"] != "Total"][numbers].sum() + assert len(rows) == 19, sector + assert abs(summed["hereditaments"] - total["hereditaments"]) <= 100 + assert ( + abs(summed["total_rv_gbp_thousand"] - total["total_rv_gbp_thousand"]) < 20 + ) + for _, rows in frame.groupby(["geography", "rv_band"]): + by_sector = rows.set_index("sector") + parts = by_sector.loc[["retail", "offices", "industry", "other"], numbers].sum() + assert abs(parts["hereditaments"] - by_sector.loc["all", "hereditaments"]) <= 40 + assert ( + abs( + parts["total_rv_gbp_thousand"] + - by_sector.loc["all", "total_rv_gbp_thousand"] + ) + < 5 + ) + + +def test_property_type_and_year_fixtures_agree_with_the_band_table() -> None: + types = pd.read_csv( + FIXTURE / "voa_property_type.csv", dtype=str, keep_default_na=False + ) + years = pd.read_csv(FIXTURE / "voa_stock_by_year.csv", dtype=str) + for geography, (count, value) in _TOTALS.items(): + row = types[(types["geography"] == geography) & (types["level"] == "all")] + assert row["hereditaments"].tolist() == [str(count)] + assert row["total_rv_gbp_thousand"].tolist() == [str(value)] + latest = years[ + (years["geography"] == geography) & (years["as_at"] == "2026-03-31") + ] + assert latest["hereditaments"].tolist() == [str(count)] + assert latest["total_rv_gbp_thousand"].tolist() == [str(value)] + assert sorted(years["as_at"].unique()) == ["2024-03-31", "2025-03-31", "2026-03-31"] + assert set(types["level"]) == {"all", "sector", "sub_sector", "shop_type"} + # A suppressed row keeps its marker and no numbers; it is never a zero. + suppressed = types[types["marker"] != ""] + assert suppressed["marker"].tolist() == ["[c]"] + assert suppressed[["geography", "prop_type_code"]].values.tolist() == [ + ["wales", "CS8"] + ] + assert (suppressed["hereditaments"] == "").all() + assert (types.loc[types["marker"] == "", "hereditaments"] != "").all() + sectors = types[(types["geography"] == "england") & (types["level"] == "sector")] + assert sectors["prop_type_code"].tolist() == ["C", "E", "U", "I", "L", "M"] + + +def test_provenance_records_the_download_and_the_rating_list() -> None: + record = _provenance() + tool = _load_tool() + source = record["source"] + assert record["accessed"] == "2026-11-22" == tool.ACCESS_DATE + assert "2023 rating list" in record["rating_list"] + assert source["url"] == tool.ZIP_URL + assert source["url"].startswith("https://assets.publishing.service.gov.uk/media/") + assert source["landing_page"] == tool.LANDING_PAGE + assert "March 2026" in source["edition"] + assert len(source["sha256"]) == 64 + assert record["method"] + assert set(record["files"]) == { + "voa_rv_band_sector.csv", + "voa_property_type.csv", + "voa_stock_by_year.csv", + } + for name, entry in record["files"].items(): + payload = (FIXTURE / name).read_bytes() + assert entry["sha256"] == hashlib.sha256(payload).hexdigest() + assert entry["bytes"] == len(payload) + assert entry["rows"] == payload.count(b"\n") - 1 + + +def _member(header: list[str], rows: list[list[str]]) -> bytes: + buffer = io.StringIO() + writer = csv.writer(buffer, quoting=csv.QUOTE_ALL, lineterminator="\n") + writer.writerow(header) + writer.writerows(rows) + return ("" + buffer.getvalue()).encode("utf-8") + + +def _bundle(path: Path, suppressed: str = "[c]") -> Path: + """A zip shaped like the VOA bundle, with made-up small tables.""" + + sectors = ["all", "retail", "offices", "industry", "other"] + band_header = ["rv_band"] + [ + f"{kind}_{sector}" for sector in sectors for kind in ("count", "total_rv") + ] + band_rows = [ + ["0 - 999", *["20", "8"] * 5], + ["1,000 and over", *["30", "90"] * 5], + ["Total", *["50", "98"] * 5], + ] + type_header = ["prop_type_code", "description"] + [ + f"{name}_{suffix}" + for suffix in ("engwal", "eng", "wal") + for name in ("count", "total_rv", "mean_rv", "median_rv") + ] + full = ["50", "98", "2", "1.5"] + type_rows = [ + ["[z]", "All Properties", *full * 3], + ["C", "Commercial", *full * 3], + ["CS", "Shops", *full * 3], + ["CS8", "Hypermarket and premises", *full * 2, *[suppressed] * 4], + ] + year_header = ["geography", "abolished_year", "ba_code", "area_code", "area_name"] + year_header += ["2023", "2024", "2025", "2026"] + year_rows = [ + ["ENGWAL", "[z]", "[z]", "K04000001", "England and Wales", "1", "2", "3", "4"], + ["NATL", "[z]", "[z]", "E92000001", "England", "1", "2", "3", "4"], + ["NATL", "[z]", "[z]", "W92000004", "Wales", "1", "2", "3", "4"], + ] + with zipfile.ZipFile(path, "w") as archive: + for name in ("table_SOP2_1.csv", "table_SOP2_2.csv", "table_SOP2_3.csv"): + archive.writestr(name, _member(band_header, band_rows)) + archive.writestr("table_SOP1_2.csv", _member(type_header, type_rows)) + archive.writestr("table_SOP3_1.csv", _member(year_header, year_rows)) + archive.writestr("table_SOP3_2.csv", _member(year_header, year_rows)) + return path + + +def test_tool_extracts_checks_and_refuses_a_bad_cell(tmp_path: Path, capsys) -> None: + tool = _load_tool() + bundle = _bundle(tmp_path / "bundle.zip") + out = tmp_path / "out" + + assert tool.main(["--zip", str(bundle), "--out", str(out)]) == 0 + assert tool.main(["--zip", str(bundle), "--out", str(out), "--check"]) == 0 + bands = (out / "voa_rv_band_sector.csv").read_text(encoding="utf-8").splitlines() + assert bands[0] == ",".join(UK_FIRM_RATEABLE_VALUE_SOURCE_COLUMNS) + assert bands[1] == "england_and_wales,0 - 999,0,999,all,20,8" + assert 'england,"1,000 and over",1000,,all,30,90' in bands + assert "wales,Total,,,other,50,98" in bands + types = (out / "voa_property_type.csv").read_text(encoding="utf-8").splitlines() + assert "england,CS8,CS,shop_type,Hypermarket and premises,50,98,2,1.5," in types + assert "wales,CS8,CS,shop_type,Hypermarket and premises,,,,,[c]" in types + assert "wales,CS,C,sub_sector,Shops,50,98,2,1.5," in types + years = (out / "voa_stock_by_year.csv").read_text(encoding="utf-8").splitlines() + assert years[1:4] == [ + "england_and_wales,2024-03-31,2,2", + "england_and_wales,2025-03-31,3,3", + "england_and_wales,2026-03-31,4,4", + ] + record = json.loads((out / ".provenance.json").read_text(encoding="utf-8")) + assert record["source"]["sha256"] == hashlib.sha256(bundle.read_bytes()).hexdigest() + + (out / "voa_stock_by_year.csv").write_text("stale\n", encoding="utf-8") + assert tool.main(["--zip", str(bundle), "--out", str(out), "--check"]) == 1 + assert "voa_stock_by_year.csv" in capsys.readouterr().err + + with pytest.raises(ValueError, match="not a whole number"): + tool.extract(_bundle(tmp_path / "bad.zip", suppressed="x")) + with pytest.raises(argparse.ArgumentTypeError, match="YYYY-MM-DD"): + tool._iso_date("22 November 2026") + + +def test_source_reads_england_bands_largest_first() -> None: + source = _source() + + assert UK_FIRM_RATEABLE_VALUE_STATUS == "assumed" + assert len(source.bands) == 18 + assert source.bands[0] == "1,000,000 and over" + assert source.bands[-1] == "0 - 999" + assert source.upper_gbp[0] == float("inf") + assert source.lower_gbp[0] == 1_000_000.0 + assert source.published_hereditaments == _TOTALS["england"][0] + assert source.published_total_rv_gbp == _TOTALS["england"][1] * 1e3 + assert abs(source.n_hereditaments - source.published_hereditaments) <= 100 + assert abs(source.total_gbp - source.published_total_rv_gbp) < 20e3 + payload = (FIXTURE / UK_FIRM_RATEABLE_VALUE_FILE).read_bytes() + assert source.sha256 == hashlib.sha256(payload).hexdigest() + + +def test_source_refuses_a_malformed_table(tmp_path: Path) -> None: + frame = _bands() + with pytest.raises(ValueError, match="columns"): + frame.drop(columns="sector").to_csv(tmp_path / "a.csv", index=False) + read_uk_firm_rateable_value_source(tmp_path / "a.csv") + england_all = (frame["geography"] == "england") & (frame["sector"] == "all") + no_total = frame[~(england_all & (frame["rv_band"] == "Total"))] + no_total.to_csv(tmp_path / "b.csv", index=False) + with pytest.raises(ValueError, match="Total"): + read_uk_firm_rateable_value_source(tmp_path / "b.csv") + closed = frame.copy() + closed.loc[england_all & (closed["band_upper_gbp"] == ""), "band_upper_gbp"] = "9" + closed.loc[england_all & (closed["rv_band"] == "Total"), "band_upper_gbp"] = "" + closed.to_csv(tmp_path / "c.csv", index=False) + with pytest.raises(ValueError, match="ascend"): + read_uk_firm_rateable_value_source(tmp_path / "c.csv") + + +def test_value_of_top_returns_each_band_total_and_stays_in_bounds() -> None: + source = _source() + edges = np.cumsum(source.hereditaments) + + np.testing.assert_allclose( + uk_firm_rateable_value_of_top(source, edges), + np.cumsum(source.total_rv_gbp), + rtol=1e-12, + ) + assert uk_firm_rateable_value_of_top(source, np.array([0.0]))[0] == 0.0 + beyond = uk_firm_rateable_value_of_top(source, np.array([edges[-1] * 3]))[0] + assert beyond == pytest.approx(source.total_gbp) + # One hereditament at a time down the first 400,000: values fall with + # rank, and each sits inside its band. + ranks = np.arange(0.0, 400_001.0) + each = np.diff(uk_firm_rateable_value_of_top(source, ranks)) + assert np.all(np.diff(each) <= 1e-3) + band = np.searchsorted(edges, ranks[1:], side="left") + lower = np.asarray(source.lower_gbp)[band] + upper = np.asarray(source.upper_gbp)[band] + assert np.all(each >= lower - 1e-3) + assert np.all(each <= upper + 1e-3) + + +def _firms(n: int, weight: float, seed: int = 7) -> pd.DataFrame: + rng = np.random.default_rng(seed) + return pd.DataFrame( + { + "firm_employees": rng.integers(0, 400, size=n), + "firm_weight": np.full(n, weight), + "firm_in_england": rng.random(n) < 0.85, + } + ) + + +def test_assignment_follows_headcount_rank_and_conserves_the_stock() -> None: + source = _source() + firms = _firms(5_000, 800.0) + value = assign_uk_firm_rateable_value(firms, source) + england = firms["firm_in_england"].to_numpy() + weight = firms["firm_weight"].to_numpy() + + assert value.shape == (len(firms),) + assert np.all(value[~england] == 0.0) + # 5,000 x 0.85 x 800 weighted firms exceed the 2.01 million hereditaments, + # so all of England's rateable value is handed out and the smallest get 0. + assert weight[england].sum() > source.n_hereditaments + assert (weight * value).sum() == pytest.approx(source.total_gbp, rel=1e-9) + with_property = weight[value > 0].sum() + assert source.n_hereditaments <= with_property < source.n_hereditaments + 800.0 + by_size = firms[england].assign(value=value[england]).sort_values("firm_employees") + means = by_size.groupby("firm_employees")["value"].agg(["min", "max"]) + # Up to float noise from differencing cumulative totals. + smaller = means["max"].to_numpy()[:-1] + assert np.all(means["min"].to_numpy()[1:] >= smaller * (1 - 1e-6) - 1e-3) + summary = uk_firm_rateable_value_summary(firms, source) + assert summary["weighted_rateable_value_gbp"] == pytest.approx(source.total_gbp) + assert summary["weighted_firms_with_property"] == with_property + assert summary["weighted_firms_in_england"] == weight[england].sum() + + +def test_assignment_with_fewer_firms_than_hereditaments_takes_the_top() -> None: + source = _source() + firms = pd.DataFrame( + { + "employment": [5, 900, 40, 40, 0], + "firm_in_england": [True, True, True, False, True], + } + ) + value = assign_uk_firm_rateable_value(firms, source) + + top_band_mean = source.total_rv_gbp[0] / source.hereditaments[0] + assert value[3] == 0.0 + # Four England firms, unweighted, take the four most valuable + # hereditaments, all in the flat open top band. + assert value[[0, 1, 2, 4]] == pytest.approx(np.full(4, top_band_mean)) + + +def test_assignment_is_seeded_and_validates_its_inputs() -> None: + source = _source() + firms = _firms(2_000, 1_500.0) + firms["firm_employees"] = 3 + + first = assign_uk_firm_rateable_value(firms, source) + np.testing.assert_array_equal(first, assign_uk_firm_rateable_value(firms, source)) + other = assign_uk_firm_rateable_value(firms, source, seed=1) + assert not np.array_equal(first, other) + assert (firms["firm_weight"] * other).sum() == pytest.approx(source.total_gbp) + + with pytest.raises(ValueError, match="firm_in_england"): + assign_uk_firm_rateable_value(firms.drop(columns="firm_in_england"), source) + with pytest.raises(ValueError, match="firm_employees or employment"): + assign_uk_firm_rateable_value(firms.drop(columns="firm_employees"), source) + with pytest.raises(ValueError, match="non-negative"): + assign_uk_firm_rateable_value(firms.assign(firm_weight=-1.0), source) + empty = assign_uk_firm_rateable_value(firms.assign(firm_in_england=False), source) + assert np.all(empty == 0.0) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_rd_tax_credits.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_rd_tax_credits.py new file mode 100644 index 0000000000..0cbfbc8a29 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_rd_tax_credits.py @@ -0,0 +1,249 @@ +"""UK firm R&D: an opt-in allocation of HMRC R&D tax credit claims.""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import sys +from functools import cache + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.uk_runtime.firm_rd_tax_credits import ( + UK_FIRM_RD_FILES, + UK_FIRM_RD_SECTIONS, + UK_FIRM_RD_STATUS, + UKFirmRDSource, + assign_uk_firm_rd_tax_credits, + draw_uk_firm_rd_tax_credits, + read_uk_firm_rd_source, + uk_firm_rd_expenditure_table, +) +from test_support.paths import paths_for + +PATHS = paths_for("microcosm-build") +FIXTURE = PATHS.tests / "fixtures" / "uk" / "firm_rd_tax_credits_2024_25" +TOOL = PATHS.repository / "tools" / "extract_uk_firm_rd_tax_credits_tables.py" + + +@cache +def _source() -> UKFirmRDSource: + return read_uk_firm_rd_source(FIXTURE) + + +@cache +def _tool(): + name = "extract_uk_firm_rd_tax_credits_tables" + 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 _firms(rows_per_section: int = 400, seed: int = 3) -> pd.DataFrame: + rng = np.random.default_rng(seed) + sections = np.repeat(np.array(UK_FIRM_RD_SECTIONS), rows_per_section) + n = sections.size + employees = np.floor(rng.lognormal(2.0, 1.5, n)) + return pd.DataFrame( + { + "firm_id": np.arange(n) * 7 + 11, + "firm_weight": rng.uniform(5.0, 60.0, n), + "firm_sic_section": sections, + "firm_employees": employees, + "firm_turnover": 80_000.0 * (1.0 + employees) * rng.uniform(0.5, 2.0, n), + "ons_legal_status": rng.choice([1, 1, 1, 2, 3], n), + } + ) + + +def test_source_reads_published_2024_25_totals() -> None: + source = _source() + manufacturing = source.sections["C"] + assert manufacturing.claims == 11_090 + assert manufacturing.expenditure_gbp == 14_195e6 + assert source.sections["L"].claims == 40 + assert source.unknown_claims == 95 + assert source.unknown_expenditure_gbp == 135e6 + assert source.national_claims == 40_325 + assert source.national_companies == 37_545 + assert source.national_expenditure_gbp["all_schemes"] == 50_970e6 + # Independent rounding to 5: the sections plus unknown miss RD1/RD4 by 5. + claims = sum(s.claims for s in source.sections.values()) + source.unknown_claims + spend = sum(s.expenditure_gbp for s in source.sections.values()) + assert claims == pytest.approx(source.national_claims, abs=5) + assert abs(spend + source.unknown_expenditure_gbp - 50_970e6) <= 10e6 + + +def test_provenance_hashes_match_fixture() -> None: + record = json.loads((FIXTURE / "provenance.json").read_text(encoding="utf-8")) + assert record["accessed"] == "2026-11-23" + assert "none was filled from memory" in record["method"].lower() + assert record["source"]["sha256"] == ( + "efc2238695c40dc4273acc8846f9057bbe582ff04c951c75085c32632c004324" + ) + for name in UK_FIRM_RD_FILES: + payload = (FIXTURE / name).read_bytes() + assert record["files"][name]["sha256"] == hashlib.sha256(payload).hexdigest() + + +def test_extract_table_rejects_moved_header() -> None: + tool = _tool() + spec = tool.RD4 + rows = [ + (spec[2] + ", 2016-17 to 2024-25 (£ million)",), + tuple(reversed(spec[3])), + ] + with pytest.raises(ValueError, match="header row"): + tool.extract_table(rows, spec) + + +def test_extract_table_keeps_published_text() -> None: + tool = _tool() + spec = tool.RD6 + labels = [f"{letter}. Sector {letter}" for letter in tool.RD6_SECTIONS] + body = [(label, "1,234", "<5", "N/A", None) for label in labels] + rows = [ + (spec[2],), + spec[3], + *body, + (tool.RD6_UNKNOWN, 5.0), + ("End of worksheet",), + ] + out = tool.extract_table(rows, spec) + assert out[0][:6] == ["A. Sector A", "1,234", "<5", "N/A", "", ""] + assert out[-1][:2] == [tool.RD6_UNKNOWN, "5"] + + +def test_expenditure_table_rakes_to_rd6_and_rd4() -> None: + source = _source() + table = uk_firm_rd_expenditure_table(source) + for letter, spec in source.sections.items(): + assert table.loc[letter].sum() == pytest.approx(spec.expenditure_gbp) + sections = sum(s.expenditure_gbp for s in source.sections.values()) + large_share = 30_245e6 / (30_245e6 + 20_725e6) + assert table["large"].sum() == pytest.approx(sections * large_share) + assert source.national_large_expenditure_gbp == 30_245e6 + assert source.national_sme_expenditure_gbp == 20_725e6 + assert source.sections["C"].large_claims == 1_100 + 215 + # Suppressed large cells count as 0: section L has no large claims. + assert source.sections["L"].large_claims == 0 + assert table.at["L", "large"] == 0 + + +def test_strata_and_expenditure_match_targets() -> None: + firms = _firms(rows_per_section=1_000) + firms["firm_turnover"] *= 100.0 + draw = draw_uk_firm_rd_tax_credits(firms, _source(), seed=7) + d = draw.diagnostics + weight = firms["firm_weight"].to_numpy() + assert d["status"] == UK_FIRM_RD_STATUS + assert d["companies_per_claim"] == pytest.approx(37_545 / 40_325) + for row in d["sections"]: + for stratum in ("large", "sme"): + if not row[f"{stratum}_draw_capped"]: + assert ( + abs( + row[f"{stratum}_weighted_claimants"] + - row[f"{stratum}_target_companies"] + ) + <= 30.0 + ) + assert row[f"{stratum}_model_expenditure_gbp"] + row[ + f"{stratum}_unallocated_gbp" + ] == pytest.approx(row[f"{stratum}_target_expenditure_gbp"]) + assert d["unallocated_expenditure_gbp"] == pytest.approx(0.0, abs=1.0) + assert d["model_large_expenditure_gbp"] + d[ + "model_sme_expenditure_gbp" + ] == pytest.approx(d["hmrc_section_expenditure_gbp"]) + company = firms["ons_legal_status"].to_numpy() == 1 + assert not draw.claimant[~company].any() + assert (draw.qualifying_rd_expenditure[~draw.claimant] == 0).all() + assert float(np.dot(weight, draw.qualifying_rd_expenditure)) == pytest.approx( + d["model_expenditure_gbp"] + ) + + +def test_expenditure_never_exceeds_turnover_and_remainder_is_reported() -> None: + firms = _firms() + draw = draw_uk_firm_rd_tax_credits(firms, _source(), seed=7) + turnover = firms["firm_turnover"].to_numpy() + assert (draw.qualifying_rd_expenditure <= turnover * (1 + 1e-12)).all() + d = draw.diagnostics + assert d["unallocated_expenditure_gbp"] > 0 + assert d["rows_at_turnover_cap"] > 0 + assert d["model_expenditure_gbp"] + d["unallocated_expenditure_gbp"] == ( + pytest.approx(d["hmrc_section_expenditure_gbp"]) + ) + + +def test_large_stratum_is_taken_top_down_by_headcount() -> None: + firms = _firms(rows_per_section=1_000) + draw = draw_uk_firm_rd_tax_credits(firms, _source(), seed=7) + employees = firms["firm_employees"].to_numpy() + large = draw.claimant & ~draw.is_sme + for letter in ("C", "J", "M"): + pool = (firms["firm_sic_section"] == letter).to_numpy() & ( + firms["ons_legal_status"].to_numpy() == 1 + ) + in_large = pool & large + assert in_large.any() + assert employees[in_large].min() >= employees[pool & ~in_large].max() + + +def test_small_pool_is_capped_and_reported() -> None: + firms = _firms(rows_per_section=40) + draw = draw_uk_firm_rd_tax_credits(firms, _source(), seed=7) + assert "C:sme" in draw.diagnostics["draw_capped_strata"] + in_c = (firms["firm_sic_section"] == "C") & (firms["ons_legal_status"] == 1) + assert draw.claimant[in_c.to_numpy()].all() + + +def test_draw_is_row_order_invariant_and_seeded() -> None: + firms = _firms() + first = assign_uk_firm_rd_tax_credits(firms, _source(), seed=11) + shuffled = firms.sample(frac=1.0, random_state=0) + second = assign_uk_firm_rd_tax_credits(shuffled, _source(), seed=11) + pd.testing.assert_frame_equal(first, second.loc[first.index]) + other = assign_uk_firm_rd_tax_credits(firms, _source(), seed=12) + assert not np.array_equal( + first["firm_qualifying_rd_expenditure"], other["firm_qualifying_rd_expenditure"] + ) + + +def test_sme_flag_follows_stratum_then_headcount_limb() -> None: + firms = _firms() + out = assign_uk_firm_rd_tax_credits(firms, _source(), seed=1) + draw = draw_uk_firm_rd_tax_credits(firms, _source(), seed=1) + employees = firms["firm_employees"].to_numpy() + rest = ~draw.claimant + assert (out["firm_is_sme"].to_numpy()[rest] == (employees[rest] < 500)).all() + large = draw.claimant & ~draw.is_sme + assert large.any() and (draw.claimant & draw.is_sme).any() + assert not out["firm_is_sme"].to_numpy()[large].any() + edge = firms.copy() + edge.loc[edge.index[:3], "ons_legal_status"] = 2 + edge.loc[edge.index[:3], "firm_employees"] = [499.0, 500.0, 5_000.0] + flags = assign_uk_firm_rd_tax_credits(edge, _source(), seed=1)["firm_is_sme"] + assert flags.iloc[:3].tolist() == [True, False, False] + assert out.drop(columns=["firm_is_sme", "firm_qualifying_rd_expenditure"]).equals( + firms + ) + + +def test_rejects_duplicate_ids_and_missing_columns() -> None: + firms = _firms(rows_per_section=5) + with pytest.raises(ValueError, match="firm_turnover"): + draw_uk_firm_rd_tax_credits( + firms.drop(columns="firm_turnover"), _source(), seed=1 + ) + firms.loc[1, "firm_id"] = firms.loc[0, "firm_id"] + with pytest.raises(ValueError, match="one row per firm_id"): + draw_uk_firm_rd_tax_credits(firms, _source(), seed=1) 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..757a9b5be0 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_table.py @@ -0,0 +1,763 @@ +"""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_employment_allowance import ( + UK_FIRM_EMPLOYMENT_ALLOWANCE_COLUMNS, + assign_uk_firm_employment_allowance, +) +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_PAYBILL_EXTENDED_POLICYENGINE_UK_COLUMNS, + UK_FIRM_PAYBILL_POLICYENGINE_UK_COLUMNS, + UK_FIRM_PAYBILL_TABLE_COLUMNS, + 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 + # The paybill table adds firm_paybill after the extended policyengine-uk + # columns and keeps the Microcosm-only tail. + assert UK_FIRM_PAYBILL_POLICYENGINE_UK_COLUMNS == ("firm_paybill",) + assert UK_FIRM_PAYBILL_EXTENDED_POLICYENGINE_UK_COLUMNS == ( + *UK_FIRM_EXTENDED_POLICYENGINE_UK_COLUMNS, + "firm_paybill", + ) + assert UK_FIRM_PAYBILL_TABLE_COLUMNS == ( + *UK_FIRM_PAYBILL_EXTENDED_POLICYENGINE_UK_COLUMNS, + *UK_FIRM_MICROCOSM_ONLY_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 + ) + assert set(UK_FIRM_PAYBILL_EXTENDED_POLICYENGINE_UK_COLUMNS) <= set( + UK_FIRM_POLICYENGINE_UK_INPUT_STATUS + ) + 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; the + # paybill gives every firm its section's mean pay per head. + assert { + name + for name, status in UK_FIRM_POLICYENGINE_UK_INPUT_STATUS.items() + if status == "assumed" + } == { + # employment less assumed working proprietors (labour link group). + "firm_employees", + # HMRC R&D tax credit statistics (rd_tax_credits group). + "firm_qualifying_rd_expenditure", + "firm_is_sme", + "firm_input_vat", + "firm_legal_form", + "firm_is_public_body", + "firm_is_charity", + "firm_in_england", + "firm_paybill", + "firm_claims_employment_allowance", + "firm_is_single_director_company", + "firm_taxable_trading_profit", + "firm_rateable_value", + "firm_employees_below_secondary_threshold", + "firm_paybill_below_secondary_threshold", + } + 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_and_paybill_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", + "paybill", + "employment_allowance", + "pay_distribution", + "profit", + "rateable_value", + "sic_division", + "labour_link", + "employment_allowance_takeup", + "rd_tax_credits", + "consumption", + "vat_composition", + ] + ( + attributes, + paybill, + allowance, + pay_distribution, + profit, + rateable_value, + sic_division, + labour_link, + takeup, + rd, + consumption, + vat_composition, + ) = UK_FIRM_EXPORT_GROUPS + assert vat_composition.requires == ("attributes",) + assert vat_composition.policyengine_uk_columns == () + assert all(c.startswith("firm_sut_") for c in vat_composition.microcosm_columns) + assert rd.policyengine_uk_columns == ( + "firm_qualifying_rd_expenditure", + "firm_is_sme", + ) + assert rd.requires == ("attributes",) + assert consumption.requires == ("attributes", "sic_division") + assert consumption.microcosm_columns == ( + "firm_household_sales", + "firm_intermediate_sales", + "firm_other_final_sales", + ) + assert labour_link.source_columns == ("employees",) + assert labour_link.policyengine_uk_columns == () + assert sic_division.microcosm_columns == ("firm_sic_division",) + assert labour_link.requires == ("attributes", "paybill", "sic_division") + assert takeup.requires == ( + "attributes", + "paybill", + "employment_allowance", + "sic_division", + "labour_link", + ) + assert takeup.microcosm_columns == ("firm_employment_allowance_rule_claims",) + assert pay_distribution.requires == ("attributes", "paybill") + assert pay_distribution.policyengine_uk_columns == ( + "firm_employees_below_secondary_threshold", + "firm_paybill_below_secondary_threshold", + ) + 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 == () + assert paybill.source_columns == ("firm_paybill",) + assert paybill.policyengine_uk_columns == UK_FIRM_PAYBILL_POLICYENGINE_UK_COLUMNS + assert paybill.microcosm_columns == () + assert paybill.requires == ("attributes",) + assert allowance.source_columns == UK_FIRM_EMPLOYMENT_ALLOWANCE_COLUMNS + assert allowance.policyengine_uk_columns == UK_FIRM_EMPLOYMENT_ALLOWANCE_COLUMNS + assert allowance.microcosm_columns == () + assert allowance.requires == ("attributes",) + for group, column in ( + (profit, "firm_taxable_trading_profit"), + (rateable_value, "firm_rateable_value"), + ): + assert group.source_columns == (column,) + assert group.policyengine_uk_columns == (column,) + assert group.microcosm_columns == () + assert group.requires == ("attributes",) + # 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; pay_distribution also needs paybill. + extending = [ + "paybill", + "employment_allowance", + "pay_distribution", + "profit", + "rateable_value", + "sic_division", + "labour_link", + "employment_allowance_takeup", + "rd_tax_credits", + "consumption", + "vat_composition", + ] + expected = {(): UK_FIRM_TABLE_COLUMNS} + for size in range(len(extending) + 1): + for chosen in itertools.combinations(extending, size): + if "pay_distribution" in chosen and "paybill" not in chosen: + continue + if "labour_link" in chosen and not {"paybill", "sic_division"} <= set( + chosen + ): + continue + if "consumption" in chosen and "sic_division" not in chosen: + continue + if "employment_allowance_takeup" in chosen and not { + "employment_allowance", + "labour_link", + } <= set(chosen): + continue + 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_LAYOUTS[("attributes", "paybill")] == ( + UK_FIRM_PAYBILL_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(["paybill", "attributes"]) == ( + UK_FIRM_PAYBILL_TABLE_COLUMNS + ) + assert uk_firm_policyengine_uk_columns(iter(["attributes", "paybill"])) == ( + UK_FIRM_PAYBILL_EXTENDED_POLICYENGINE_UK_COLUMNS + ) + assert uk_firm_table_columns(iter(["attributes"])) == ( + UK_FIRM_EXTENDED_TABLE_COLUMNS + ) + with pytest.raises(ValueError, match="extends"): + uk_firm_table_columns(["paybill"]) + 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",) + paybill = _attributed_firms().assign(firm_paybill=0.0) + assert uk_firm_export_groups(paybill) == ("attributes", "paybill") + with pytest.raises(ValueError, match="needs both"): + uk_firm_export_groups(_attributed_firms().drop(columns="ons_region_code")) + with pytest.raises(ValueError, match="firm_paybill without"): + uk_firm_export_groups(_firms().assign(firm_paybill=0.0)) + allowance = assign_uk_firm_employment_allowance(_attributed_firms()) + assert uk_firm_export_groups(allowance) == ("attributes", "employment_allowance") + with pytest.raises(ValueError, match="needs both"): + uk_firm_export_groups(allowance.drop(columns="firm_is_single_director_company")) + + +def test_employment_allowance_export_follows_status_and_employment() -> None: + firms = assign_uk_firm_employment_allowance(_attributed_firms()) + table = to_policyengine_uk_firm_table(firms, threshold_k=90.0) + assert tuple(table.columns) == uk_firm_table_columns( + ["attributes", "employment_allowance"] + ) + validate_uk_firm_table(table) + base = to_policyengine_uk_firm_table(_attributed_firms(), threshold_k=90.0) + pd.testing.assert_frame_equal(table[list(base.columns)], base) + by_status = table.set_index("ons_legal_status") + # The partnership has employment 0 and the sole trader employment 1: both + # are their proprietors alone; the company has employment 12. + assert not by_status.loc[3, "firm_claims_employment_allowance"] + assert not by_status.loc[2, "firm_claims_employment_allowance"] + assert by_status.loc[1, "firm_claims_employment_allowance"] + assert not table["firm_is_single_director_company"].any() + broken = table.assign( + firm_claims_employment_allowance=~table["firm_claims_employment_allowance"] + ) + with pytest.raises(ValueError, match="does not follow"): + validate_uk_firm_table(broken) + + +def test_rateable_value_must_be_zero_outside_england() -> None: + # Rows are firms 4, 2, 1, 3: Wales, North East, Scotland, London. + firms = _attributed_firms().assign(firm_rateable_value=[0.0, 2000.0, 0.0, 500.0]) + table = to_policyengine_uk_firm_table(firms, threshold_k=90.0) + validate_uk_firm_table(table) + outside = ~table["firm_in_england"].to_numpy(bool) + wrong = table["firm_rateable_value"].where(~outside, 100.0) + with pytest.raises(ValueError, match="zero outside England"): + validate_uk_firm_table(table.assign(firm_rateable_value=wrong)) + + +def test_public_sector_link_leaves_out_public_corporations() -> None: + # Rows are firms 4, 2, 1, 3: a public corporation, a local authority, + # central government and a non-profit body. + firms = _attributed_firms().assign( + ons_legal_status=np.array([4, 6, 5, 7], dtype=np.int64), + firm_paybill=[360000.0, 90000.0, 0.0, 30000.0], + firm_sic_division=np.array([11, 47, 4, 86], dtype=np.int64), + ) + firms = firms.assign(employees=firms["employment"].to_numpy(np.int64)) + table = to_policyengine_uk_firm_table(firms, threshold_k=90.0) + validate_uk_firm_table(table) + by_status = table.set_index("ons_legal_status") + assert by_status["firm_is_public_body"].to_dict() == { + 4: True, + 5: True, + 6: True, + 7: False, + } + assert by_status["firm_is_public_sector"].to_dict() == { + 4: False, + 5: True, + 6: True, + 7: False, + } 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..10d338a251 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_target_candidates.py @@ -0,0 +1,181 @@ +"""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", +} + + +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..6267d2e085 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_tax_receipts.py @@ -0,0 +1,213 @@ +"""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"] + assert "Assumed input" in lines["firm_business_rates"] + assert "In-sample" in lines["corporation_tax"] + for tax in ("firm_employer_ni", "apprenticeship_levy"): + assert "not a validation" in lines[tax] + assert "ASHE 2025" in lines[tax] + assert "working proprietors" in lines[tax] + assert "zero-turnover" 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_firm_vat_composition.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_vat_composition.py new file mode 100644 index 0000000000..1c6c95ce5e --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_vat_composition.py @@ -0,0 +1,424 @@ +"""UK firm VAT composition by SIC section from the Supply and Use Tables 2024.""" + +from __future__ import annotations + +import hashlib +import json +from functools import cache + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.uk_runtime.firm_consumption import UKFirmSupplyUseSource +from microcosm.build.uk_runtime.firm_vat_composition import ( + UK_FIRM_INPUT_RATIO_BOUNDS, + UK_FIRM_VAT_COMPOSITION_FILES, + UK_FIRM_VAT_COMPOSITION_RULE_COLUMNS, + UK_FIRM_VAT_COMPOSITION_SHARE_COLUMNS, + UK_FIRM_VAT_SUPPLY_COLUMNS, + UK_FIRM_VAT_TREATMENTS, + UKFirmVATCompositionRules, + UKFirmVATCompositionSource, + add_uk_firm_vat_composition_columns, + compose_uk_firm_vat_supplies, + read_uk_firm_vat_composition_source, + rescale_uk_firm_input_costs, + uk_firm_input_ratio_factors, + uk_firm_vat_product_shares, + uk_firm_vat_relief_checks, + uk_firm_vat_section_shares, + uk_firm_vat_voluntary_registration, +) +from test_support.paths import paths_for + +PATHS = paths_for("microcosm-build") +FIXTURES = PATHS.tests / "fixtures" / "uk" +FIXTURE = FIXTURES / "firm_vat_composition_2024" +SUPPLY_USE = FIXTURES / "firm_supply_use_2024" + + +@cache +def _source(): + return read_uk_firm_vat_composition_source(FIXTURE, SUPPLY_USE) + + +@cache +def _shares() -> pd.DataFrame: + return uk_firm_vat_section_shares(_source()) + + +def test_provenance_pins_every_file_and_both_workbooks(): + provenance = json.loads((FIXTURE / "provenance.json").read_text()) + for name in UK_FIRM_VAT_COMPOSITION_FILES: + digest = hashlib.sha256((FIXTURE / name).read_bytes()).hexdigest() + assert provenance["files"][name]["sha256"] == digest + assert provenance["sources"]["sut"]["sha256"].startswith("716c9e02") + assert provenance["sources"]["abs"]["sha256"].startswith("9e548c5c") + assert { + x["direct_url"].split("/")[-2] for x in provenance["sources"]["legislation"] + } >= { + "7A", + "8", + "9", + } + + +def test_reader_refuses_a_changed_file(tmp_path): + for name in (*UK_FIRM_VAT_COMPOSITION_FILES, "provenance.json"): + (tmp_path / name).write_bytes((FIXTURE / name).read_bytes()) + path = tmp_path / "sut_dwellings_gfcf.csv" + path.write_text(path.read_text().replace("107010", "107011")) + with pytest.raises(ValueError, match="sha256"): + read_uk_firm_vat_composition_source(tmp_path, SUPPLY_USE) + + +def test_treatment_rows_are_labelled_and_sum_to_one(): + table = _source().treatment + assert set(table["status"]) == {"statute", "assumed"} + assert table["basis"].str.len().min() > 10 + numeric = table[~table["standard"].isin(["DWELLINGS", "GOODS"])] + sums = numeric[list(UK_FIRM_VAT_TREATMENTS)].astype(float).sum(axis=1) + assert np.allclose(sums, 1.0) + computed = table[table["standard"].isin(["DWELLINGS", "GOODS"])] + assert set(computed["status"]) == {"assumed"} + + +def test_section_shares_are_shares_and_match_the_reviewed_values(): + shares = _shares() + assert np.allclose(shares[list(UK_FIRM_VAT_TREATMENTS)].sum(axis=1), 1.0) + assert ( + ( + (shares[list(UK_FIRM_VAT_TREATMENTS)] >= 0) + & (shares[list(UK_FIRM_VAT_TREATMENTS)] <= 1) + ) + .all() + .all() + ) + lo, hi = UK_FIRM_INPUT_RATIO_BOUNDS + assert shares["input_ratio_target"].between(lo, hi).all() + # Values reviewed at gate B1 (27 Nov 2026). + assert shares.loc["K", "exempt"] == pytest.approx(0.5628, abs=1e-4) + assert shares.loc["D", "reduced"] == pytest.approx(0.2136, abs=1e-4) + assert shares.loc["A", "zero"] == pytest.approx(0.8142, abs=1e-4) + assert shares.loc["G", "input_ratio_target"] == pytest.approx(0.8612, abs=1e-4) + assert shares.loc["G", "input_vat_rate"] == pytest.approx(0.1669, abs=1e-4) + assert shares.loc["G", "standard"] == pytest.approx(0.6911, abs=1e-4) + # Exports of hotel and restaurant services are non-residents' spending here. + assert shares.loc["I", "standard"] == pytest.approx(1.0) + assert shares.loc["P", "zero"] == pytest.approx(0.0) + assert shares.loc["O", "exempt"] == pytest.approx(0.9923, abs=1e-4) + + +def test_section_g_ratio_is_on_the_gross_sales_base(): + source = _source() + abs_g = source.abs_turnover.set_index("sic_section").loc[ + "G", "turnover_gbp_million" + ] + assert abs_g == 1793666 + # ABS 2024 purchases / turnover for G, a cross-check of the SUT-based base. + purchases = source.abs_turnover.set_index("sic_section").loc[ + "G", "purchases_gbp_million" + ] + assert purchases / abs_g == pytest.approx( + _shares().loc["G", "input_ratio_target"], abs=0.03 + ) + + +def test_compose_splits_turnover_and_keeps_out_of_scope_rows_exempt(): + firms = pd.DataFrame( + { + "firm_turnover": [1_000_000.0, 500_000.0], + "firm_input_costs": [400_000.0, 100_000.0], + "firm_sic_section": ["K", "C"], + } + ) + out = compose_uk_firm_vat_supplies(firms, _shares(), np.array([True, False])) + total = sum(out[c] for c in UK_FIRM_VAT_SUPPLY_COLUMNS.values()) + assert np.allclose(total, firms["firm_turnover"]) + assert out.loc[0, "firm_exempt_supplies"] == pytest.approx( + 1e6 * _shares().loc["K", "exempt"] + ) + assert out.loc[1, "firm_exempt_supplies"] == 500_000.0 + assert out.loc[1, "firm_standard_rated_supplies"] == 0.0 + assert out.loc[0, "firm_input_vat"] == pytest.approx( + 400_000 * _shares().loc["K", "input_vat_rate"] + ) + with pytest.raises(ValueError, match="sections"): + compose_uk_firm_vat_supplies( + firms.assign(firm_sic_section=["K", "U"]), _shares() + ) + + +def test_voluntary_registration_keeps_registered_rows_below_threshold(): + firms = pd.DataFrame( + { + "firm_standard_rated_supplies": [50_000.0, 100_000.0, 10_000.0], + "firm_reduced_rated_supplies": [0.0, 0.0, 0.0], + "firm_zero_rated_supplies": [10_000.0, 0.0, 0.0], + } + ) + got = uk_firm_vat_voluntary_registration( + firms, np.array([True, True, False]), 90_000.0 + ) + assert got.tolist() == [True, False, False] + + +def test_input_ratio_factors_hit_the_target_and_keep_the_bounds(): + rng = np.random.default_rng(0) + ratio = 0.2 + rng.beta(4, 2, 2000) * 0.6 + turnover = rng.lognormal(12, 1, 2000) + sections = np.array(["G"] * 1000 + ["M"] * 1000) + targets = pd.Series({"G": 0.86, "M": 0.39}) + factors = uk_firm_input_ratio_factors(sections, ratio, turnover, targets) + assert factors["G"]["achieved"] == pytest.approx(0.86, abs=1e-9) + assert factors["M"]["achieved"] == pytest.approx(0.39, abs=1e-9) + assert factors["G"]["k"] > 1 > factors["M"]["k"] + new, again = rescale_uk_firm_input_costs( + turnover, ratio * turnover, sections, targets + ) + assert again == factors + lo, hi = UK_FIRM_INPUT_RATIO_BOUNDS + assert ((new / turnover >= lo - 1e-12) & (new / turnover <= hi + 1e-12)).all() + zero, _ = rescale_uk_firm_input_costs( + np.array([0.0]), np.array([0.0]), np.array(["G"]), targets + ) + assert zero.tolist() == [0.0] + + +class _FakeSimulation: + """VAT liability with pe-uk's formula: output VAT less input VAT x rounded recovery.""" + + def __init__(self, table: pd.DataFrame, period: int) -> None: + self.table = table + assert list(table.columns) == list(UK_FIRM_VAT_COMPOSITION_RULE_COLUMNS) + + def calculate(self, variable: str, period: int): + t = self.table + if variable == "firm_id": + return t["firm_id"].to_numpy() + taxable = ( + t["firm_standard_rated_supplies"] + + t["firm_reduced_rated_supplies"] + + t["firm_zero_rated_supplies"] + ) + share = ( + np.ceil(taxable / (taxable + t["firm_exempt_supplies"]) * 100 - 1e-6) / 100 + ) + output = ( + 0.2 * t["firm_standard_rated_supplies"] + + 0.05 * t["firm_reduced_rated_supplies"] + ) + return (output - t["firm_input_vat"] * share).to_numpy() + + +def test_rules_hand_zero_and_reduced_supplies_to_policyengine_uk(): + candidates = pd.DataFrame( + { + "firm_id": [1, 2], + "firm_turnover": [1e6, 1e6], + "firm_input_costs": [5e5, 5e5], + "firm_employees": [5, 5], + "firm_sic_section": ["K", "C"], + "firm_standard_rated_supplies": [1e6, 1e6], + "firm_exempt_supplies": [0.0, 0.0], + "firm_input_vat": [1e5, 1e5], + } + ) + rules = UKFirmVATCompositionRules(_shares(), simulation_factory=_FakeSimulation) + got = rules.evaluate(candidates, period=2024).vat_liability_if_registered + k = _shares().loc["K"] + # Recovery share for section K: (1 - exempt) = 0.4372, rounded up to 0.44. + share = np.ceil((1 - k["exempt"]) * 100 - 1e-6) / 100 + assert share == 0.44 + hand_k = 0.2 * k["standard"] * 1e6 - k["input_vat_rate"] * 5e5 * share + c = _shares().loc["C"] + hand_c = 0.2 * c["standard"] * 1e6 - c["input_vat_rate"] * 5e5 + assert got == pytest.approx([hand_k, hand_c], rel=1e-12) + + +def test_relief_checks_are_reported_not_targets(): + checks = uk_firm_vat_relief_checks(_source())["ratio"].round(3).to_dict() + # Every ratio is pinned, the poor ones too; none is a target. + assert checks == { + "NS7 food (zero)": 1.044, + "NS1 printed matter (zero)": 1.563, + "NS2 children's clothing (zero)": 0.866, + "NS3 new dwellings (zero)": 0.892, + "NS4 domestic fuel and power (reduced)": 0.999, + "NS5 domestic passenger transport (zero)": 0.72, + "NS6 prescription drugs (zero)": 0.0, + "NS16 water and sewerage (zero)": 0.846, + } + costs = _source().relief_costs.set_index("code")["cost_2024_25_gbp_million"] + assert costs["VAT - NS7"] == 26300 and costs["VAT - NS16"] == 2900 + + +def _copy_fixture(tmp_path): + for name in (*UK_FIRM_VAT_COMPOSITION_FILES, "provenance.json"): + (tmp_path / name).write_bytes((FIXTURE / name).read_bytes()) + + +def _rewrite_treatment(tmp_path, edit): + path = tmp_path / "vat_product_treatment.csv" + table = pd.read_csv(path, dtype=str) + table = edit(table) + table.to_csv(path, index=False, lineterminator="\n") + provenance = json.loads((tmp_path / "provenance.json").read_text()) + digest = hashlib.sha256(path.read_bytes()).hexdigest() + provenance["files"]["vat_product_treatment.csv"]["sha256"] = digest + (tmp_path / "provenance.json").write_text(json.dumps(provenance)) + + +def _set(column, value): + def edit(table): + table.loc[0, column] = value + return table + + return edit + + +@pytest.mark.parametrize( + ("edit", "message"), + [ + (_set("user", "tourists"), "user must be"), + (_set("standard", "0.5"), "sum to 1"), + (_set("status", "guess"), "status"), + (lambda table: table.drop(index=0), "Every SUT product"), + (lambda table: pd.concat([table, table.iloc[[1]]]), "repeats"), + ], +) +def test_reader_refuses_a_malformed_treatment_table(tmp_path, edit, message): + _copy_fixture(tmp_path) + _rewrite_treatment(tmp_path, edit) + with pytest.raises(ValueError, match=message): + read_uk_firm_vat_composition_source(tmp_path, SUPPLY_USE) + + +def _toy_source() -> UKFirmVATCompositionSource: + """Three products by hand: food (A), a service (M) and retail (G47).""" + + uses = pd.DataFrame( + { + "intermediate_consumption": [20.0, 30.0, 0.0], + "households": [60.0, 10.0, 0.0], + "npish": 0.0, + "central_government": 0.0, + "local_government": 0.0, + "gfcf": 0.0, + "valuables": 0.0, + "changes_in_inventories": 0.0, + "exports": [20.0, 60.0, 0.0], + "total_demand": [100.0, 100.0, 0.0], + "domestic_output": [80.0, 100.0, 40.0], + "distributors_margins": [40.0, 0.0, -40.0], + }, + index=pd.Index(["CPA_A01", "CPA_M70", "CPA_G47"], name="product_code"), + ) + treatment = pd.DataFrame( + [ + ("CPA_A01", "all", "0.25", "0", "0.75", "0", "toy", "assumed"), + ("CPA_M70", "all", "1", "0", "0", "0", "toy", "statute"), + ("CPA_G47", "all", "GOODS", "0", "GOODS", "0", "toy", "assumed"), + ], + columns=["product_code", "user", *UK_FIRM_VAT_TREATMENTS, "basis", "status"], + ) + intermediate = pd.DataFrame( + { + "product_code": ["CPA_A01", "CPA_M70", "CPA_M70"], + "industry_product_code": ["CPA_M70", "CPA_M70", "CPA_A01"], + "value_gbp_million": [10.0, 30.0, 20.0], + } + ) + divisions = pd.DataFrame( + { + "product_code": ["CPA_A01", "CPA_M70", "CPA_G47"], + "sic_division": [1, 70, 47], + "sic_section": ["A", "M", "G"], + } + ) + supply_use = UKFirmSupplyUseSource( + uses=uses, hhfce=pd.DataFrame(), divisions=divisions, sha256={} + ) + abs_turnover = pd.DataFrame( + { + "sic_section": ["G", "45", "46", "47"], + "turnover_gbp_million": [200.0, 0.0, 0.0, 200.0], + } + ) + return UKFirmVATCompositionSource( + treatment=treatment, + intermediate=intermediate, + dwellings_gfcf_gbp_million=0.0, + abs_turnover=abs_turnover, + relief_costs=pd.DataFrame(), + supply_use=supply_use, + sha256={}, + ) + + +def test_product_and_section_shares_by_hand(): + source = _toy_source() + products = uk_firm_vat_product_shares(source) + # Food: 80 of 100 sold at home at 0.25/0.75, 20 exported zero-rated. + assert products.loc["CPA_A01", "zero"] == pytest.approx((80 * 0.75 + 20) / 100) + assert products.loc["CPA_A01", "export_share"] == pytest.approx(0.2) + # Service: 40 at home standard, 60 exported zero-rated. + assert products.loc["CPA_M70", "standard"] == pytest.approx(0.4) + # Retail resells household goods (food only here): the food household mix. + assert products.loc["CPA_G47", "zero"] == pytest.approx(0.75) + # Industry M70 buys 10 of food at 0.2 x 0.25 and 30 of M at 0.2. + assert products.loc["CPA_M70", "input_vat_rate"] == pytest.approx( + (10 * 0.05 + 30 * 0.2) / 40 + ) + assert products.loc["CPA_A01", "input_vat_rate"] == pytest.approx(0.2) + sections = uk_firm_vat_section_shares(source) + assert sections.loc["M", "input_ratio_target"] == pytest.approx(40 / 100) + # Section G: gross sales 200, margin 40, no IC, so the ratio is + # 1 - 40 / 200; goods resold are priced at food's business rate 0.2 x 0.25. + assert sections.loc["G", "input_ratio_target"] == pytest.approx(0.8) + assert sections.loc["G", "input_vat_rate"] == pytest.approx(0.05) + + +def test_rescale_leaves_sections_without_a_target_alone(): + turnover = np.array([100.0, 100.0, 0.0]) + inputs = np.array([50.0, 5.0, 3.0]) + new, factors = rescale_uk_firm_input_costs( + turnover, inputs, np.array(["G", "Z", "G"]), pd.Series({"G": 0.6}) + ) + assert new[0] == pytest.approx(60.0) + assert new[1] == 5.0 and new[2] == 3.0 + assert factors["Z"]["rescaled"] == 0.0 + + +def test_columns_only_mode_adds_shares_and_leaves_scored_columns_alone(): + firms = pd.DataFrame( + { + "firm_id": [1, 2], + "firm_turnover": [1e6, 2e5], + "firm_input_costs": [6e5, 1e5], + "firm_sic_section": ["G", "Q"], + "firm_standard_rated_supplies": [1e6, 0.0], + "firm_exempt_supplies": [0.0, 2e5], + "firm_input_vat": [1.2e5, 2e4], + } + ) + out = add_uk_firm_vat_composition_columns(firms, _shares()) + pd.testing.assert_frame_equal(out[firms.columns], firms) + assert set(out.columns) - set(firms.columns) == set( + UK_FIRM_VAT_COMPOSITION_SHARE_COLUMNS.values() + ) + assert out.loc[1, "firm_sut_exempt_share"] == pytest.approx( + _shares().loc["Q", "exempt"] + ) + with pytest.raises(ValueError, match="already"): + add_uk_firm_vat_composition_columns(out, _shares()) + + +def test_input_ratio_bounds_follow_the_generator_clamp(): + from microcosm.build.uk_runtime import firm_generation + + assert UK_FIRM_INPUT_RATIO_BOUNDS == ( + firm_generation.INPUT_RATIO_LOWER, + firm_generation.INPUT_RATIO_UPPER, + ) 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_2024_25_size/.provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_2024_25_size/.provenance.json new file mode 100644 index 0000000000..40a6b334ea --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_2024_25_size/.provenance.json @@ -0,0 +1,28 @@ +{ + "source": { + "publisher": "Department for Business and Trade", + "dataset_title": "Business population estimates 2024", + "landing_page": "https://www.gov.uk/government/statistics/business-population-estimates-2024", + "edition": "Business population estimates for the UK and regions 2024 (start of 2024); landing page first published and last updated 3 October 2024 (GOV.UK content API on the access date)", + "download_url": "https://assets.publishing.service.gov.uk/media/66f554dcc71e42688b65ecd3/BPE_2024_detailed_tables.xlsx", + "file": "BPE_2024_detailed_tables.xlsx", + "sha256": "a1e96b8cd60cad6fbd4d8ea9d09c60c555953d9fced4b28cc6f928ce6048b399", + "bytes": 635200, + "sheet": "Table 1", + "sheet_title": "Table 1 (UK private sector): Number and percentage of businesses in the private sector and their associated employment and turnover, by number of employees, UK, start 2024", + "rows": ["250 to 499", "500 to 999", "1000 or more"], + "columns": ["Business number", "Employment number (thousands)"], + "licence": "Open Government Licence v3.0", + "access_date": "2026-11-22" + }, + "method": "The three rows were read from the downloaded workbook on the access date; none was filled from memory. Together they give 8,250 private businesses with 250 or more employees and 11,115 thousand employment (the sum of the three published rows, each rounded to the nearest thousand), a mean of 1,347.3 per business. Employment includes working proprietors (Note 6 of the workbook).", + "used_by": "microcosm.build.uk_runtime.firm_generation.LARGE_EMPLOYMENT_MEAN, the mean headcount of the open 250+ employment band", + "files": { + "dbt_bpe_private_250plus.csv": { + "sha256": "0ad49d2c6b9f1350f2d06600f7c2fe2b7277991f2f46e7b3b126f9b61efc8771", + "bytes": 115, + "rows": 3, + "columns": ["employee_size_band", "businesses", "employment_thousand"] + } + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_2024_25_size/dbt_bpe_private_250plus.csv b/packages/microcosm-build/tests/fixtures/uk/firm_2024_25_size/dbt_bpe_private_250plus.csv new file mode 100644 index 0000000000..fde04b0df0 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_2024_25_size/dbt_bpe_private_250plus.csv @@ -0,0 +1,4 @@ +employee_size_band,businesses,employment_thousand +250 to 499,4205,1457 +500 to 999,2115,1459 +1000 or more,1930,8199 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_bpe_2025/bpe_legal_status_bands.csv b/packages/microcosm-build/tests/fixtures/uk/firm_bpe_2025/bpe_legal_status_bands.csv new file mode 100644 index 0000000000..ee3f1cb1af --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_bpe_2025/bpe_legal_status_bands.csv @@ -0,0 +1,61 @@ +legal_status,size_band,business_number,business_number_flag,employment_thousand,employment_flag +private_sector,All businesses,5690265,,28128, +private_sector,All employers,1417730,,23464, +private_sector,With no employees (unregistered),3044940,,3356, +private_sector,With no employees (registered),1227595,,1307, +private_sector,1,114170,,254, +private_sector,2 to 4,772535,,2124, +private_sector,5 to 9,264170,,1778, +private_sector,10 to 19,142500,,1952, +private_sector,20 to 49,77585,,2372, +private_sector,50 to 99,26020,,1811, +private_sector,100 to 199,10205,,1435, +private_sector,200 to 249,2210,,492, +private_sector,250 to 499,4290,,1491, +private_sector,500 to 999,2075,,1435, +private_sector,1000 or more,1970,,8320, +companies,All businesses,2103615,,23000, +companies,All employers,1155990,,22056, +companies,With no employees (unregistered),0,,0, +companies,With no employees (registered),947625,,943, +companies,1,0,,0, +companies,2 to 4,677950,,1749, +companies,5 to 9,231525,,1519, +companies,10 to 19,129495,,1756, +companies,20 to 49,71515,,2174, +companies,50 to 99,25025,,1741, +companies,100 to 199,10000,,1406, +companies,200 to 249,2185,,,[c] +companies,250 to 499,4260,,,[c] +companies,500 to 999,2065,,1426, +companies,1000 or more,1970,,,[c] +ordinary_partnerships,All businesses,367925,,1407, +ordinary_partnerships,All employers,81320,,725, +ordinary_partnerships,With no employees (unregistered),206300,,518, +ordinary_partnerships,With no employees (registered),80305,,164, +ordinary_partnerships,1,24955,,76, +ordinary_partnerships,2 to 4,29245,,139, +ordinary_partnerships,5 to 9,13920,,121, +ordinary_partnerships,10 to 19,7330,,117, +ordinary_partnerships,20 to 49,4750,,161, +ordinary_partnerships,50 to 99,875,,62, +ordinary_partnerships,100 to 199,180,,26, +ordinary_partnerships,200 to 249,25,,5, +ordinary_partnerships,250 to 499,30,,10, +ordinary_partnerships,500 to 999,10,,,[c] +ordinary_partnerships,1000 or more,0,,,[c] +sole_proprietorships,All businesses,3218725,,3721, +sole_proprietorships,All employers,180420,,683, +sole_proprietorships,With no employees (unregistered),2838640,,2839, +sole_proprietorships,With no employees (registered),199665,,200, +sole_proprietorships,1,89215,,178, +sole_proprietorships,2 to 4,65340,,236, +sole_proprietorships,5 to 9,18725,,139, +sole_proprietorships,10 to 19,5675,,79, +sole_proprietorships,20 to 49,1315,,37, +sole_proprietorships,50 to 99,120,,8, +sole_proprietorships,100 to 199,25,,3, +sole_proprietorships,200 to 249,0,,,[c] +sole_proprietorships,250 to 499,5,,,[c] +sole_proprietorships,500 to 999,0,,,[c] +sole_proprietorships,1000 or more,0,,0, diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_bpe_2025/bpe_size_bands.csv b/packages/microcosm-build/tests/fixtures/uk/firm_bpe_2025/bpe_size_bands.csv new file mode 100644 index 0000000000..7061e78d63 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_bpe_2025/bpe_size_bands.csv @@ -0,0 +1,64 @@ +table,sector,size_band,business_number,employment_thousand,employees_thousand,working_proprietors_thousand,turnover_million +Table 1,private_sector,All businesses,5690265,28128,23999,4129,5524662 +Table 1,private_sector,All employers,1417730,23464,23064,401,5122051 +Table 1,private_sector,With no employees (unregistered),3044940,3356,0,3356,135561 +Table 1,private_sector,With no employees (registered),1227595,1307,935,372,267051 +Table 1,private_sector,1,114170,254,114,140,27686 +Table 1,private_sector,2 to 4,772535,2124,1998,127,372779 +Table 1,private_sector,5 to 9,264170,1778,1729,49,300783 +Table 1,private_sector,10 to 19,142500,1952,1926,26,297849 +Table 1,private_sector,20 to 49,77585,2372,2350,23,478314 +Table 1,private_sector,50 to 99,26020,1811,1803,8,422278 +Table 1,private_sector,100 to 199,10205,1435,1430,5,350825 +Table 1,private_sector,200 to 249,2210,492,491,1,175536 +Table 1,private_sector,250 to 499,4290,1491,1487,4,407886 +Table 1,private_sector,500 to 999,2075,1435,1430,5,524307 +Table 1,private_sector,1000 or more,1970,8320,8307,13,1763807 +Table 2,whole_economy,All,5786945,36027,31899,,5938850 +Table 2,whole_economy,Zero or 1 employee,4420045,4943,1074,,432962 +Table 2,whole_economy,2 to 4,795555,2188,2061,,377854 +Table 2,whole_economy,5 to 9,280440,1888,1838,,308516 +Table 2,whole_economy,10 to 19,152135,2083,2057,,307255 +Table 2,whole_economy,20 to 49,83630,2560,2537,,490565 +Table 2,whole_economy,50 to 99,28960,2018,2010,,434005 +Table 2,whole_economy,100 to 199,12025,1695,1690,,364258 +Table 2,whole_economy,200 to 249,2765,616,615,,181692 +Table 2,whole_economy,250 to 499,5475,1911,1907,,429862 +Table 2,whole_economy,500 to 999,2890,2005,2000,,547379 +Table 2,whole_economy,1000 or more,3025,14120,14107,,2064503 +Table 2,private_sector,All,5690265,28128,23999,,5524662 +Table 2,private_sector,Zero or 1 employee,4386705,4918,1050,,430298 +Table 2,private_sector,2 to 4,772535,2124,1998,,372779 +Table 2,private_sector,5 to 9,264170,1778,1729,,300783 +Table 2,private_sector,10 to 19,142500,1952,1926,,297849 +Table 2,private_sector,20 to 49,77585,2372,2350,,478314 +Table 2,private_sector,50 to 99,26020,1811,1803,,422278 +Table 2,private_sector,100 to 199,10205,1435,1430,,350825 +Table 2,private_sector,200 to 249,2210,492,491,,175536 +Table 2,private_sector,250 to 499,4290,1491,1487,,407886 +Table 2,private_sector,500 to 999,2075,1435,1430,,524307 +Table 2,private_sector,1000 or more,1970,8320,8307,,1763807 +Table 2,central_and_local_government,All,12535,5829,5829,,289767 +Table 2,central_and_local_government,Zero or 1 employee,5065,5,5,,529 +Table 2,central_and_local_government,2 to 4,1685,4,4,,320 +Table 2,central_and_local_government,5 to 9,710,5,5,,300 +Table 2,central_and_local_government,10 to 19,400,6,6,,461 +Table 2,central_and_local_government,20 to 49,870,28,28,,1501 +Table 2,central_and_local_government,50 to 99,810,58,58,,2914 +Table 2,central_and_local_government,100 to 199,790,114,114,,6012 +Table 2,central_and_local_government,200 to 249,255,57,57,,2616 +Table 2,central_and_local_government,250 to 499,615,223,223,,11100 +Table 2,central_and_local_government,500 to 999,545,381,381,,12871 +Table 2,central_and_local_government,1000 or more,790,4948,4948,,251141 +Table 2,non_profit,All,84145,2070,2070,,124421 +Table 2,non_profit,Zero or 1 employee,28275,20,20,,2135 +Table 2,non_profit,2 to 4,21335,60,60,,4755 +Table 2,non_profit,5 to 9,15560,105,105,,7432 +Table 2,non_profit,10 to 19,9235,125,125,,8944 +Table 2,non_profit,20 to 49,5180,159,159,,10749 +Table 2,non_profit,50 to 99,2130,150,150,,8812 +Table 2,non_profit,100 to 199,1030,146,146,,7421 +Table 2,non_profit,200 to 249,300,67,67,,3541 +Table 2,non_profit,250 to 499,565,197,197,,10876 +Table 2,non_profit,500 to 999,270,189,189,,10200 +Table 2,non_profit,1000 or more,265,852,852,,49555 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_bpe_2025/firm_bpe_2025.provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_bpe_2025/firm_bpe_2025.provenance.json new file mode 100644 index 0000000000..abb9000d56 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_bpe_2025/firm_bpe_2025.provenance.json @@ -0,0 +1,67 @@ +{ + "kind": "uk_firm_bpe_size_band_fixture", + "schema_version": 1, + "period": "start of 2025 (BPE reference date), not a tax year", + "accessed": "2026-11-22", + "method": "Figures were read from the downloaded workbook on the access date by tools/extract_uk_firm_bpe_tables.py; none was filled from memory. Numbers are the cells as published: business counts in businesses, employment, employees and working proprietors in thousands of people, turnover in millions of pounds. A cell published as [c] (disclosive) is left empty and flagged [c]. Band labels lose their [Note n] markers; percentage columns are not kept.", + "source": { + "publisher": "Department for Business and Trade", + "dataset_title": "Business population estimates 2025", + "landing_page": "https://www.gov.uk/government/statistics/business-population-estimates-2025", + "url": "https://assets.publishing.service.gov.uk/media/68dbccc9c487360cc70c9f4e/BPE_2025_detailed_tables.xlsx", + "edition": "BUSINESS POPULATION ESTIMATES FOR THE UK AND REGIONS 2025; Published 2nd October 2025", + "file": "bpe2025.xlsx", + "size_bytes": 634622, + "sha256": "223790dfd61d41d5866b747f2ea24535cef0db754ee261ae9a2d88bba9f478d7", + "sheets": { + "bpe_legal_status_bands.csv": [ + "Table 3" + ], + "bpe_size_bands.csv": [ + "Table 1", + "Table 2" + ] + }, + "tables": { + "Table 1": "Number and percentage of businesses in the private sector and their associated employment and turnover, by number of employees, UK, start 2025", + "Table 2": "Number and percentage of businesses and other organisations in the whole economy, private sector, central and local government, and non-profit organisations with associated employment and turnover, start 2025", + "Table 3": "Number and percentage of businesses in the private sector and associated employment and turnover, by legal status and number of employees, UK, start 2025" + }, + "designation": "Official statistics in development", + "licence": "Open Government Licence v3.0" + }, + "notes": "Employment is employees plus working proprietors (Table 1 note 3). Companies with one PAYE employee on the IDBR are counted with no employees, the employee being treated as a working proprietor (Table 3 notes 3 and 6). Businesses with no employees are registered (VAT and/or PAYE) or unregistered (Table 3 note 2). Companies include public corporations and nationalised bodies (Table 3 heading). Turnover excludes SIC 2007 Section K. Business counts are rounded, so totals may not equal the sum of their parts.", + "extraction_date": "2026-11-22", + "tool": "tools/extract_uk_firm_bpe_tables.py", + "command": "uv run --no-sync python tools/extract_uk_firm_bpe_tables.py --xlsx /BPE_2025_detailed_tables.xlsx", + "files": { + "bpe_legal_status_bands.csv": { + "sha256": "c4c2706bdaa79a268fdc3da247701da1b99f6db6f1b334455448b9100918db44", + "bytes": 2589, + "rows": 60, + "columns": [ + "legal_status", + "size_band", + "business_number", + "business_number_flag", + "employment_thousand", + "employment_flag" + ] + }, + "bpe_size_bands.csv": { + "sha256": "b636affd3b889f987f2787fbd9f44c79def85584550b4a205f0a4bd1bfa67275", + "bytes": 3779, + "rows": 63, + "columns": [ + "table", + "sector", + "size_band", + "business_number", + "employment_thousand", + "employees_thousand", + "working_proprietors_thousand", + "turnover_million" + ] + } + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_capex_2024/abs_capex_by_section.csv b/packages/microcosm-build/tests/fixtures/uk/firm_capex_2024/abs_capex_by_section.csv new file mode 100644 index 0000000000..85d740a1e8 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_capex_2024/abs_capex_by_section.csv @@ -0,0 +1,22 @@ +sic_section,year,acquisitions_gbp_million,disposals_gbp_million +A-S (part),2024,243900,39889 +A (part),2024,1530,196 +B-E,2024,64346,5520 +B,2024,7286,372 +C,2024,22879,2752 +D,2024,20833,2114 +E,2024,13348,282 +F,2024,12475,3907 +G-S (part),2024,165550,30266 +G,2024,26008,4040 +H-S (part),2024,139541,26227 +H,2024,24535,3089 +I,2024,8127,1497 +J,2024,26557,1827 +L,2024,8414,2132 +M,2024,14617,2189 +N,2024,34023,11347 +P (part),2024,7680,496 +Q (part),2024,5156,726 +R,2024,8136,2301 +S,2024,2297,623 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_capex_2024/business_investment_by_asset.csv b/packages/microcosm-build/tests/fixtures/uk/firm_capex_2024/business_investment_by_asset.csv new file mode 100644 index 0000000000..fda9e34a5b --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_capex_2024/business_investment_by_asset.csv @@ -0,0 +1,6 @@ +series_id,asset,year,value_gbp_million +NPEK,Business Investment,2024,309068 +EDRB,Transport Equipment,2024,30824 +EDWH,ICT equipment and other machinery and equipment,2024,56621 +EDYP,Other buildings and structures,2024,81112 +EDYS,Intellectual Property Products,2024,140511 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_capex_2024/provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_capex_2024/provenance.json new file mode 100644 index 0000000000..957d2704cb --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_capex_2024/provenance.json @@ -0,0 +1,44 @@ +{ + "kind": "uk_firm_capex_fixture", + "schema_version": 1, + "accessed": "2026-11-26", + "use": "fixture only; not read by any build (see docs/uk-firm-capex-design.md)", + "sources": { + "business_investment": { + "publisher": "Office for National Statistics", + "dataset_title": "Business investment by asset", + "landing_page": "https://www.ons.gov.uk/economy/grossdomesticproductgdp/datasets/businessinvestmentbyasset", + "url": "https://www.ons.gov.uk/file?uri=/economy/grossdomesticproductgdp/datasets/businessinvestmentbyasset/current/businessinvestmentbyasset.xlsx", + "edition": "Business investment, Q2 2026 revised results, 30 September 2026", + "file": "businessinvestmentbyasset.xlsx", + "size_bytes": 80704, + "sha256": "f206fa785e4b1f1f04fef31dbcafd4b8b480af4029a20b5f438383fa7c521c2c", + "sheet": "CP (Annual)", + "note": "Business investment excludes dwellings and government; ICT and other machinery are one class." + }, + "abs": { + "publisher": "Office for National Statistics", + "dataset_title": "Non-financial business economy, UK: Sections A to S (Annual Business Survey)", + "url": "https://www.ons.gov.uk/file?uri=/businessindustryandtrade/business/businessservices/datasets/uknonfinancialbusinesseconomyannualbusinesssurveysectionsas/current/abssectionsas.xlsx", + "edition": "ABS 2024 results, 26 May 2026", + "file": "abssectionsas.xlsx", + "size_bytes": 1055873, + "sha256": "9e548c5c410b73e5a7aec1f97db8f92843430cb6ef5457b1459a0e0e9b13e710", + "sheet": "Sections A to S", + "note": "No asset split is published; section K and public bodies are outside the ABS." + } + }, + "tool": "tools/extract_uk_firm_capex_tables.py", + "files": { + "business_investment_by_asset.csv": { + "sha256": "52a53f96a7053f1b142647b5cf5b4251174a2c8123abf7e84f061517cc4b4aeb", + "bytes": 271, + "rows": 5 + }, + "abs_capex_by_section.csv": { + "sha256": "aa51f9eeb3001a13c804e3fc7136f71c5a8768960a2634d608a98a57abbf3c71", + "bytes": 485, + "rows": 21 + } + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_ct_2024/ct_liability_bands.csv b/packages/microcosm-build/tests/fixtures/uk/firm_ct_2024/ct_liability_bands.csv new file mode 100644 index 0000000000..df7bd187ff --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_ct_2024/ct_liability_bands.csv @@ -0,0 +1,17 @@ +band,lower_gbp,upper_gbp,companies,liability_gbp_million +0,0,0,1676855, +>0-100,0,100,82910,3 +>100-500,100,500,143140,40 +">500-1,000",500,1000,114070,84 +">1,000-5,000",1000,5000,455465,1232 +">5,000-10,000",5000,10000,276945,2008 +">10,000-50,000",10000,50000,412795,9204 +">50,000-100,000",50000,100000,75660,5273 +">100,000-500,000",100000,500000,61290,12280 +">500,000-1m",500000,1000000,7290,5074 +>1m-5m,1000000,5000000,5925,12123 +>5m-10m,5000000,10000000,855,5985 +>10m-50m,10000000,50000000,735,15390 +>50m,50000000,,155,19248 +POSITIVE,,,1637230,87945 +ALL_RETURNS,,,3314085, diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_ct_2024/ct_liability_bands.csv.provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_ct_2024/ct_liability_bands.csv.provenance.json new file mode 100644 index 0000000000..b8b32c8f96 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_ct_2024/ct_liability_bands.csv.provenance.json @@ -0,0 +1,39 @@ +{ + "kind": "uk_firm_ct_liability_fixture", + "schema_version": 1, + "period": "financial year 2024-25 (1 April 2024 to 31 March 2025)", + "accessed": "2026-11-22", + "url": "https://assets.publishing.service.gov.uk/media/6aabc7c52f29b38884818639/corporation_tax_data_tables_2026.ods", + "landing_page": "https://www.gov.uk/government/statistics/corporation-tax-statistics-2026", + "collection_page": "https://www.gov.uk/government/collections/analyses-of-corporation-tax-receipts-and-liabilities", + "edition": "Corporation Tax Statistics 2026, published 24 September 2026 (cover sheet: all tables updated in September 2026; next release autumn 2027)", + "publisher": "HM Revenue and Customs", + "licence": "Open Government Licence v3.0", + "sha256": "d1a1ea0e9ae5c8e3045c99d5b1aad242b659d955d9569df4d202feac9b24aa21", + "size_bytes": 71415, + "source_file": "corporation_tax_data_tables_2026.ods", + "sheet": "Tables_9A,B", + "tables": [ + "Table 9A: Total tax liability per band", + "Table 9B: Number of companies per band" + ], + "column": "2024-25", + "method": "Every figure was read from the downloaded workbook on the access date by tools/extract_uk_firm_ct_tables.py; none was filled from memory. Counts are as published (rounded by HMRC to the nearest 5) and amounts are GBP million as published (rounded to the nearest million). Band edges are parsed from the band labels (lower exclusive, upper inclusive, 'm' = million). Table 9A has no row for the 0 band and no liability for all returns, so those cells are blank. Earlier editions numbered this table 10; in the 2026 edition Tables 10A,B are trading turnover by band.", + "liability_concept": "The tables' 'tax liability' total equals 'Corporation Tax payable' in Table 5A of the same workbook: after double taxation relief and other charges and reliefs, including ring fence Corporation Tax and the supplementary charge.", + "tool": "tools/extract_uk_firm_ct_tables.py", + "command": "uv run --no-sync python tools/extract_uk_firm_ct_tables.py --ods /corporation_tax_data_tables_2026.ods", + "extraction_date": "2026-11-22", + "file": { + "name": "ct_liability_bands.csv", + "sha256": "c3beb7499d3d2e014c7bd8c3410b9df0ca8f7baaa244abb73e24fd0a23c4b306", + "bytes": 573, + "rows": 16, + "columns": [ + "band", + "lower_gbp", + "upper_gbp", + "companies", + "liability_gbp_million" + ] + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_ct_2024/ct_sic_sections.csv b/packages/microcosm-build/tests/fixtures/uk/firm_ct_2024/ct_sic_sections.csv new file mode 100644 index 0000000000..5057f27198 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_ct_2024/ct_sic_sections.csv @@ -0,0 +1,23 @@ +hmrc_section,description,companies_with_liability,liability_gbp_million +A,"Agriculture, Forestry and Fishing",15640,711 +B,Mining and Quarrying,2525,2088 +C,Manufacturing,76530,7259 +D,"Electricity, Gas, Steam and Air Conditioning",4780,3189 +E,"Water, Sewerage and Waste",5255,324 +F,Construction,226575,6048 +G,"Wholesale and Retail Trade, Repairs",177720,8919 +H,Transport and Storage,46875,1575 +I,Accommodation and Food,61730,1321 +J,Information and Communication,138490,7026 +K,Financial and Insurance,48005,21738 +L,Real Estate,160170,3236 +M,"Professional, Scientific & Technical",261470,8403 +N,Admin and Support Services,136940,7295 +O,"Public Admin, Defence and Social Services",3340,321 +P,Education,29995,520 +Q,Health and Social Work,99540,2379 +R,"Arts, Entertainment and Recreation",36655,1248 +S,Other services activities,76530,1527 +T,Households,7325,48 +U,"Overseas; Unclassified, Dormant and Non-trading",21150,2770 +ALL,Total,1637230,87945 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_ct_2024/ct_sic_sections.csv.provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_ct_2024/ct_sic_sections.csv.provenance.json new file mode 100644 index 0000000000..5eee5a8cf8 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_ct_2024/ct_sic_sections.csv.provenance.json @@ -0,0 +1,38 @@ +{ + "kind": "uk_firm_ct_liability_fixture", + "schema_version": 1, + "period": "financial year 2024-25 (1 April 2024 to 31 March 2025)", + "accessed": "2026-11-22", + "url": "https://assets.publishing.service.gov.uk/media/6aabc7c52f29b38884818639/corporation_tax_data_tables_2026.ods", + "landing_page": "https://www.gov.uk/government/statistics/corporation-tax-statistics-2026", + "collection_page": "https://www.gov.uk/government/collections/analyses-of-corporation-tax-receipts-and-liabilities", + "edition": "Corporation Tax Statistics 2026, published 24 September 2026 (cover sheet: all tables updated in September 2026; next release autumn 2027)", + "publisher": "HM Revenue and Customs", + "licence": "Open Government Licence v3.0", + "sha256": "d1a1ea0e9ae5c8e3045c99d5b1aad242b659d955d9569df4d202feac9b24aa21", + "size_bytes": 71415, + "source_file": "corporation_tax_data_tables_2026.ods", + "sheet": "Tables_6A,B", + "tables": [ + "Table 6A: Tax liability by SIC section", + "Table 6B: Number of companies by SIC section with > £0 CT payable" + ], + "column": "2024-25", + "method": "Every figure was read from the downloaded workbook on the access date by tools/extract_uk_firm_ct_tables.py; none was filled from memory. Counts are as published (rounded by HMRC to the nearest 5) and amounts are GBP million as published (rounded to the nearest million). HMRC section U is 'Overseas; Unclassified, Dormant and Non-trading', not SIC section U alone. This table is held out of the profit draw and used only to check it.", + "liability_concept": "The tables' 'tax liability' total equals 'Corporation Tax payable' in Table 5A of the same workbook: after double taxation relief and other charges and reliefs, including ring fence Corporation Tax and the supplementary charge.", + "tool": "tools/extract_uk_firm_ct_tables.py", + "command": "uv run --no-sync python tools/extract_uk_firm_ct_tables.py --ods /corporation_tax_data_tables_2026.ods", + "extraction_date": "2026-11-22", + "file": { + "name": "ct_sic_sections.csv", + "sha256": "c6a87608939cc3c409b5a00e48944c2406f5906596b96f24cec6d896cfc1f456", + "bytes": 940, + "rows": 22, + "columns": [ + "hmrc_section", + "description", + "companies_with_liability", + "liability_gbp_million" + ] + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_2024_25/hmrc_employment_allowance.csv b/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_2024_25/hmrc_employment_allowance.csv new file mode 100644 index 0000000000..a67254cd96 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_2024_25/hmrc_employment_allowance.csv @@ -0,0 +1,2 @@ +tax_year,claimants,cost_gbp +2024-25,1223000,3300000000 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_2024_25/hmrc_employment_allowance.csv.provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_2024_25/hmrc_employment_allowance.csv.provenance.json new file mode 100644 index 0000000000..b851fd0e5e --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_2024_25/hmrc_employment_allowance.csv.provenance.json @@ -0,0 +1,20 @@ +{ + "kind": "uk_firm_employment_allowance_check", + "schema_version": 1, + "period": "2024-25", + "accessed": "2026-11-22", + "use": "Held-out check of policyengine-uk employment_allowance on the generated firms. Never a calibration target.", + "method": "Read from the downloaded ODS on the access date. claimants: Table 5 (Claimants estimates), row 'Employment Allowance' (NIC - NS6), column '2024 to 2025' (1,223,000). cost_gbp: Table 2 (Six-year cost estimates, GBP million), same row and column (3,300), multiplied by 1,000,000. Table 2 marks 2025 to 2026 as the first forecasted costing year, so 2024-25 is an outturn estimate. HMRC describes the method as 'Administrative data on the use of the relief, with minimal further assumptions applied'. In 2024-25 the allowance was up to GBP 5,000 and employers with GBP 100,000 or more of prior-year secondary Class 1 liabilities could not claim.", + "sources": { + "hmrc_tax_relief_statistics": { + "url": "https://assets.publishing.service.gov.uk/media/69a0194e3e672177d0bc76e6/tax_relief_statistics_january_2026.ods", + "edition": "Tax relief statistics, January 2026", + "tables": [ + "Table 2: Six-year cost estimates", + "Table 5: Claimants estimates" + ], + "sha256": "fa94a61fe6b6a02c19b87a656154f27eaf5f00f35f0cce9339b8101b9ac8ee4a", + "landing_page_note": "Not recorded: the release page was not confirmed on the access date; the file URL and its sha256 identify the edition." + } + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_takeup_2024_25/hmrc_ea_takeup_by_region.csv b/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_takeup_2024_25/hmrc_ea_takeup_by_region.csv new file mode 100644 index 0000000000..eb6492b41e --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_takeup_2024_25/hmrc_ea_takeup_by_region.csv @@ -0,0 +1,14 @@ +region_code,region_description,employers_benefitting,share_percent +E12000001,North East,38000,3 +E12000002,North West,130000,11 +E12000003,Yorkshire and The Humber,93000,8 +E12000004,East Midlands,83000,7 +E12000005,West Midlands,102000,8 +E12000006,East of England,120000,10 +E12000007,London,219000,18 +E12000008,South East,173000,14 +E12000009,South West,102000,8 +W99999999,Wales,49000,4 +S99999999,Scotland,82000,7 +N99999999,Northern Ireland,33000,3 +Total,Total,1223000,100 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_takeup_2024_25/hmrc_ea_takeup_by_region.csv.provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_takeup_2024_25/hmrc_ea_takeup_by_region.csv.provenance.json new file mode 100644 index 0000000000..9f49fc372e --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_takeup_2024_25/hmrc_ea_takeup_by_region.csv.provenance.json @@ -0,0 +1,41 @@ +{ + "kind": "uk_firm_employment_allowance_takeup_fixture", + "schema_version": 1, + "period": "tax year 2024-25", + "accessed": "2026-11-22", + "url": "https://assets.publishing.service.gov.uk/media/684bf34372e2ed81c079700c/Employment_Allowance_2024-2025.ods", + "landing_page": "https://www.gov.uk/government/statistics/employment-allowance-take-up-2024-to-2025-tax-year-estimate", + "edition": "Employment Allowance take-up statistics: 2024 to 2025 tax year estimates", + "published": "2025-06-25", + "published_note": "Cover_Sheet: 'The data tables in this spreadsheet were originally published at 9:30am 25 June 2025.' The next publication was due June 2026.", + "publisher": "HM Revenue and Customs", + "licence": "Open Government Licence v3.0", + "sha256": "3848abed310515a0882c5f59a34b0b5e2f350155965f22ff3b173b55a0ceaaf0", + "size_bytes": 32709, + "source_file": "ea_2024_25.ods", + "sheet": "3_Regional_breakdown", + "sheets_read": [ + "Cover_Sheet", + "3_Regional_breakdown" + ], + "columns": [ + "2024 to 2025 tax year: Employers benefitting from EA", + "2024 to 2025 tax year: % of EA beneficiaries" + ], + "method": "Every figure was read from the downloaded workbook on the access date by tools/extract_uk_firm_employment_allowance_takeup.py; none was filled from memory. Counts are as published, rounded by HMRC to the nearest 1,000, with thousands separators removed; shares are whole percent as published. Labels are whitespace-normalised (the region sheet's 'Total ' code loses its trailing space). An employer counts as benefitting when some allowance was offset against its employer NICs paid to HMRC (Cover_Sheet). Codes as published: GSS E12 codes for the English regions and HMRC's W99999999, S99999999 and N99999999 for Wales, Scotland and Northern Ireland. Region is the claiming enterprise's postcode in the ONS Business Lookup Table (94% match rate); unmatched cases were apportioned by HMRC.", + "tool": "tools/extract_uk_firm_employment_allowance_takeup.py", + "command": "uv run --no-sync python tools/extract_uk_firm_employment_allowance_takeup.py --ods /Employment_Allowance_2024-2025.ods", + "extraction_date": "2026-11-22", + "file": { + "name": "hmrc_ea_takeup_by_region.csv", + "sha256": "fae0b44aabfb0870399583828b3f6038b84a8e05958268bb4eab689ea8e69997", + "bytes": 469, + "rows": 13, + "columns": [ + "region_code", + "region_description", + "employers_benefitting", + "share_percent" + ] + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_takeup_2024_25/hmrc_ea_takeup_by_sector.csv b/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_takeup_2024_25/hmrc_ea_takeup_by_sector.csv new file mode 100644 index 0000000000..392ec29afe --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_takeup_2024_25/hmrc_ea_takeup_by_sector.csv @@ -0,0 +1,19 @@ +sic_section,sic_description,employers_benefitting,share_percent +A,"Agriculture, forestry and fishing",26000,2 +C,Manufacturing,61000,5 +F,Construction,160000,13 +G,Wholesale and retail trade; repair of motor vehicles and motorcycles,205000,17 +H,Transportation and storage,39000,3 +I,Accommodation and food service activities,127000,10 +J,Information and communication,58000,5 +K,Financial and insurance activities,18000,1 +L,Real estate activities,35000,3 +M,"Professional, scientific and technical activities",147000,12 +N,Administrative and support service activities,100000,8 +P,Education,23000,2 +Q,Human health and social work activities,67000,5 +R,"Arts, entertainment and recreation",27000,2 +S,Other service activities,75000,6 +T,Activities of households as employers...,50000,4 +"B,D,E,O,U",Other,6000,<1 +Total,Total,1223000,100 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_takeup_2024_25/hmrc_ea_takeup_by_sector.csv.provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_takeup_2024_25/hmrc_ea_takeup_by_sector.csv.provenance.json new file mode 100644 index 0000000000..7bf6e8d212 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_takeup_2024_25/hmrc_ea_takeup_by_sector.csv.provenance.json @@ -0,0 +1,41 @@ +{ + "kind": "uk_firm_employment_allowance_takeup_fixture", + "schema_version": 1, + "period": "tax year 2024-25", + "accessed": "2026-11-22", + "url": "https://assets.publishing.service.gov.uk/media/684bf34372e2ed81c079700c/Employment_Allowance_2024-2025.ods", + "landing_page": "https://www.gov.uk/government/statistics/employment-allowance-take-up-2024-to-2025-tax-year-estimate", + "edition": "Employment Allowance take-up statistics: 2024 to 2025 tax year estimates", + "published": "2025-06-25", + "published_note": "Cover_Sheet: 'The data tables in this spreadsheet were originally published at 9:30am 25 June 2025.' The next publication was due June 2026.", + "publisher": "HM Revenue and Customs", + "licence": "Open Government Licence v3.0", + "sha256": "3848abed310515a0882c5f59a34b0b5e2f350155965f22ff3b173b55a0ceaaf0", + "size_bytes": 32709, + "source_file": "ea_2024_25.ods", + "sheet": "2_Sector_breakdown", + "sheets_read": [ + "Cover_Sheet", + "2_Sector_breakdown" + ], + "columns": [ + "2024 to 2025 tax year: Employers benefitting from EA", + "2024 to 2025 tax year: % of EA beneficiaries" + ], + "method": "Every figure was read from the downloaded workbook on the access date by tools/extract_uk_firm_employment_allowance_takeup.py; none was filled from memory. Counts are as published, rounded by HMRC to the nearest 1,000, with thousands separators removed; shares are whole percent as published. Labels are whitespace-normalised (the region sheet's 'Total ' code loses its trailing space). An employer counts as benefitting when some allowance was offset against its employer NICs paid to HMRC (Cover_Sheet). Sections are SIC 2007 letters; HMRC pools B, D, E, O and U as 'Other', kept here under the code 'B,D,E,O,U' as published. T's description is HMRC's shortened 'Activities of households as employers...'. Sector came from the ONS Business Lookup Table with a 94% match rate; unmatched cases were apportioned by HMRC.", + "tool": "tools/extract_uk_firm_employment_allowance_takeup.py", + "command": "uv run --no-sync python tools/extract_uk_firm_employment_allowance_takeup.py --ods /Employment_Allowance_2024-2025.ods", + "extraction_date": "2026-11-22", + "file": { + "name": "hmrc_ea_takeup_by_sector.csv", + "sha256": "d28f94183d4a466e2695f1ce9cfb2395bbac8b30cf259b70ade71f648219f804", + "bytes": 823, + "rows": 18, + "columns": [ + "sic_section", + "sic_description", + "employers_benefitting", + "share_percent" + ] + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_takeup_2024_25/hmrc_ea_takeup_by_size.csv b/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_takeup_2024_25/hmrc_ea_takeup_by_size.csv new file mode 100644 index 0000000000..b82f38de62 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_takeup_2024_25/hmrc_ea_takeup_by_size.csv @@ -0,0 +1,6 @@ +business_size,employers_benefitting,share_percent +1-9,1049000,86 +10-49,166000,14 +50-249,7000,1 +250+,<500,<1 +Total,1223000,100 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_takeup_2024_25/hmrc_ea_takeup_by_size.csv.provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_takeup_2024_25/hmrc_ea_takeup_by_size.csv.provenance.json new file mode 100644 index 0000000000..c5fa3ee543 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_employment_allowance_takeup_2024_25/hmrc_ea_takeup_by_size.csv.provenance.json @@ -0,0 +1,40 @@ +{ + "kind": "uk_firm_employment_allowance_takeup_fixture", + "schema_version": 1, + "period": "tax year 2024-25", + "accessed": "2026-11-22", + "url": "https://assets.publishing.service.gov.uk/media/684bf34372e2ed81c079700c/Employment_Allowance_2024-2025.ods", + "landing_page": "https://www.gov.uk/government/statistics/employment-allowance-take-up-2024-to-2025-tax-year-estimate", + "edition": "Employment Allowance take-up statistics: 2024 to 2025 tax year estimates", + "published": "2025-06-25", + "published_note": "Cover_Sheet: 'The data tables in this spreadsheet were originally published at 9:30am 25 June 2025.' The next publication was due June 2026.", + "publisher": "HM Revenue and Customs", + "licence": "Open Government Licence v3.0", + "sha256": "3848abed310515a0882c5f59a34b0b5e2f350155965f22ff3b173b55a0ceaaf0", + "size_bytes": 32709, + "source_file": "ea_2024_25.ods", + "sheet": "5_Employer_size_breakdown", + "sheets_read": [ + "Cover_Sheet", + "5_Employer_size_breakdown" + ], + "columns": [ + "2024 to 2025 tax year: Employers benefitting from EA", + "2024 to 2025 tax year: % of EA beneficiaries" + ], + "method": "Every figure was read from the downloaded workbook on the access date by tools/extract_uk_firm_employment_allowance_takeup.py; none was filled from memory. Counts are as published, rounded by HMRC to the nearest 1,000, with thousands separators removed; shares are whole percent as published. Labels are whitespace-normalised (the region sheet's 'Total ' code loses its trailing space). An employer counts as benefitting when some allowance was offset against its employer NICs paid to HMRC (Cover_Sheet). Size is the number of employees on the claiming PAYE scheme at the end of the tax year (sheet note); employers may run several PAYE schemes. The 250+ count and share are published suppressed ('<500', '<1') and are kept as those markers, never as numbers. The bands sum to 1,222,000 against a published total of 1,223,000 (HMRC: 'Sum of employer sizes may not sum to the total due to rounding').", + "tool": "tools/extract_uk_firm_employment_allowance_takeup.py", + "command": "uv run --no-sync python tools/extract_uk_firm_employment_allowance_takeup.py --ods /Employment_Allowance_2024-2025.ods", + "extraction_date": "2026-11-22", + "file": { + "name": "hmrc_ea_takeup_by_size.csv", + "sha256": "6f1b526dc67fffa2fa247514ca7fa96c75d4b0218a304e0d22402e97661c235a", + "bytes": 126, + "rows": 5, + "columns": [ + "business_size", + "employers_benefitting", + "share_percent" + ] + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_empty_property_2024_25/mhclg_nndr1_empty_hereditaments.csv b/packages/microcosm-build/tests/fixtures/uk/firm_empty_property_2024_25/mhclg_nndr1_empty_hereditaments.csv new file mode 100644 index 0000000000..1cf49e8f92 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_empty_property_2024_25/mhclg_nndr1_empty_hereditaments.csv @@ -0,0 +1,15 @@ +snapshot_date,variable,label,england_hereditaments +2023-12-31,hdit_mr_empty,Mandatory Relief for empty premises,175870 +2023-12-31,hdit_mr_emptyind,"Empty premises that are classed as ""industrial property"" above the exemption threshold",12081 +2023-12-31,hdit_mr_emptylisted,"Empty premises those that have ""listed building status""",26317 +2023-12-31,hdit_mr_emptycasc,"Empty premises that are ""Community Amateur Sports Clubs""",570 +2023-12-31,hdit_mr_emptycharity,"Empty premises that are ""charities""",973 +2023-12-31,hdit_mr_emptyoth,Empty premises not included in previous four categories,93557 +2023-12-31,hdit_mr_emptyabove,"Empty premises that are classed as ""non-industrial"" above the exemption threshold",42372 +2024-12-31,hdit_mr_empty,Mandatory Relief for empty premises,178507 +2024-12-31,hdit_mr_emptyind,"Empty premises that are classed as ""industrial property"" above the exemption threshold",12873 +2024-12-31,hdit_mr_emptylisted,"Empty premises those that have ""listed building status""",26832 +2024-12-31,hdit_mr_emptycasc,"Empty premises that are ""Community Amateur Sports Clubs""",16 +2024-12-31,hdit_mr_emptycharity,"Empty premises that are ""charities""",1294 +2024-12-31,hdit_mr_emptyoth,Empty premises not included in previous four categories,97733 +2024-12-31,hdit_mr_emptyabove,"Empty premises that are classed as ""non-industrial"" above the exemption threshold",39759 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_empty_property_2024_25/mhclg_nndr1_empty_relief_value.csv b/packages/microcosm-build/tests/fixtures/uk/firm_empty_property_2024_25/mhclg_nndr1_empty_relief_value.csv new file mode 100644 index 0000000000..568168ae54 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_empty_property_2024_25/mhclg_nndr1_empty_relief_value.csv @@ -0,0 +1,15 @@ +forecast_year,variable,label,england_value_gbp +2024-25,value_empty,Estimated value of empty property relief to be granted in 2024-25,1040932319 +2024-25,value_emptyind,Relief to be given to industrial property above the exemption threshold,93976929 +2024-25,value_emptylisted,Empty Property Relief value - listed building status,442786939 +2024-25,value_emptycasc,Empty Property Relief value - Community Amateur Sports Clubs,175240 +2024-25,value_emptycharity,Empty Property Relief value - charities,14004126 +2024-25,value_emptyoth,Empty Property Relief value - where the property is empty and not included in the previous categories,265323240 +2024-25,value_emptyabove,Empty Property Relief value - to non-industrial property above the exemption threshold,207668695 +2025-26,value_empty,Estimated value of empty property relief to be granted in 2024-25,-1084979229 +2025-26,value_emptyind,Relief to be given to industrial property above the exemption threshold,-105564889 +2025-26,value_emptylisted,Empty Property Relief value - listed building status,-464165033 +2025-26,value_emptycasc,Empty Property Relief value - Community Amateur Sports Clubs,-1031081 +2025-26,value_emptycharity,Empty Property Relief value - charities,-18439472 +2025-26,value_emptyoth,Empty Property Relief value - where the property is empty and not included in the previous categories,-291953680 +2025-26,value_emptyabove,Empty Property Relief value - to non-industrial property above the exemption threshold,-197607483 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_empty_property_2024_25/mhclg_nndr3_2024_25.csv b/packages/microcosm-build/tests/fixtures/uk/firm_empty_property_2024_25/mhclg_nndr3_2024_25.csv new file mode 100644 index 0000000000..7ef06ed12e --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_empty_property_2024_25/mhclg_nndr3_2024_25.csv @@ -0,0 +1,7 @@ +item,table,row_label,year,value,unit +gross_rates_payable,Table_1,Gross rates payable in year,2024 to 2025 [R],35439.30771,GBP million +empty_premises_relief,Table_2,Of which empty premises,2024 to 2025 [R],1275.504353,GBP million +hereditaments_30_sept,Table_1a,Number of hereditaments on rating list as at 30 Sept ('000s),2024 to 2025,2011,thousand +aggregate_rateable_value_30_sept,Table_1a,Total aggregate rateable value of all hereditaments on rating list as at 30 Sept (£ million),2024 to 2025,67968,GBP million +small_business_multiplier,Table_1a,Small business rate multiplier (pence),2024 to 2025,49.9,pence +standard_multiplier,Table_1a,National non-domestic rates multiplier (pence),2024 to 2025,54.6,pence diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_empty_property_2024_25/provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_empty_property_2024_25/provenance.json new file mode 100644 index 0000000000..2db9c8486e --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_empty_property_2024_25/provenance.json @@ -0,0 +1,78 @@ +{ + "kind": "uk_firm_empty_property_fixture", + "schema_version": 1, + "period": "2024-25: relief counts as at 31 December 2023 and 2024, relief value forecasts for 2024-25 and 2025-26, and the 2024-25 NNDR3 outturn", + "accessed": "2026-11-23", + "method": "Values were read from the downloaded files on the access date by tools/extract_uk_firm_empty_property_tables.py, from the England row of each supplementary sheet (columns found by MHCLG variable name) and the '2024 to 2025' column of NNDR3 Tables 1, 1a and 2; none was filled from memory.", + "sources": { + "nndr1_2024_25": { + "landing_page": "https://www.gov.uk/government/statistics/national-non-domestic-rates-collected-by-councils-in-england-forecast-2024-to-2025", + "url": "https://assets.publishing.service.gov.uk/media/663b98e474933dccbbb6c431/NNDR1_2024-25_Supplementary_table.xlsx", + "edition": "National non-domestic rates collected by councils in England: forecast 2024 to 2025; supplementary data tables (added 9 May 2024)", + "publisher": "Ministry of Housing, Communities and Local Government", + "file": "NNDR1_2024-25_Supplementary_table.xlsx", + "size_bytes": 164616, + "sha256": "69da6a689dd3121dd40affa8c7b48117c423b4f8a2300d54d2d5e54ac3fb82a4", + "licence": "Open Government Licence v3.0", + "sheets": [ + "NNDR1S Hereditaments Data", + "NNDR1S Relief data" + ] + }, + "nndr1_2025_26": { + "landing_page": "https://www.gov.uk/government/statistics/national-non-domestic-rates-collected-by-councils-in-england-forecast-2025-to-2026", + "url": "https://assets.publishing.service.gov.uk/media/67d2c9c4814acba3755e97c1/NNDR1_2025-26_Supplementary_table__ecomms_.xlsx", + "edition": "National non-domestic rates collected by councils in England: forecast 2025 to 2026; supplementary data tables (added 13 March 2025)", + "publisher": "Ministry of Housing, Communities and Local Government", + "file": "NNDR1_2025-26_Supplementary_table__ecomms_.xlsx", + "size_bytes": 162273, + "sha256": "5d7501eabad4de45f65c9fd45b1a7d48bf22a3a0bee722d64fb72012b6be60fc", + "licence": "Open Government Licence v3.0", + "sheets": [ + "NNDR1S Hereditaments Data", + "NNDR1S Relief data" + ] + }, + "nndr3_2024_25": { + "landing_page": "https://www.gov.uk/government/statistics/national-non-domestic-rates-collected-by-councils-in-england-2024-to-2025", + "url": "https://assets.publishing.service.gov.uk/media/6977f8533fd50ac304b79790/NNDR3_2024-25_Tables_1-3_accessible_gov.uk__Values_only__-_3rd_Release.ods", + "edition": "National non-domestic rates collected by councils in England: 2024 to 2025; Tables 1-3: England, 3rd release (updated 27 January 2026)", + "publisher": "Ministry of Housing, Communities and Local Government", + "file": "NNDR3_2024-25_Tables_1-3_accessible_gov.uk__Values_only__-_3rd_Release.ods", + "size_bytes": 35587, + "sha256": "f28b9bf086aa5c03fac29d171d6a40e937fbc57ea149fedb8c37239edf0ae32e", + "licence": "Open Government Licence v3.0", + "sheets": [ + "Table_1", + "Table_1a", + "Table_2" + ] + } + }, + "coverage": "Counts are hereditaments in receipt of mandatory empty premises relief at the snapshot date, not all empty hereditaments: an empty property past its 3-month (6 for industrial) exemption pays full rates and is not counted. The six sub-categories (industrial above the exemption threshold, listed building, community amateur sports club, charity, not in the previous four, non-industrial above the exemption threshold) partition the total; the relief value sub-categories do not quite sum to the relief total as published. No source gives the rateable value of empty property, empty shares by property type, or empty durations.", + "caveats": [ + "NNDR1 2024-25 supplementary Note 7: the split of empty property relief by category was first published in 2024-25 and was validated against earlier unvalidated data; use with caution.", + "NNDR1 2025-26 Table 4 Note 25: for 2024 the empty premises hereditament count is under investigation for 2 local authorities; data are as provided by the authorities.", + "The NNDR1 2025-26 relief labels read 'to be granted in 2024-25' as published; the forecast year is taken from the sheet title, and the total equals Table 2's 2025-26 empty premises forecast (\u00a31,084.979229 million).", + "NNDR1 2024-25 supplementary Note 3: Three Rivers and Watford supplied no supplementary figures for 31 December 2023." + ], + "extraction_date": "2026-11-23", + "tool": "tools/extract_uk_firm_empty_property_tables.py", + "files": { + "mhclg_nndr1_empty_hereditaments.csv": { + "sha256": "e218cf5cdd52097e253472d34434b185c4865231e00160a5d4530e3caadd4dea", + "bytes": 1395, + "rows": 14 + }, + "mhclg_nndr1_empty_relief_value.csv": { + "sha256": "58448f3edf3706de9b8ac1086ecef210306a2f3520e56956aa4693b94d8829f7", + "bytes": 1486, + "rows": 14 + }, + "mhclg_nndr3_2024_25.csv": { + "sha256": "7daf60b3babadcff6644f2de425524590a72e64aa98dd635c42f8bf7affa85cf", + "bytes": 713, + "rows": 6 + } + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_pay_distribution_2024/ashe_section_annual_pay_percentiles.csv b/packages/microcosm-build/tests/fixtures/uk/firm_pay_distribution_2024/ashe_section_annual_pay_percentiles.csv new file mode 100644 index 0000000000..afc97ff75b --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_pay_distribution_2024/ashe_section_annual_pay_percentiles.csv @@ -0,0 +1,23 @@ +sic_section,description,jobs_thousand,mean,p10,p20,p25,p30,p40,p50,p60,p70,p75,p80,p90 +A,"AGRICULTURE, FORESTRY AND FISHING",139.0,29689.3,x,14400.0,17913.0,21495.5,25928.5,28582.2,31850.8,35053.1,37836.9,40357.1,x +B,MINING AND QUARRYING,38.0,59336.7,29273.4,35969.3,38333.5,39805.2,45140.9,50878.5,58822.1,68479.2,73585.8,80241.2,x +C,MANUFACTURING,2240.0,43879.2,22548.5,26427.5,28012.3,29687.4,33228.4,37230.0,42221.0,48574.3,52293.2,56557.5,71069.8 +D,"ELECTRICITY, GAS, STEAM AND AIR CONDITIONING SUPPLY",103.0,59338.9,28141.0,34916.0,37962.4,41582.3,46056.8,53088.7,59447.0,67750.8,72076.5,78508.7,97502.7 +E,"WATER SUPPLY; SEWERAGE, WASTE MANAGEMENT AND REMEDIATION ACTIVITIES",197.0,42777.1,24735.4,28939.6,30808.8,32879.4,36580.2,39826.2,43367.7,47534.9,50000.0,53125.5,62066.8 +F,CONSTRUCTION,942.0,45321.3,12960.0,24503.6,27246.8,29933.9,34389.0,39106.3,44730.9,51180.1,55000.0,60101.3,76335.6 +G,WHOLESALE AND RETAIL TRADE; REPAIR OF MOTOR VEHICLES AND MOTORCYCLES,3262.0,31679.1,9257.8,13219.0,15508.8,17997.1,23101.1,26279.1,29959.3,34847.9,38009.7,42269.0,56395.5 +H,TRANSPORTATION AND STORAGE,1072.0,44282.1,19184.6,26272.7,28257.7,30000.0,33481.3,37376.7,41600.0,46820.2,50186.3,54652.3,72414.1 +I,ACCOMMODATION AND FOOD SERVICE ACTIVITIES,1052.0,21528.1,4518.1,8180.7,9610.5,11006.1,13968.2,18198.2,22733.9,26527.7,28735.9,31149.1,39214.1 +J,INFORMATION AND COMMUNICATION,1052.0,62473.6,24000.0,30951.8,34165.1,37116.7,43002.5,49702.1,57354.0,67000.0,73445.4,80532.9,105131.7 +K,FINANCIAL AND INSURANCE ACTIVITIES,975.0,84079.9,24029.4,29464.0,32552.8,35749.9,43932.7,53773.9,64848.8,79126.7,88958.0,100004.0,147546.9 +L,REAL ESTATE ACTIVITIES,382.0,39526.8,12600.0,21968.8,24361.3,26130.6,29441.6,33000.0,36929.0,41597.6,45198.6,50334.1,66397.5 +M,"PROFESSIONAL, SCIENTIFIC AND TECHNICAL ACTIVITIES",1982.0,55186.8,16231.1,25190.0,27887.0,30211.8,35499.7,41679.2,48764.1,57991.4,64141.9,71799.5,96691.2 +N,ADMINISTRATIVE AND SUPPORT SERVICE ACTIVITIES,1183.0,36756.9,7995.9,13279.6,17006.9,20759.1,25416.6,28893.3,33391.6,39239.5,43266.3,48658.2,68153.5 +O,PUBLIC ADMINISTRATION AND DEFENCE; COMPULSORY SOCIAL SECURITY,1675.0,39545.6,17365.8,25992.0,28110.5,30351.0,34224.6,37950.5,42001.4,47325.5,49881.4,52805.0,62118.7 +P,EDUCATION,3326.0,33876.5,9854.7,16626.9,19202.2,21806.1,26829.0,31770.0,36937.9,42708.0,45789.5,48914.4,57769.3 +Q,HUMAN HEALTH AND SOCIAL WORK ACTIVITIES,4272.0,34429.7,11830.6,17355.5,19956.1,22448.3,25930.4,29485.1,33536.9,38936.3,42308.4,46150.2,57390.4 +R,"ARTS, ENTERTAINMENT AND RECREATION",477.0,30034.1,3179.4,7440.2,10060.0,12570.0,18387.8,24041.0,27943.6,32377.6,35505.9,39305.8,54901.9 +S,OTHER SERVICE ACTIVITIES,443.0,31510.8,8600.0,12570.0,15138.2,17983.5,23299.3,26857.5,30632.5,35297.0,38473.4,42788.4,57269.1 +T,ACTIVITIES OF HOUSEHOLDS AS EMPLOYERS; UNDIFFERENTIATED GOODS-AND SERVICES-PRODUCING ACTIVITIES OF HOUSEHOLDS FOR OWN USE,71.0,16061.1,2074.6,3923.7,5334.6,6389.2,8887.2,11950.9,15549.3,20254.1,23508.3,26709.3,x +U,ACTIVITIES OF EXTRATERRITORIAL ORGANISATIONS AND BODIES,x,x,x,x,x,x,x,x,x,x,x,x,x +ALL,ALL EMPLOYEES,24889.0,40444.9,11412.1,18505.5,22000.0,24488.0,28550.1,32856.6,38000.0,44556.0,48398.5,52939.4,69766.7 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_pay_distribution_2024/ashe_section_annual_pay_percentiles.csv.provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_pay_distribution_2024/ashe_section_annual_pay_percentiles.csv.provenance.json new file mode 100644 index 0000000000..f930fbca3e --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_pay_distribution_2024/ashe_section_annual_pay_percentiles.csv.provenance.json @@ -0,0 +1,47 @@ +{ + "kind": "uk_firm_pay_distribution_fixture", + "schema_version": 1, + "period": "2024-25", + "accessed": "2026-11-22", + "method": "Cells were copied from the downloaded workbook by tools/extract_uk_firm_pay_distribution_table.py; none was filled from memory. p50 is the sheet's Median column. A cell ONS does not publish keeps its marker ('x' unreliable, ':' not available).", + "sources": { + "ons_ashe_table_4": { + "publisher": "Office for National Statistics", + "landing_page": "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/earningsandworkinghours/datasets/industry2digitsicashetable4", + "url": "https://www.ons.gov.uk/file?uri=/employmentandlabourmarket/peopleinwork/earningsandworkinghours/datasets/industry2digitsicashetable4/2025revised/ashetable42025revised.zip", + "edition": "2025 revised", + "sha256": "df87c313d1cb40bf499f1ec001076bcb9c9884c6443d76b186f09e84ff614bc3", + "size_bytes": 2961773, + "member": "sic07 Industry (2) Table 4.7a Annual pay - Gross 2025.xlsx", + "member_sha256": "5ec5fe60b9aaae2555996cbb66f8d4c29868105e59384b95d85db36462728baf", + "sheet": "All", + "sheet_title": "SIC2007 Table 4 .7a Annual pay - Gross (\u00a3) - For all employee jobsa: United Kingdom 2025", + "reference_period": "ASHE annual estimates are for the tax year that ended on 5 April of the reference year: the 2025 edition is 2024-25.", + "coverage": "Employees on adult rates in the same job for more than a year; all employee jobs, full-time and part-time.", + "licence": "Open Government Licence v3.0" + } + }, + "files": { + "ashe_section_annual_pay_percentiles.csv": { + "sha256": "eed711c231c9d91570cf982b912088715ff40830b90df45c76cd3a012ebe809e", + "bytes": 3174, + "columns": [ + "sic_section", + "description", + "jobs_thousand", + "mean", + "p10", + "p20", + "p25", + "p30", + "p40", + "p50", + "p60", + "p70", + "p75", + "p80", + "p90" + ] + } + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_paybill_2024/.provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_paybill_2024/.provenance.json new file mode 100644 index 0000000000..73f4076b2c --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_paybill_2024/.provenance.json @@ -0,0 +1,49 @@ +{ + "source": { + "publisher": "Office for National Statistics", + "dataset_title": "Earnings and hours worked, industry by two-digit SIC: ASHE Table 4", + "dataset_id": "ASHE: Table 4", + "dataset_url": "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/earningsandworkinghours/datasets/industry2digitsicashetable4", + "edition": "2025 revised", + "download_url": "https://www.ons.gov.uk/file?uri=/employmentandlabourmarket/peopleinwork/earningsandworkinghours/datasets/industry2digitsicashetable4/2025revised/ashetable42025revised.zip", + "zip_file": "ashetable42025revised.zip", + "zip_sha256": "df87c313d1cb40bf499f1ec001076bcb9c9884c6443d76b186f09e84ff614bc3", + "zip_bytes": 2961773, + "member": "sic07 Industry (2) Table 4.7a Annual pay - Gross 2025.xlsx", + "member_sha256": "5ec5fe60b9aaae2555996cbb66f8d4c29868105e59384b95d85db36462728baf", + "member_bytes": 165467, + "sheet": "All", + "sheet_title": "SIC2007 Table 4 .7a Annual pay - Gross (\u00a3) - For all employee jobsa: United Kingdom 2025", + "column": "Mean (Annual pay - Gross, GBP)", + "jobs_column": "Number of jobs (thousand), indicative only", + "release_date_note": "The dataset landing page read 'Release date: 22 October 2026' on the access date; that is the page's latest release (the 2026 provisional edition), not necessarily this edition's. The zip's members are dated 13 October 2026.", + "licence": "Open Government Licence v3.0", + "access_date": "2026-11-22" + }, + "reference_period": "Workbook Notes: annual estimates are for the tax year that ended on 5 April in the reference year, so the 2025 edition is tax year 2024-25. The directory is named for the build's rule period, 2024 (tax year 2024-25), not for the ASHE edition.", + "coverage": "Workbook footnote a: employees on adult rates who have been in the same job for more than a year. All employee jobs, full-time and part-time; a person with two jobs counts twice.", + "extraction_date": "2026-11-22", + "tool": "tools/extract_uk_firm_paybill_table.py", + "command": "uv run --no-sync python tools/extract_uk_firm_paybill_table.py --zip /ashetable42025revised.zip", + "unpublished": { + "markers": { + "U": "x" + }, + "rule": "A section whose mean is 'x' or ':' keeps blank numbers and the marker; it is never written as 0." + }, + "all_row": "sic_section 'ALL' is the sheet's 'ALL EMPLOYEES' row, the fallback for sections without a published mean.", + "files": { + "ashe_section_annual_pay.csv": { + "sha256": "5be6605abf436d3bc6d80e911c3e7645a4b687ef62cd115b8fc626b1c9f536a5", + "bytes": 1344, + "rows": 22, + "columns": [ + "sic_section", + "description", + "jobs_thousand", + "mean_annual_gross_pay_gbp", + "marker" + ] + } + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_paybill_2024/ashe_section_annual_pay.csv b/packages/microcosm-build/tests/fixtures/uk/firm_paybill_2024/ashe_section_annual_pay.csv new file mode 100644 index 0000000000..9b50f90a42 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_paybill_2024/ashe_section_annual_pay.csv @@ -0,0 +1,23 @@ +sic_section,description,jobs_thousand,mean_annual_gross_pay_gbp,marker +A,"AGRICULTURE, FORESTRY AND FISHING",139.0,29689.3, +B,MINING AND QUARRYING,38.0,59336.7, +C,MANUFACTURING,2240.0,43879.2, +D,"ELECTRICITY, GAS, STEAM AND AIR CONDITIONING SUPPLY",103.0,59338.9, +E,"WATER SUPPLY; SEWERAGE, WASTE MANAGEMENT AND REMEDIATION ACTIVITIES",197.0,42777.1, +F,CONSTRUCTION,942.0,45321.3, +G,WHOLESALE AND RETAIL TRADE; REPAIR OF MOTOR VEHICLES AND MOTORCYCLES,3262.0,31679.1, +H,TRANSPORTATION AND STORAGE,1072.0,44282.1, +I,ACCOMMODATION AND FOOD SERVICE ACTIVITIES,1052.0,21528.1, +J,INFORMATION AND COMMUNICATION,1052.0,62473.6, +K,FINANCIAL AND INSURANCE ACTIVITIES,975.0,84079.9, +L,REAL ESTATE ACTIVITIES,382.0,39526.8, +M,"PROFESSIONAL, SCIENTIFIC AND TECHNICAL ACTIVITIES",1982.0,55186.8, +N,ADMINISTRATIVE AND SUPPORT SERVICE ACTIVITIES,1183.0,36756.9, +O,PUBLIC ADMINISTRATION AND DEFENCE; COMPULSORY SOCIAL SECURITY,1675.0,39545.6, +P,EDUCATION,3326.0,33876.5, +Q,HUMAN HEALTH AND SOCIAL WORK ACTIVITIES,4272.0,34429.7, +R,"ARTS, ENTERTAINMENT AND RECREATION",477.0,30034.1, +S,OTHER SERVICE ACTIVITIES,443.0,31510.8, +T,ACTIVITIES OF HOUSEHOLDS AS EMPLOYERS; UNDIFFERENTIATED GOODS-AND SERVICES-PRODUCING ACTIVITIES OF HOUSEHOLDS FOR OWN USE,71.0,16061.1, +U,ACTIVITIES OF EXTRATERRITORIAL ORGANISATIONS AND BODIES,,,x +ALL,ALL EMPLOYEES,24889.0,40444.9, diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_paybill_anchor_2024/paybill_anchors.csv b/packages/microcosm-build/tests/fixtures/uk/firm_paybill_anchor_2024/paybill_anchors.csv new file mode 100644 index 0000000000..1ea4ac3cb3 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_paybill_anchor_2024/paybill_anchors.csv @@ -0,0 +1,4 @@ +anchor,period,value,unit,detail +ons_d11_wages_and_salaries,2024,1162752000000.00,GBP,"ONS DTWL, UK wages and salaries (D.11), uses, current prices, SA; QNA" +paye_rti_aggregate_pay,2024-25,1189583389662.00,GBP,"ONS/HMRC PAYE RTI aggregate pay, UK, NSA; sum of April 2024 to March 2025" +paye_rti_payrolled_employees,2024-25,30430260.17,persons,"ONS/HMRC PAYE RTI payrolled employees, UK, NSA; mean of April 2024 to March 2025" diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_paybill_anchor_2024/provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_paybill_anchor_2024/provenance.json new file mode 100644 index 0000000000..1583c66677 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_paybill_anchor_2024/provenance.json @@ -0,0 +1,46 @@ +{ + "kind": "uk_firm_paybill_anchor_fixture", + "schema_version": 1, + "accessed": "2026-11-26", + "use": "report only: model paybill and employees are divided by these anchors in the receipt; never a target, never a guard", + "concept_notes": [ + "D.11 is whole-economy wages and salaries (public and private, including wages in kind) on a national accounts basis, calendar 2024.", + "PAYE RTI aggregate pay covers payrolled employees' pay (pensions excluded) for tax year 2024-25; the employee count is the mean of monthly payrolled employees.", + "The binding paybill guard stays ASHE annual jobs x mean pay (0.85-1.25)." + ], + "sources": { + "dtwl": { + "publisher": "Office for National Statistics", + "series": "DTWL", + "dataset": "Quarterly National Accounts (QNA)", + "series_page": "https://www.ons.gov.uk/economy/grossdomesticproductgdp/timeseries/dtwl/qna", + "url": "https://www.ons.gov.uk/generator?format=csv&uri=/economy/grossdomesticproductgdp/timeseries/dtwl/qna", + "edition": "QNA, released 30 September 2026 (2024 value identical in the 12 November 2026 second estimate, PN2)", + "file": "dtwl_qna.csv", + "size_bytes": 6619, + "sha256": "5948ee2d3da0fe42fab8a27768a18eb6b8ee352e712e02e15c817bf5cb8df1a5" + }, + "rti": { + "publisher": "Office for National Statistics with HM Revenue & Customs", + "dataset": "Real Time Information statistics reference table, not seasonally adjusted", + "landing_page": "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/earningsandworkinghours/datasets/realtimeinformationstatisticsreferencetablenonseasonallyadjusted", + "url": "https://www.ons.gov.uk/file?uri=/employmentandlabourmarket/peopleinwork/earningsandworkinghours/datasets/realtimeinformationstatisticsreferencetablenonseasonallyadjusted/current/rtinsanov2026.xlsx", + "edition": "Earnings and employment from PAYE RTI, UK: November 2026 (17 November 2026)", + "file": "rtinsanov2026.xlsx", + "size_bytes": 2248167, + "sha256": "8aafec63ce93a6a8b299c438faf4ce54a535d9ed331c2e2dc30106b8c163748c", + "sheets": [ + "4. Aggregate pay (UK)", + "1. Payrolled employees (UK)" + ] + } + }, + "tool": "tools/extract_uk_firm_paybill_anchor.py", + "files": { + "paybill_anchors.csv": { + "sha256": "f98bc92ae7babc0ada9473f313debc62b1296a8a1e982c7ff8f5eb5dd96539a7", + "bytes": 425, + "rows": 3 + } + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_public_sector_2025/ons_public_sector_employment.csv b/packages/microcosm-build/tests/fixtures/uk/firm_public_sector_2025/ons_public_sector_employment.csv new file mode 100644 index 0000000000..b51bcca15c --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_public_sector_2025/ons_public_sector_employment.csv @@ -0,0 +1,3 @@ +sector,ons_legal_status,series_id,period,headcount_thousand +central_government,5,G6NQ,Mar 2025,4020 +local_government,6,G6NT,Mar 2025,1977 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_public_sector_2025/ons_public_sector_employment.csv.provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_public_sector_2025/ons_public_sector_employment.csv.provenance.json new file mode 100644 index 0000000000..4ff58da8f4 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_public_sector_2025/ons_public_sector_employment.csv.provenance.json @@ -0,0 +1,56 @@ +{ + "kind": "uk_firm_public_sector_employment_fixture", + "schema_version": 1, + "period": "March 2025 quarter (the last quarter of tax year 2024-25)", + "accessed": "2026-11-22", + "method": "Figures were read from the downloaded workbook on the access date by tools/extract_uk_firm_public_sector_table.py; none was filled from memory. headcount_thousand is the Table 1 cell as published (thousands of people, seasonally adjusted). ons_legal_status is the firm build's mapping of each sector to an ONS business-count legal status (5 central government, 6 local authority), an assumption beyond the source.", + "source": { + "publisher": "Office for National Statistics", + "dataset_title": "Public sector employment", + "landing_page": "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/publicsectorpersonnel/datasets/publicsectoremploymentreferencetable", + "url": "https://www.ons.gov.uk/file?uri=/employmentandlabourmarket/peopleinwork/publicsectorpersonnel/datasets/publicsectoremploymentreferencetable/march2025/datasets8.xlsx", + "edition": "March 2025 edition: Public sector employment, UK: March 2025; Released on 10 June 2025", + "file": "datasets8.xlsx", + "size_bytes": 218985, + "sha256": "00f38ef61bd115ac0acc9a2351530feedd8e68f3982fd86e9a9f823311698cd2", + "sheet": "Table 1", + "table": "Table 1: Public sector employment by sector classification; Headcount; United Kingdom (thousands), seasonally adjusted; row 'Mar 2025'", + "series": { + "central_government": "G6NQ", + "local_government": "G6NT" + }, + "survey": "Quarterly Public Sector Employment Survey", + "licence": "Open Government Licence v3.0" + }, + "edition_note": "The March 2025 edition is not the dataset's latest: the landing page listed a June 2026 edition (release date 15 September 2026) on the access date. The March 2025 edition is used so the headcount is the first published estimate for the quarter that closes the 2024-25 frame; later editions revise it.", + "coverage": "Headcount, full-time and part-time. Table 1 does not list the bodies in each sector; the workbook's Table 2 splits the public sector total by industry (HM Forces, police, public administration, education, National Health Service, other), and its Reclassification notes place English further education colleges and Network Rail in central government. Police (England and Wales) are based on projections (footnote 4). Public corporations (series G7AR) are not extracted.", + "extraction_date": "2026-11-22", + "tool": "tools/extract_uk_firm_public_sector_table.py", + "command": "uv run --no-sync python tools/extract_uk_firm_public_sector_table.py --xlsx /datasets8.xlsx --later-xlsx /datasets3.xlsx", + "files": { + "ons_public_sector_employment.csv": { + "sha256": "e8fafbefc8132178731728854db83fab2dc490d389a3504a0c75a490f3868e15", + "bytes": 138, + "rows": 2, + "columns": [ + "sector", + "ons_legal_status", + "series_id", + "period", + "headcount_thousand" + ] + } + }, + "later_edition": { + "note": "The same row and series in a later edition, recorded for comparison only; the CSV does not use it.", + "url": "https://www.ons.gov.uk/file?uri=/employmentandlabourmarket/peopleinwork/publicsectorpersonnel/datasets/publicsectoremploymentreferencetable/june2026/datasets3.xlsx", + "edition": "Public sector employment, UK: June 2026; Released on 15 September 2026", + "file": "datasets3.xlsx", + "size_bytes": 228246, + "sha256": "99c92dd12ca0dcd6641e5d18a4ce8c97c8135b2f16a9aa7b7f547caf2f827c5e", + "headcount_thousand": { + "central_government": 4024, + "local_government": 1977 + } + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_rateable_value_2024/.provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_rateable_value_2024/.provenance.json new file mode 100644 index 0000000000..9938ae4c8f --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_rateable_value_2024/.provenance.json @@ -0,0 +1,108 @@ +{ + "kind": "uk_firm_rateable_value_fixture", + "schema_version": 1, + "accessed": "2026-11-22", + "rating_list": "2023 rating list (England and Wales), as at 31 March 2026", + "method": "Every figure was copied digit for digit from the downloaded VOA CSV bundle by the tool on the access date; none was filled from memory and none is computed. Rateable values stay in the source's unit, GBP thousand (the bundle's metadata file ndr_sop_variable_names.csv: 'Total rateable value (GBP thousands)'). Band bounds are parsed from the band labels.", + "source": { + "publisher": "Valuation Office Agency", + "title": "Non-domestic rating: stock of properties, March 2026", + "landing_page": "https://www.gov.uk/government/statistics/non-domestic-rating-stock-of-properties-march-2026", + "collection_page": "https://www.gov.uk/government/collections/non-domestic-rating-stock-of-properties-collection", + "url": "https://assets.publishing.service.gov.uk/media/69f9bdf9a96f4d06cda76fbf/ndr_stock_of_properties_2026.zip", + "edition": "Non-domestic rating: stock of properties, March 2026 (published 14 May 2026): stock on the 2023 central and local rating lists as at 31 March 2026", + "edition_note": "The collection page listed this as the latest edition on the access date (landing page public-updated-at 2026-05-14T09:30:00+01:00).", + "zip_file": "ndr_stock_of_properties_2026.zip", + "sha256": "722d59ae5894ba77e08f5eea39f7eb8cf69285b2ef93bf5e2c7b6a21ff643961", + "zip_bytes": 1076301, + "members": { + "table_SOP1_2.csv": { + "sha256": "e1fdfbd208ad23018e54e9af4311b12a462d66da759f2a4df40acf852b84c243", + "bytes": 5472 + }, + "table_SOP2_1.csv": { + "sha256": "b1ec4ce75288b0ec7a8cc97c4643815d9bacb23386e0f1d0d9dce9e8367380d2", + "bytes": 2142 + }, + "table_SOP2_2.csv": { + "sha256": "f84ca3e08f389ec39f104aa2a7484696f4382f451bf3865b8e323c131fbec304", + "bytes": 2141 + }, + "table_SOP2_3.csv": { + "sha256": "f225b7b684836cabf2d92ee53474f09c0d3adea22f3be383d3de3fd5518cc7d9", + "bytes": 1878 + }, + "table_SOP3_1.csv": { + "sha256": "bbb1ff44e56aa93fbee5548240a588bbc55debebc847738f2359b1bc1e747921", + "bytes": 64846 + }, + "table_SOP3_2.csv": { + "sha256": "f1f9fc86691c9c50555973eedbeefd8dac6a4d07358559224bbbb32002e77f9e", + "bytes": 74340 + } + }, + "licence": "Open Government Licence v3.0" + }, + "coverage": "Hereditaments (rateable properties), not firms, in England and Wales. Scotland and Northern Ireland have their own valuation rolls and are not in the release. Table SOP1.1 of the same bundle lists central rating list rateable value separately; it is not extracted.", + "reference_period": "Stock at 31 March 2026 on the 2023 rating lists (in force 1 April 2023 to 31 March 2026). The directory is named for the firm build's rule period, 2024 (tax year 2024-25), not for the VOA edition; voa_stock_by_year.csv carries the all-property stock at 31 March 2024, 2025 and 2026 from the same bundle.", + "suppression": "A Table SOP1.2 row the VOA marks '[c]' keeps blank numbers and the marker; it is never written as 0.", + "extraction_date": "2026-11-22", + "tool": "tools/extract_uk_firm_rateable_value_tables.py", + "command": "uv run --no-sync python tools/extract_uk_firm_rateable_value_tables.py --zip /ndr_stock_of_properties_2026.zip", + "files": { + "voa_rv_band_sector.csv": { + "sha256": "b8ee4c5b6912d97a5597a4264d49accf8afbd51e6a41bb13205da5909cab288b", + "bytes": 16453, + "rows": 285, + "columns": [ + "geography", + "rv_band", + "band_lower_gbp", + "band_upper_gbp", + "sector", + "hereditaments", + "total_rv_gbp_thousand" + ], + "source_members": [ + "table_SOP2_1.csv", + "table_SOP2_2.csv", + "table_SOP2_3.csv" + ] + }, + "voa_property_type.csv": { + "sha256": "4e8c86e0daa35c6e6bb3f5790939a2a35bd12e34e1876db1dad1d5a4de4db066", + "bytes": 9534, + "rows": 138, + "columns": [ + "geography", + "prop_type_code", + "parent_code", + "level", + "description", + "hereditaments", + "total_rv_gbp_thousand", + "mean_rv_gbp_thousand", + "median_rv_gbp_thousand", + "marker" + ], + "source_members": [ + "table_SOP1_2.csv" + ] + }, + "voa_stock_by_year.csv": { + "sha256": "7ac8cc506c6e8a80f3598e06c37266ecb26102075ec1042a95a0418e73eba1f3", + "bytes": 394, + "rows": 9, + "columns": [ + "geography", + "as_at", + "hereditaments", + "total_rv_gbp_thousand" + ], + "source_members": [ + "table_SOP3_1.csv", + "table_SOP3_2.csv" + ] + } + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_rateable_value_2024/voa_property_type.csv b/packages/microcosm-build/tests/fixtures/uk/firm_rateable_value_2024/voa_property_type.csv new file mode 100644 index 0000000000..3199ac1a7f --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_rateable_value_2024/voa_property_type.csv @@ -0,0 +1,139 @@ +geography,prop_type_code,parent_code,level,description,hereditaments,total_rv_gbp_thousand,mean_rv_gbp_thousand,median_rv_gbp_thousand,marker +england_and_wales,ALL,,all,All Properties,2138260,70853994,33.1,8.1, +england_and_wales,C,ALL,sector,Commercial,1609570,49826789,31,7.9, +england_and_wales,CA,C,sub_sector,Advertising rights,34630,129421,3.7,0.8, +england_and_wales,CC,C,sub_sector,Holiday sites,9330,315989,33.9,6.1, +england_and_wales,CG,C,sub_sector,Garages & petrol stations,39090,1514838,38.7,13, +england_and_wales,CH,C,sub_sector,Hotels etc.,94590,1641552,17.4,2.9, +england_and_wales,CL,C,sub_sector,Pubs & wine bars,51430,1530276,29.8,15, +england_and_wales,CM,C,sub_sector,Markets,940,32605,34.6,7.9, +england_and_wales,CO,C,sub_sector,Offices,428840,16164807,37.7,7, +england_and_wales,CP,C,sub_sector,Car parks,81030,701747,8.7,1.5, +england_and_wales,CR,C,sub_sector,Restaurants & cafes,52320,1827875,34.9,17.5, +england_and_wales,CS,C,sub_sector,Shops,500150,12683066,25.4,9.4, +england_and_wales,CS7,CS,shop_type,Showroom and premises,8210,239974,29.2,16.5, +england_and_wales,CS8,CS,shop_type,Hypermarket and premises,30,36965,1320.2,1510, +england_and_wales,CS9,CS,shop_type,Superstore and premises,2180,2314594,1061.3,1060, +england_and_wales,CS1,CS,shop_type,Other Shops,489730,10091533,20.6,9.3, +england_and_wales,CW,C,sub_sector,Warehouses & stores,277360,12024914,43.4,9.8, +england_and_wales,CX,C,sub_sector,Other commercial,39870,1259697,31.6,6.8, +england_and_wales,E,ALL,sector,"Educational, training & cultural",48080,4941921,102.8,38.3, +england_and_wales,EL,E,sub_sector,Local authority schools & colleges,24080,2830031,117.5,57, +england_and_wales,EM,E,sub_sector,Libraries and museums,4450,276583,62.2,12.8, +england_and_wales,EP,E,sub_sector,Private schools & colleges,3720,578351,155.4,59, +england_and_wales,EU,E,sub_sector,Universities,1050,822642,787.2,257.5, +england_and_wales,EX,E,sub_sector,"Other educational, training and cultural",14790,434314,29.4,19.5, +england_and_wales,U,ALL,sector,Utilities,26280,1320709,50.3,1.2, +england_and_wales,FD,U,sub_sector,Docks,150,77903,533.6,22, +england_and_wales,FE,U,sub_sector,Electricity companies,5240,620710,118.4,13, +england_and_wales,NT,U,sub_sector,"Bus stations, moorings etc.",2010,88562,44.1,3.4, +england_and_wales,NX,U,sub_sector,Other utilities,18880,533535,28.3,0.8, +england_and_wales,I,ALL,sector,Industrial,271360,8163580,30.1,9, +england_and_wales,IF,I,sub_sector,"Factories, mills & workshops",260070,6715114,25.8,8.8, +england_and_wales,IM,I,sub_sector,"Quarries, mines etc.",5370,704738,131.3,41.3, +england_and_wales,IX,I,sub_sector,Other industrial,5920,743728,125.6,28.8, +england_and_wales,L,ALL,sector,Leisure,97310,2194390,22.6,4.4, +england_and_wales,LC,L,sub_sector,Community centres & halls,35180,818633,23.3,5.5, +england_and_wales,LI,L,sub_sector,Sports centres & stadia,750,230218,307,117, +england_and_wales,LS,L,sub_sector,"Sports grounds, golf courses etc",11080,315693,28.5,9.3, +england_and_wales,LT,L,sub_sector,"Cinemas, theatres etc.",2570,196213,76.3,32, +england_and_wales,LX,L,sub_sector,Other leisure,47730,633634,13.3,2, +england_and_wales,M,ALL,sector,Miscellaneous,85660,4406605,51.4,9.3, +england_and_wales,MC,M,sub_sector,Cemeteries and crematoria,2880,67032,23.3,3.3, +england_and_wales,MH,M,sub_sector,Medical facilities,27240,1686708,61.9,15.8, +england_and_wales,ML,M,sub_sector,Local government offices,1800,174189,96.6,15.5, +england_and_wales,MP,M,sub_sector,Police stations & courts,1820,410704,225.3,60, +england_and_wales,MR,M,sub_sector,Hostels & homes,1620,24998,15.5,5.9, +england_and_wales,MX,M,sub_sector,Other properties,50300,2042973,40.6,7.8, +england,ALL,,all,All Properties,2013470,68437352,34,8.3, +england,C,ALL,sector,Commercial,1518370,48350815,31.8,8.1, +england,CA,C,sub_sector,Advertising rights,33710,127072,3.8,0.8, +england,CC,C,sub_sector,Holiday sites,7560,276419,36.6,6.1, +england,CG,C,sub_sector,Garages & petrol stations,36200,1455343,40.2,13.5, +england,CH,C,sub_sector,Hotels etc.,85420,1573934,18.4,2.9, +england,CL,C,sub_sector,Pubs & wine bars,47450,1454514,30.7,15.5, +england,CM,C,sub_sector,Markets,870,31229,36,8.1, +england,CO,C,sub_sector,Offices,408550,15887950,38.9,7.3, +england,CP,C,sub_sector,Car parks,78430,678166,8.6,1.5, +england,CR,C,sub_sector,Restaurants & cafes,49440,1767580,35.8,18, +england,CS,C,sub_sector,Shops,471950,12213253,25.9,9.6, +england,CS7,CS,shop_type,Showroom and premises,7840,231779,29.6,16.5, +england,CS8,CS,shop_type,Hypermarket and premises,30,35625,1319.4,1510, +england,CS9,CS,shop_type,Superstore and premises,2050,2195073,1072.9,1080, +england,CS1,CS,shop_type,Other Shops,462040,9750777,21.1,9.5, +england,CW,C,sub_sector,Warehouses & stores,261350,11665484,44.6,10, +england,CX,C,sub_sector,Other commercial,37460,1219872,32.6,7, +england,E,ALL,sector,"Educational, training & cultural",45080,4779967,106,39.8, +england,EL,E,sub_sector,Local authority schools & colleges,22340,2724240,121.9,60, +england,EM,E,sub_sector,Libraries and museums,4100,271241,66.2,13.5, +england,EP,E,sub_sector,Private schools & colleges,3650,573525,157.2,60, +england,EU,E,sub_sector,Universities,970,787808,813,266, +england,EX,E,sub_sector,"Other educational, training and cultural",14020,423153,30.2,20, +england,U,ALL,sector,Utilities,24660,1208109,49,1.1, +england,FD,U,sub_sector,Docks,120,74938,609.3,27.3, +england,FE,U,sub_sector,Electricity companies,4550,531045,116.7,12.8, +england,NT,U,sub_sector,"Bus stations, moorings etc.",1970,87475,44.4,3.3, +england,NX,U,sub_sector,Other utilities,18010,514652,28.6,0.8, +england,I,ALL,sector,Industrial,254110,7752099,30.5,9.2, +england,IF,I,sub_sector,"Factories, mills & workshops",243680,6385787,26.2,9, +england,IM,I,sub_sector,"Quarries, mines etc.",4930,679618,137.9,43.3, +england,IX,I,sub_sector,Other industrial,5510,686694,124.7,28.8, +england,L,ALL,sector,Leisure,91810,2103709,22.9,4.4, +england,LC,L,sub_sector,Community centres & halls,32190,779210,24.2,5.5, +england,LI,L,sub_sector,Sports centres & stadia,700,221311,316.2,121, +england,LS,L,sub_sector,"Sports grounds, golf courses etc",10360,302688,29.2,9.5, +england,LT,L,sub_sector,"Cinemas, theatres etc.",2380,187675,78.9,34, +england,LX,L,sub_sector,Other leisure,46180,612824,13.3,2, +england,M,ALL,sector,Miscellaneous,79440,4242653,53.4,9.7, +england,MC,M,sub_sector,Cemeteries and crematoria,2640,64226,24.3,3.7, +england,MH,M,sub_sector,Medical facilities,25170,1622276,64.5,16.5, +england,ML,M,sub_sector,Local government offices,1690,160067,94.8,14.5, +england,MP,M,sub_sector,Police stations & courts,1620,392264,242.6,72.5, +england,MR,M,sub_sector,Hostels & homes,1260,22812,18.1,7, +england,MX,M,sub_sector,Other properties,47070,1981009,42.1,7.9, +wales,ALL,,all,All Properties,124790,2416641,19.4,5.4, +wales,C,ALL,sector,Commercial,91210,1475974,16.2,5, +wales,CA,C,sub_sector,Advertising rights,920,2349,2.6,0.5, +wales,CC,C,sub_sector,Holiday sites,1770,39570,22.3,6.3, +wales,CG,C,sub_sector,Garages & petrol stations,2900,59496,20.6,6.9, +wales,CH,C,sub_sector,Hotels etc.,9180,67618,7.4,2.7, +wales,CL,C,sub_sector,Pubs & wine bars,3980,75762,19,9.9, +wales,CM,C,sub_sector,Markets,70,1377,18.6,5.7, +wales,CO,C,sub_sector,Offices,20300,276858,13.6,4.3, +wales,CP,C,sub_sector,Car parks,2600,23581,9.1,1.4, +wales,CR,C,sub_sector,Restaurants & cafes,2880,60296,20.9,9.8, +wales,CS,C,sub_sector,Shops,28190,469812,16.7,6, +wales,CS7,CS,shop_type,Showroom and premises,370,8195,22.1,13, +wales,CS8,CS,shop_type,Hypermarket and premises,,,,,[c] +wales,CS9,CS,shop_type,Superstore and premises,140,119521,885.3,875, +wales,CS1,CS,shop_type,Other Shops,27690,340756,12.3,5.9, +wales,CW,C,sub_sector,Warehouses & stores,16010,359431,22.5,5.5, +wales,CX,C,sub_sector,Other commercial,2410,39825,16.5,4.3, +wales,E,ALL,sector,"Educational, training & cultural",3000,161953,54,19, +wales,EL,E,sub_sector,Local authority schools & colleges,1740,105791,60.8,27.5, +wales,EM,E,sub_sector,Libraries and museums,350,5342,15.5,7.4, +wales,EP,E,sub_sector,Private schools & colleges,70,4826,66.1,18.3, +wales,EU,E,sub_sector,Universities,80,34834,458.3,176, +wales,EX,E,sub_sector,"Other educational, training and cultural",770,11161,14.6,10.5, +wales,U,ALL,sector,Utilities,1620,112600,69.5,5.8, +wales,FD,U,sub_sector,Docks,20,2965,128.9,8.5, +wales,FE,U,sub_sector,Electricity companies,690,89665,129.2,13.6, +wales,NT,U,sub_sector,"Bus stations, moorings etc.",30,1087,32,12.6, +wales,NX,U,sub_sector,Other utilities,870,18883,21.8,3.8, +wales,I,ALL,sector,Industrial,17240,411480,23.9,6.1, +wales,IF,I,sub_sector,"Factories, mills & workshops",16390,329326,20.1,5.9, +wales,IM,I,sub_sector,"Quarries, mines etc.",440,25120,57.4,21, +wales,IX,I,sub_sector,Other industrial,420,57034,136.8,29.3, +wales,L,ALL,sector,Leisure,5500,90681,16.5,4.9, +wales,LC,L,sub_sector,Community centres & halls,2990,39422,13.2,4.9, +wales,LI,L,sub_sector,Sports centres & stadia,50,8907,178.1,92.8, +wales,LS,L,sub_sector,"Sports grounds, golf courses etc",720,13005,18.1,5, +wales,LT,L,sub_sector,"Cinemas, theatres etc.",200,8538,43.8,16.5, +wales,LX,L,sub_sector,Other leisure,1550,20810,13.4,3.6, +wales,M,ALL,sector,Miscellaneous,6220,163952,26.4,6.9, +wales,MC,M,sub_sector,Cemeteries and crematoria,230,2806,12,1.1, +wales,MH,M,sub_sector,Medical facilities,2070,64432,31.1,6.5, +wales,ML,M,sub_sector,Local government offices,120,14122,122.8,27.5, +wales,MP,M,sub_sector,Police stations & courts,210,18441,89.5,16.4, +wales,MR,M,sub_sector,Hostels & homes,360,2186,6.1,3.8, +wales,MX,M,sub_sector,Other properties,3230,61964,19.2,7.1, diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_rateable_value_2024/voa_rv_band_sector.csv b/packages/microcosm-build/tests/fixtures/uk/firm_rateable_value_2024/voa_rv_band_sector.csv new file mode 100644 index 0000000000..2a726a8037 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_rateable_value_2024/voa_rv_band_sector.csv @@ -0,0 +1,286 @@ +geography,rv_band,band_lower_gbp,band_upper_gbp,sector,hereditaments,total_rv_gbp_thousand +england_and_wales,0 - 999,0,999,all,153440,75007 +england_and_wales,0 - 999,0,999,retail,3530,1515 +england_and_wales,0 - 999,0,999,offices,17070,9924 +england_and_wales,0 - 999,0,999,industry,36350,16182 +england_and_wales,0 - 999,0,999,other,96490,47386 +england_and_wales,"1,000 - 1,999",1000,1999,all,155910,231609 +england_and_wales,"1,000 - 1,999",1000,1999,retail,10340,16372 +england_and_wales,"1,000 - 1,999",1000,1999,offices,44890,67698 +england_and_wales,"1,000 - 1,999",1000,1999,industry,33410,49287 +england_and_wales,"1,000 - 1,999",1000,1999,other,67270,98252 +england_and_wales,"2,000 - 3,999",2000,3999,all,299370,879353 +england_and_wales,"2,000 - 3,999",2000,3999,retail,56740,175184 +england_and_wales,"2,000 - 3,999",2000,3999,offices,77060,223748 +england_and_wales,"2,000 - 3,999",2000,3999,industry,67000,199797 +england_and_wales,"2,000 - 3,999",2000,3999,other,98570,280625 +england_and_wales,"4,000 - 6,000",4000,6000,all,256370,1276589 +england_and_wales,"4,000 - 6,000",4000,6000,retail,78980,396035 +england_and_wales,"4,000 - 6,000",4000,6000,offices,54840,271931 +england_and_wales,"4,000 - 6,000",4000,6000,industry,66230,330821 +england_and_wales,"4,000 - 6,000",4000,6000,other,56320,277802 +england_and_wales,"6,001 - 7,999",6001,7999,all,191490,1336946 +england_and_wales,"6,001 - 7,999",6001,7999,retail,62400,434817 +england_and_wales,"6,001 - 7,999",6001,7999,offices,36350,252933 +england_and_wales,"6,001 - 7,999",6001,7999,industry,52180,364124 +england_and_wales,"6,001 - 7,999",6001,7999,other,40560,285073 +england_and_wales,"8,000 - 9,999",8000,9999,all,159100,1416406 +england_and_wales,"8,000 - 9,999",8000,9999,retail,52620,469181 +england_and_wales,"8,000 - 9,999",8000,9999,offices,29360,261661 +england_and_wales,"8,000 - 9,999",8000,9999,industry,45870,409026 +england_and_wales,"8,000 - 9,999",8000,9999,other,31250,276537 +england_and_wales,"10,000 - 12,000",10000,12000,all,141400,1548682 +england_and_wales,"10,000 - 12,000",10000,12000,retail,46660,510769 +england_and_wales,"10,000 - 12,000",10000,12000,offices,25870,283296 +england_and_wales,"10,000 - 12,000",10000,12000,industry,40530,444275 +england_and_wales,"10,000 - 12,000",10000,12000,other,28340,310342 +england_and_wales,"12,001 - 13,999",12001,13999,all,81130,1051403 +england_and_wales,"12,001 - 13,999",12001,13999,retail,26630,345089 +england_and_wales,"12,001 - 13,999",12001,13999,offices,14730,190833 +england_and_wales,"12,001 - 13,999",12001,13999,industry,23670,306794 +england_and_wales,"12,001 - 13,999",12001,13999,other,16100,208687 +england_and_wales,"14,000 - 15,000",14000,15000,all,50070,726219 +england_and_wales,"14,000 - 15,000",14000,15000,retail,15220,220426 +england_and_wales,"14,000 - 15,000",14000,15000,offices,8350,120954 +england_and_wales,"14,000 - 15,000",14000,15000,industry,13440,194708 +england_and_wales,"14,000 - 15,000",14000,15000,other,13060,190130 +england_and_wales,"15,001 - 19,999",15001,19999,all,129640,2241118 +england_and_wales,"15,001 - 19,999",15001,19999,retail,39960,690891 +england_and_wales,"15,001 - 19,999",15001,19999,offices,22670,392478 +england_and_wales,"15,001 - 19,999",15001,19999,industry,36470,631276 +england_and_wales,"15,001 - 19,999",15001,19999,other,30540,526474 +england_and_wales,"20,000 - 24,999",20000,24999,all,88840,1971272 +england_and_wales,"20,000 - 24,999",20000,24999,retail,25540,566665 +england_and_wales,"20,000 - 24,999",20000,24999,offices,15410,342589 +england_and_wales,"20,000 - 24,999",20000,24999,industry,24820,552147 +england_and_wales,"20,000 - 24,999",20000,24999,other,23060,509872 +england_and_wales,"25,000 - 49,999",25000,49999,all,200570,7002252 +england_and_wales,"25,000 - 49,999",25000,49999,retail,49150,1691232 +england_and_wales,"25,000 - 49,999",25000,49999,offices,35920,1251890 +england_and_wales,"25,000 - 49,999",25000,49999,industry,60800,2125552 +england_and_wales,"25,000 - 49,999",25000,49999,other,54700,1933578 +england_and_wales,"50,000 - 50,999",50000,50999,all,4540,228004 +england_and_wales,"50,000 - 50,999",50000,50999,retail,980,49080 +england_and_wales,"50,000 - 50,999",50000,50999,offices,800,39982 +england_and_wales,"50,000 - 50,999",50000,50999,industry,1320,66375 +england_and_wales,"50,000 - 50,999",50000,50999,other,1450,72568 +england_and_wales,"51,000 - 99,999",51000,99999,all,111870,7847728 +england_and_wales,"51,000 - 99,999",51000,99999,retail,21860,1507932 +england_and_wales,"51,000 - 99,999",51000,99999,offices,20280,1424597 +england_and_wales,"51,000 - 99,999",51000,99999,industry,33380,2337572 +england_and_wales,"51,000 - 99,999",51000,99999,other,36350,2577627 +england_and_wales,"100,000 - 249,999",100000,249999,all,72580,11057257 +england_and_wales,"100,000 - 249,999",100000,249999,retail,13420,2095455 +england_and_wales,"100,000 - 249,999",100000,249999,offices,14670,2257351 +england_and_wales,"100,000 - 249,999",100000,249999,industry,20260,3063758 +england_and_wales,"100,000 - 249,999",100000,249999,other,24220,3640694 +england_and_wales,"250,000 - 499,999",250000,499999,all,24640,8463081 +england_and_wales,"250,000 - 499,999",250000,499999,retail,5160,1748930 +england_and_wales,"250,000 - 499,999",250000,499999,offices,5410,1863916 +england_and_wales,"250,000 - 499,999",250000,499999,industry,6070,2082574 +england_and_wales,"250,000 - 499,999",250000,499999,other,7990,2767661 +england_and_wales,"500,000 - 999,999",500000,999999,all,10360,7055767 +england_and_wales,"500,000 - 999,999",500000,999999,retail,1750,1218360 +england_and_wales,"500,000 - 999,999",500000,999999,offices,2750,1882930 +england_and_wales,"500,000 - 999,999",500000,999999,industry,2600,1760739 +england_and_wales,"500,000 - 999,999",500000,999999,other,3260,2193738 +england_and_wales,"1,000,000 and over",1000000,,all,6970,16445299 +england_and_wales,"1,000,000 and over",1000000,,retail,1570,2500098 +england_and_wales,"1,000,000 and over",1000000,,offices,1840,4838860 +england_and_wales,"1,000,000 and over",1000000,,industry,1830,4269175 +england_and_wales,"1,000,000 and over",1000000,,other,1730,4837166 +england_and_wales,Total,,,all,2138260,70853994 +england_and_wales,Total,,,retail,512500,14638031 +england_and_wales,Total,,,offices,428270,15977569 +england_and_wales,Total,,,industry,566240,19204182 +england_and_wales,Total,,,other,631250,21034212 +england,0 - 999,0,999,all,144660,70131 +england,0 - 999,0,999,retail,3140,1333 +england,0 - 999,0,999,offices,15670,9038 +england,0 - 999,0,999,industry,33530,14389 +england,0 - 999,0,999,other,92320,45372 +england,"1,000 - 1,999",1000,1999,all,142570,211650 +england,"1,000 - 1,999",1000,1999,retail,8750,13849 +england,"1,000 - 1,999",1000,1999,offices,41560,62729 +england,"1,000 - 1,999",1000,1999,industry,29360,43434 +england,"1,000 - 1,999",1000,1999,other,62910,91638 +england,"2,000 - 3,999",2000,3999,all,272960,802515 +england,"2,000 - 3,999",2000,3999,retail,50620,156694 +england,"2,000 - 3,999",2000,3999,offices,72220,209785 +england,"2,000 - 3,999",2000,3999,industry,60810,181619 +england,"2,000 - 3,999",2000,3999,other,89310,254417 +england,"4,000 - 6,000",4000,6000,all,237170,1181639 +england,"4,000 - 6,000",4000,6000,retail,72860,365764 +england,"4,000 - 6,000",4000,6000,offices,51640,256165 +england,"4,000 - 6,000",4000,6000,industry,61100,305374 +england,"4,000 - 6,000",4000,6000,other,51570,254336 +england,"6,001 - 7,999",6001,7999,all,179480,1253600 +england,"6,001 - 7,999",6001,7999,retail,58740,409541 +england,"6,001 - 7,999",6001,7999,offices,34640,241132 +england,"6,001 - 7,999",6001,7999,industry,49060,342524 +england,"6,001 - 7,999",6001,7999,other,37030,260403 +england,"8,000 - 9,999",8000,9999,all,150840,1343101 +england,"8,000 - 9,999",8000,9999,retail,50180,447618 +england,"8,000 - 9,999",8000,9999,offices,28310,252312 +england,"8,000 - 9,999",8000,9999,industry,43350,386538 +england,"8,000 - 9,999",8000,9999,other,29010,256633 +england,"10,000 - 12,000",10000,12000,all,135030,1479031 +england,"10,000 - 12,000",10000,12000,retail,44810,490623 +england,"10,000 - 12,000",10000,12000,offices,24980,273603 +england,"10,000 - 12,000",10000,12000,industry,38750,424810 +england,"10,000 - 12,000",10000,12000,other,26480,289996 +england,"12,001 - 13,999",12001,13999,all,77680,1006689 +england,"12,001 - 13,999",12001,13999,retail,25630,332172 +england,"12,001 - 13,999",12001,13999,offices,14280,184930 +england,"12,001 - 13,999",12001,13999,industry,22730,294563 +england,"12,001 - 13,999",12001,13999,other,15040,195025 +england,"14,000 - 15,000",14000,15000,all,47880,694663 +england,"14,000 - 15,000",14000,15000,retail,14660,212271 +england,"14,000 - 15,000",14000,15000,offices,8060,116730 +england,"14,000 - 15,000",14000,15000,industry,12910,187030 +england,"14,000 - 15,000",14000,15000,other,12260,178633 +england,"15,001 - 19,999",15001,19999,all,124140,2145912 +england,"15,001 - 19,999",15001,19999,retail,38600,667353 +england,"15,001 - 19,999",15001,19999,offices,21930,379600 +england,"15,001 - 19,999",15001,19999,industry,34850,603210 +england,"15,001 - 19,999",15001,19999,other,28760,495749 +england,"20,000 - 24,999",20000,24999,all,85140,1888911 +england,"20,000 - 24,999",20000,24999,retail,24700,548015 +england,"20,000 - 24,999",20000,24999,offices,14900,331130 +england,"20,000 - 24,999",20000,24999,industry,23660,526300 +england,"20,000 - 24,999",20000,24999,other,21880,483466 +england,"25,000 - 49,999",25000,49999,all,192780,6732668 +england,"25,000 - 49,999",25000,49999,retail,47530,1635251 +england,"25,000 - 49,999",25000,49999,offices,34920,1217831 +england,"25,000 - 49,999",25000,49999,industry,58330,2040132 +england,"25,000 - 49,999",25000,49999,other,52000,1839455 +england,"50,000 - 50,999",50000,50999,all,4370,219463 +england,"50,000 - 50,999",50000,50999,retail,940,47271 +england,"50,000 - 50,999",50000,50999,offices,780,39029 +england,"50,000 - 50,999",50000,50999,industry,1280,64113 +england,"50,000 - 50,999",50000,50999,other,1380,69051 +england,"51,000 - 99,999",51000,99999,all,107920,7571865 +england,"51,000 - 99,999",51000,99999,retail,21130,1457642 +england,"51,000 - 99,999",51000,99999,offices,19810,1392499 +england,"51,000 - 99,999",51000,99999,industry,32250,2258897 +england,"51,000 - 99,999",51000,99999,other,34730,2462828 +england,"100,000 - 249,999",100000,249999,all,70100,10681805 +england,"100,000 - 249,999",100000,249999,retail,12860,2006792 +england,"100,000 - 249,999",100000,249999,offices,14430,2221619 +england,"100,000 - 249,999",100000,249999,industry,19590,2962107 +england,"100,000 - 249,999",100000,249999,other,23230,3491287 +england,"250,000 - 499,999",250000,499999,all,23860,8202285 +england,"250,000 - 499,999",250000,499999,retail,4920,1669773 +england,"250,000 - 499,999",250000,499999,offices,5340,1839761 +england,"250,000 - 499,999",250000,499999,industry,5880,2016444 +england,"250,000 - 499,999",250000,499999,other,7720,2676308 +england,"500,000 - 999,999",500000,999999,all,10110,6881192 +england,"500,000 - 999,999",500000,999999,retail,1670,1155585 +england,"500,000 - 999,999",500000,999999,offices,2730,1867555 +england,"500,000 - 999,999",500000,999999,industry,2540,1719864 +england,"500,000 - 999,999",500000,999999,other,3180,2138188 +england,"1,000,000 and over",1000000,,all,6790,16070230 +england,"1,000,000 and over",1000000,,retail,1520,2425278 +england,"1,000,000 and over",1000000,,offices,1830,4812510 +england,"1,000,000 and over",1000000,,industry,1790,4174105 +england,"1,000,000 and over",1000000,,other,1650,4658337 +england,Total,,,all,2013470,68437352 +england,Total,,,retail,483250,14042822 +england,Total,,,offices,408010,15707956 +england,Total,,,industry,531760,18545452 +england,Total,,,other,590450,20141122 +wales,0 - 999,0,999,all,8780,4876 +wales,0 - 999,0,999,retail,390,183 +wales,0 - 999,0,999,offices,1410,886 +wales,0 - 999,0,999,industry,2820,1793 +wales,0 - 999,0,999,other,4160,2014 +wales,"1,000 - 1,999",1000,1999,all,13350,19958 +wales,"1,000 - 1,999",1000,1999,retail,1600,2523 +wales,"1,000 - 1,999",1000,1999,offices,3340,4969 +wales,"1,000 - 1,999",1000,1999,industry,4050,5852 +wales,"1,000 - 1,999",1000,1999,other,4360,6614 +wales,"2,000 - 3,999",2000,3999,all,26410,76838 +wales,"2,000 - 3,999",2000,3999,retail,6120,18490 +wales,"2,000 - 3,999",2000,3999,offices,4840,13963 +wales,"2,000 - 3,999",2000,3999,industry,6190,18178 +wales,"2,000 - 3,999",2000,3999,other,9260,26208 +wales,"4,000 - 6,000",4000,6000,all,19200,94951 +wales,"4,000 - 6,000",4000,6000,retail,6120,30272 +wales,"4,000 - 6,000",4000,6000,offices,3200,15766 +wales,"4,000 - 6,000",4000,6000,industry,5130,25447 +wales,"4,000 - 6,000",4000,6000,other,4750,23466 +wales,"6,001 - 7,999",6001,7999,all,12010,83346 +wales,"6,001 - 7,999",6001,7999,retail,3660,25276 +wales,"6,001 - 7,999",6001,7999,offices,1710,11801 +wales,"6,001 - 7,999",6001,7999,industry,3120,21600 +wales,"6,001 - 7,999",6001,7999,other,3530,24669 +wales,"8,000 - 9,999",8000,9999,all,8250,73304 +wales,"8,000 - 9,999",8000,9999,retail,2440,21563 +wales,"8,000 - 9,999",8000,9999,offices,1050,9349 +wales,"8,000 - 9,999",8000,9999,industry,2520,22488 +wales,"8,000 - 9,999",8000,9999,other,2240,19904 +wales,"10,000 - 12,000",10000,12000,all,6370,69651 +wales,"10,000 - 12,000",10000,12000,retail,1840,20147 +wales,"10,000 - 12,000",10000,12000,offices,890,9693 +wales,"10,000 - 12,000",10000,12000,industry,1780,19466 +wales,"10,000 - 12,000",10000,12000,other,1860,20346 +wales,"12,001 - 13,999",12001,13999,all,3450,44714 +wales,"12,001 - 13,999",12001,13999,retail,1000,12918 +wales,"12,001 - 13,999",12001,13999,offices,460,5902 +wales,"12,001 - 13,999",12001,13999,industry,940,12231 +wales,"12,001 - 13,999",12001,13999,other,1060,13663 +wales,"14,000 - 15,000",14000,15000,all,2180,31556 +wales,"14,000 - 15,000",14000,15000,retail,560,8155 +wales,"14,000 - 15,000",14000,15000,offices,290,4225 +wales,"14,000 - 15,000",14000,15000,industry,530,7679 +wales,"14,000 - 15,000",14000,15000,other,800,11498 +wales,"15,001 - 19,999",15001,19999,all,5500,95206 +wales,"15,001 - 19,999",15001,19999,retail,1360,23538 +wales,"15,001 - 19,999",15001,19999,offices,740,12878 +wales,"15,001 - 19,999",15001,19999,industry,1620,28066 +wales,"15,001 - 19,999",15001,19999,other,1770,30724 +wales,"20,000 - 24,999",20000,24999,all,3700,82361 +wales,"20,000 - 24,999",20000,24999,retail,840,18650 +wales,"20,000 - 24,999",20000,24999,offices,520,11458 +wales,"20,000 - 24,999",20000,24999,industry,1160,25847 +wales,"20,000 - 24,999",20000,24999,other,1190,26406 +wales,"25,000 - 49,999",25000,49999,all,7790,269584 +wales,"25,000 - 49,999",25000,49999,retail,1620,55980 +wales,"25,000 - 49,999",25000,49999,offices,1000,34060 +wales,"25,000 - 49,999",25000,49999,industry,2460,85421 +wales,"25,000 - 49,999",25000,49999,other,2700,94123 +wales,"50,000 - 50,999",50000,50999,all,170,8541 +wales,"50,000 - 50,999",50000,50999,retail,40,1809 +wales,"50,000 - 50,999",50000,50999,offices,20,953 +wales,"50,000 - 50,999",50000,50999,industry,50,2262 +wales,"50,000 - 50,999",50000,50999,other,70,3517 +wales,"51,000 - 99,999",51000,99999,all,3940,275863 +wales,"51,000 - 99,999",51000,99999,retail,730,50291 +wales,"51,000 - 99,999",51000,99999,offices,470,32098 +wales,"51,000 - 99,999",51000,99999,industry,1130,78675 +wales,"51,000 - 99,999",51000,99999,other,1620,114799 +wales,"100,000 - 249,999",100000,249999,all,2470,375453 +wales,"100,000 - 249,999",100000,249999,retail,560,88663 +wales,"100,000 - 249,999",100000,249999,offices,240,35732 +wales,"100,000 - 249,999",100000,249999,industry,670,101651 +wales,"100,000 - 249,999",100000,249999,other,1000,149407 +wales,"250,000 - 499,999",250000,499999,all,780,260796 +wales,"250,000 - 499,999",250000,499999,retail,240,79158 +wales,"250,000 - 499,999",250000,499999,offices,70,24155 +wales,"250,000 - 499,999",250000,499999,industry,200,66130 +wales,"250,000 - 499,999",250000,499999,other,270,91354 +wales,"500,000 - 999,999",500000,999999,all,250,174575 +wales,"500,000 - 999,999",500000,999999,retail,80,62775 +wales,"500,000 - 999,999",500000,999999,offices,20,15375 +wales,"500,000 - 999,999",500000,999999,industry,60,40875 +wales,"500,000 - 999,999",500000,999999,other,80,55550 +wales,"1,000,000 and over",1000000,,all,180,375069 +wales,"1,000,000 and over",1000000,,retail,60,74820 +wales,"1,000,000 and over",1000000,,offices,10,26350 +wales,"1,000,000 and over",1000000,,industry,40,95070 +wales,"1,000,000 and over",1000000,,other,70,178829 +wales,Total,,,all,124790,2416641 +wales,Total,,,retail,29250,595208 +wales,Total,,,offices,20260,269613 +wales,Total,,,industry,34480,658731 +wales,Total,,,other,40810,893089 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_rateable_value_2024/voa_stock_by_year.csv b/packages/microcosm-build/tests/fixtures/uk/firm_rateable_value_2024/voa_stock_by_year.csv new file mode 100644 index 0000000000..61373ddb0d --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_rateable_value_2024/voa_stock_by_year.csv @@ -0,0 +1,10 @@ +geography,as_at,hereditaments,total_rv_gbp_thousand +england_and_wales,2024-03-31,2132000,70683462 +england_and_wales,2025-03-31,2129730,70943844 +england_and_wales,2026-03-31,2138260,70853994 +england,2024-03-31,2004870,68228319 +england,2025-03-31,2003610,68503619 +england,2026-03-31,2013470,68437352 +wales,2024-03-31,127130,2455143 +wales,2025-03-31,126120,2440225 +wales,2026-03-31,124790,2416641 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_rd_tax_credits_2024_25/hmrc_rd_rd1_claims.csv b/packages/microcosm-build/tests/fixtures/uk/firm_rd_tax_credits_2024_25/hmrc_rd_rd1_claims.csv new file mode 100644 index 0000000000..33a170882c --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_rd_tax_credits_2024_25/hmrc_rd_rd1_claims.csv @@ -0,0 +1,10 @@ +financial_year,status,sme_deductions,sme_payable_credits,sme_combination,sme_intensive_eris,sme_total,rdec_large,rdec_sme,merged_rdec_large,merged_rdec_sme,rdec_merged_total,total_claims,total_returns,total_companies +2016-17,Unchanged,"26,225","8,020","11,195",,"45,440","3,935","3,640",,,"7,575","53,015","52,785","51,100" +2017-18,Unchanged,"29,750","9,460","14,700",,"53,910","4,010","4,370",,,"8,380","62,290","62,135","60,175" +2018-19,Unchanged,"34,235","12,185","19,520",,"65,940","4,035","4,560",,,"8,595","74,535","74,400","72,110" +2019-20,Unchanged,"37,030","13,960","23,200",,"74,190","4,385","5,430",,,"9,815","84,005","83,420","80,845" +2020-21,Unchanged,"38,225","14,700","23,205",,"76,135","4,250","6,795",,,"11,045","87,180","85,490","82,785" +2021-22,Revised,"34,545","14,135","24,435",,"73,115","4,150","7,270",,,"11,420","84,535","81,440","78,870" +2022-23,"Provisional, Revised","23,245","11,365","19,675",,"54,285","3,780","6,860",,,"10,645","64,925","62,010","60,220" +2023-24,"Provisional, Revised","16,790","5,640","11,645","4,030","38,110","3,665","6,840",,,"10,500","48,610","45,990","44,880" +2024-25,"Provisional, Uplifted","11,105","3,500","4,995","4,965","24,570","3,180","5,740",625,"6,215","15,760","40,325","38,420","37,545" diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_rd_tax_credits_2024_25/hmrc_rd_rd4_expenditure.csv b/packages/microcosm-build/tests/fixtures/uk/firm_rd_tax_credits_2024_25/hmrc_rd_rd4_expenditure.csv new file mode 100644 index 0000000000..248361cb44 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_rd_tax_credits_2024_25/hmrc_rd_rd4_expenditure.csv @@ -0,0 +1,10 @@ +financial_year,status,sme_scheme,sme_intensive_eris,rdec_large,rdec_sme,merged_rdec_large,merged_rdec_sme,all_schemes +2016-17,Unchanged,"8,165",,"23,035","2,425",,,"33,650" +2017-18,Unchanged,"10,150",,"23,550","3,050",,,"36,760" +2018-19,Unchanged,"13,020",,"25,455","3,305",,,"41,780" +2019-20,Unchanged,"15,510",,"23,150","4,275",,,"42,940" +2020-21,Unchanged,"15,695",,"21,230","3,830",,,"40,760" +2021-22,Revised,"17,580",,"23,250","4,590",,,"45,420" +2022-23,"Provisional, Revised","16,515",,"24,875","5,600",,,"46,990" +2023-24,"Provisional, Revised","11,855","3,070","26,510","6,380",,,"47,820" +2024-25,"Provisional, Uplifted","8,495","3,515","23,840","6,010","6,405","2,705","50,970" diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_rd_tax_credits_2024_25/hmrc_rd_rd6_sector_2024_25.csv b/packages/microcosm-build/tests/fixtures/uk/firm_rd_tax_credits_2024_25/hmrc_rd_rd6_sector_2024_25.csv new file mode 100644 index 0000000000..4ee46c6266 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_rd_tax_credits_2024_25/hmrc_rd_rd6_sector_2024_25.csv @@ -0,0 +1,21 @@ +sector,sme_scheme_claims,sme_scheme_cost_gbp_m,sme_intensive_eris_claims,sme_intensive_eris_cost_gbp_m,rdec_large_claims,rdec_large_cost_gbp_m,rdec_sme_claims,rdec_sme_cost_gbp_m,merged_rdec_large_claims,merged_rdec_large_cost_gbp_m,merged_rdec_sme_claims,merged_rdec_sme_cost_gbp_m,total_claims,total_cost_gbp_m,total_expenditure_gbp_m +"A. Agriculture, Forestry, Fishing",390,25,35,<10,50,55,85,<10,15,<10,195,15,770,110,700 +B. Mining & Quarrying,70,<10,<10,<10,50,135,35,<10,N/A,N/A,30,<10,190,150,825 +C. Manufacturing,"5,665",340,735,85,"1,100",960,"1,700",195,215,560,"1,670",95,"11,090","2,235","14,195" +"D. Electricity, Gas, Steam and Air Conditioning",45,<10,10,<10,50,15,20,<10,10,<10,40,<10,175,30,195 +"E. Water, Sewerage and Waste",145,<10,20,<10,20,<10,40,<10,15,<10,50,<10,290,30,190 +F. Construction,"1,460",110,60,<10,240,190,125,10,60,50,455,30,"2,405",390,"2,510" +"G. Wholesale & Retail Trade, Repairs",825,40,90,<10,120,135,140,15,25,10,180,<10,"1,375",220,"1,410" +H. Transport & Storage,115,<10,20,<10,50,30,25,<10,20,<10,40,<10,270,50,310 +I. Accommodation & Food,40,<10,<10,<10,15,<10,<10,<10,N/A,N/A,15,<10,75,<10,50 +J. Information & Communication,"5,225",435,"2,180",250,425,480,"1,405",245,90,110,"1,600",110,"10,920","1,630","9,950" +K. Financial & Insurance,305,40,55,10,230,335,80,60,30,35,100,20,805,500,"3,270" +L. Real Estate,20,<10,<10,<10,<10,<10,<10,<10,<10,<10,<10,<10,40,<10,35 +"M. Professional, Scientific & Technical","3,410",290,"1,345",410,450,815,"1,665",280,75,70,"1,250",95,"8,195","1,960","11,665" +N. Admin & Support Services,"1,130",70,195,45,255,265,230,30,35,120,335,20,"2,180",550,"3,475" +"O. Public Admin, Defence & Social Services",15,<10,<10,<10,<10,10,<10,<10,<10,<10,<10,<10,45,15,110 +P. Education,65,<10,20,<10,<10,<10,10,<10,<10,<10,20,<10,125,<10,60 +Q. Health & Social Work,180,10,70,<10,25,<10,60,15,<10,<10,65,<10,405,45,265 +"R. Arts, Entertainment & Recreation",175,15,35,<10,40,105,25,<10,<10,<10,40,<10,320,130,885 +S. Other services activities,290,15,65,<10,40,40,55,15,<10,30,95,<10,550,115,730 +Unknown or other,30,<10,<10,<10,<10,<10,30,<10,<10,<10,20,<10,95,20,135 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_rd_tax_credits_2024_25/provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_rd_tax_credits_2024_25/provenance.json new file mode 100644 index 0000000000..9815cac8e7 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_rd_tax_credits_2024_25/provenance.json @@ -0,0 +1,46 @@ +{ + "kind": "uk_firm_rd_tax_credit_fixture", + "schema_version": 1, + "period": "Financial year 2024-25 (accounting periods; provisional, uplifted by HMRC for claims not yet received)", + "accessed": "2026-11-23", + "method": "Cells were read from the downloaded workbook on the access date by tools/extract_uk_firm_rd_tax_credits_tables.py and written as published text: thousands separators, HMRC's suppression marker (a '<' followed by the rounding floor), 'N/A' and blank cells are kept. None was filled from memory.", + "source": { + "publisher": "HM Revenue and Customs", + "dataset_title": "Corporate tax: Research and Development Tax Credits", + "landing_page": "https://www.gov.uk/government/statistics/corporate-tax-research-and-development-tax-credit", + "url": "https://assets.publishing.service.gov.uk/media/6ab52b118cb3c0580e501188/rd_tax_credits_main_tables_2026.ods", + "edition": "Research and Development Tax Credits Statistics: September 2026 (published 29 September 2026); Main tables 2026; claims in Company Tax returns received on or before 31 May 2026", + "file": "rd_tax_credits_main_tables_2026.ods", + "size_bytes": 24793, + "sha256": "efc2238695c40dc4273acc8846f9057bbe582ff04c951c75085c32632c004324", + "sheets": { + "hmrc_rd_rd1_claims.csv": "RD1", + "hmrc_rd_rd4_expenditure.csv": "RD4", + "hmrc_rd_rd6_sector_2024_25.csv": "RD6_2425" + }, + "rounding": "All figures independently rounded to the nearest 5 or \u00a35 million; components may not sum to totals (Cover sheet).", + "licence": "Open Government Licence v3.0" + }, + "edition_note": "The September 2026 edition is the latest on the access date and replaces the September 2025 edition (2023-24 claims). Its 2024-25 year is the first with the merged RDEC scheme (accounting periods beginning on or after 1 April 2024): HMRC notes SME-level figures for 2024-25 are not comparable with earlier years.", + "coverage": "RD6 sector is the primary SIC 2007 code of the registered company, which may not be the sector of the R&D. RD6 gives the number and cost of claims by scheme but qualifying expenditure only in total per sector; RD4 gives expenditure by scheme only nationally. RD1 counts claims (40,325 in 2024-25) and companies (37,545) separately.", + "extraction_date": "2026-11-23", + "tool": "tools/extract_uk_firm_rd_tax_credits_tables.py", + "command": "uv run --no-sync python tools/extract_uk_firm_rd_tax_credits_tables.py --ods /rd_tax_credits_main_tables_2026.ods", + "files": { + "hmrc_rd_rd1_claims.csv": { + "sha256": "dbb6df5aaaf4618b2a759254e166fbfaaef79ba6a194b03593edb8968caa935b", + "bytes": 1251, + "rows": 9 + }, + "hmrc_rd_rd4_expenditure.csv": { + "sha256": "68b391ae0098e5e142e2dd830d069c1207ab04066d7b32c5c42a00b27a2546fc", + "bytes": 686, + "rows": 9 + }, + "hmrc_rd_rd6_sector_2024_25.csv": { + "sha256": "9329ac1a500713e7e991bf56000da2c10c9fa86b734ab29a5f527296e54e0305", + "bytes": 2123, + "rows": 20 + } + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_supply_use_2024/firm_supply_use_2024.provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_supply_use_2024/firm_supply_use_2024.provenance.json new file mode 100644 index 0000000000..38a8f388bd --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_supply_use_2024/firm_supply_use_2024.provenance.json @@ -0,0 +1,93 @@ +{ + "kind": "uk_firm_supply_use_fixture", + "schema_version": 1, + "period": "calendar year 2024", + "accessed": "2026-11-22", + "method": "Figures were read from the downloaded workbook on the access date by tools/extract_uk_firm_supply_use_tables.py; none was filled from memory. Values are pounds million at current prices as published. Demand is at purchasers' prices (the 'Combined Use' matrix, domestic output and imports together); domestic output is at basic prices. The product -> SIC division rows are parsed from the CPA product codes and checked against the Industry and product map sheet; a product spanning several divisions is repeated once per division with the whole product.", + "identities_checked": [ + "domestic output + imports + distributors' margins + taxes less subsidies = total supply (each product)", + "intermediate consumption + total final demand = total demand = total supply (each product)", + "final demand components sum to total final demand (each product)", + "Table 3 COICOP columns sum to Total (domestic concept); domestic + non-resident expenditure in the UK + resident expenditure abroad = Total HHFCE (national concept) = Table 2 households (each product)", + "distributors' margins sum to zero over products", + "products per SIC division = distinct A103 codes per division in the Industry and product map" + ], + "notes": [ + "Table 2's households column is the national concept (includes UK residents' spending abroad, excludes non-residents' spending in the UK, which sits in exports); Table 3's COICOP columns are the domestic concept.", + "Table 3 publishes COICOP classes for divisions 01-09 and only division totals for 10, 11 and 12 (no 12.6.1 FISIM class).", + "Distributors' trading margins are negative only on the trade products CPA_G45, CPA_G46 and CPA_G47 and are spread over the goods products (and publishing products J58, J59 & J60) as positive margins; one combined column, not split by wholesale, retail and motor trade.", + "Table 3 footnote: COICOP data here may differ from Consumer Trends because of the CPA to COICOP correlator; at the total level they are consistent.", + "Table 3 has 102 product rows: it prints CPA_C27 and CPA_C28 as one row, CPA_C27 & C28, written under that code.", + "Zero cells of Table 3 are not written to sut_hhfce_product_coicop.csv." + ], + "source": { + "publisher": "Office for National Statistics", + "dataset_title": "Input-output supply and use tables", + "landing_page": "https://www.ons.gov.uk/economy/nationalaccounts/supplyandusetables/datasets/inputoutputsupplyandusetables", + "url": "https://www.ons.gov.uk/file?uri=/economy/nationalaccounts/supplyandusetables/datasets/inputoutputsupplyandusetables/current/supublicationtablesbb26.xlsx", + "edition": "Supply and Use Tables, 1997 - 2024 (consistent with UK National Accounts 2026 Blue Book), released October 2026", + "file": "sut_bb26.xlsx", + "size_bytes": 3160155, + "sha256": "716c9e023e95cad60d3ca6affb058540887f436ad21a2f3c0f8f01eec0bbeaa8", + "sheets": [ + "Table 1 - Supply 2024", + "Table 2 - Int Con 2024", + "Table 2 - Final Demand 2024", + "Table 3 - HHFCE 2024", + "Industry and product map" + ], + "units": "pounds million, current prices", + "licence": "Open Government Licence v3.0" + }, + "extraction_date": "2026-11-22", + "tool": "tools/extract_uk_firm_supply_use_tables.py", + "command": "uv run --no-sync python tools/extract_uk_firm_supply_use_tables.py --xlsx /supublicationtablesbb26.xlsx", + "files": { + "sut_product_uses.csv": { + "sha256": "40b4a8b6ac88ffe6cc03528bb93ea36aec534742a6675f400b2693db828ad83c", + "bytes": 12185, + "rows": 103, + "columns": [ + "product_code", + "product_label", + "intermediate_consumption", + "households", + "npish", + "central_government", + "local_government", + "gfcf", + "valuables", + "changes_in_inventories", + "exports", + "total_demand", + "domestic_output", + "imports", + "distributors_margins", + "taxes_less_subsidies", + "total_supply" + ] + }, + "sut_hhfce_product_coicop.csv": { + "sha256": "48ae45bfeb5ce5bb0ae8cb9491e80d71e8e4598e0337a262627e4a1c16772cd6", + "bytes": 3596, + "rows": 192, + "columns": [ + "product_code", + "coicop", + "value_gbp_million" + ] + }, + "sut_product_sic_division.csv": { + "sha256": "ae8825d74bcc261208c5846089b985b24b537d866bdc6b3a53199718903d1070", + "bytes": 3422, + "rows": 110, + "columns": [ + "product_code", + "sic_division", + "sic_section", + "map_sic_codes", + "map_a103_codes" + ] + } + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_supply_use_2024/sut_hhfce_product_coicop.csv b/packages/microcosm-build/tests/fixtures/uk/firm_supply_use_2024/sut_hhfce_product_coicop.csv new file mode 100644 index 0000000000..e98cf9b7ce --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_supply_use_2024/sut_hhfce_product_coicop.csv @@ -0,0 +1,193 @@ +product_code,coicop,value_gbp_million +CPA_A01,01.1,25419 +CPA_A01,09.2,257 +CPA_A01,09.3,5879 +CPA_A02,04.5,178 +CPA_A02,09.3,35 +CPA_A03,01.1,785 +CPA_B05 & B06,04.5,159 +CPA_B07 & B08,09.3,57 +CPA_C101,01.1,26569 +CPA_C102_3,01.1,17217 +CPA_C102_3,01.2,2335 +CPA_C104,01.1,2508 +CPA_C105,01.1,17232 +CPA_C106,01.1,3811 +CPA_C107,01.1,17938 +CPA_C108,01.1,24248 +CPA_C108,01.2,3501 +CPA_C109,09.3,10525 +CPA_C11.01-6 & C12,02.1,27058 +CPA_C11.01-6 & C12,02.2,17102 +CPA_C1107,01.2,11874 +CPA_C13,03.1,4883 +CPA_C13,05.1,6781 +CPA_C13,05.2,6980 +CPA_C13,05.6,82 +CPA_C13,09.3,1590 +CPA_C14,03.1,58792 +CPA_C15,03.2,12073 +CPA_C15,05.6,83 +CPA_C15,09.3,1742 +CPA_C15,12,1161 +CPA_C16,04.3,197 +CPA_C16,05.1,1431 +CPA_C16,09.3,52 +CPA_C16,09.5,285 +CPA_C16,12,734 +CPA_C17,04.3,143 +CPA_C17,05.6,328 +CPA_C17,09.3,56 +CPA_C17,09.5,589 +CPA_C17,12,5440 +CPA_C18,09.3,966 +CPA_C19,04.5,1390 +CPA_C19,07.2,35291 +CPA_C203,04.3,308 +CPA_C203,07.2,14 +CPA_C204,05.6,6209 +CPA_C204,12,15493 +CPA_C205,07.2,169 +CPA_C205,09.1,689 +CPA_C205,09.3,343 +CPA_C205,09.5,1544 +CPA_C205,12,483 +CPA_C20A,09.3,796 +CPA_C20C,09.3,531 +CPA_C21,02.3,3044 +CPA_C21,06.1,8069 +CPA_C21,09.3,375 +CPA_C22,04.3,562 +CPA_C22,05.4,618 +CPA_C22,05.5,897 +CPA_C22,05.6,1102 +CPA_C22,06.1,401 +CPA_C22,07.2,1288 +CPA_C22,09.3,208 +CPA_C22,09.5,336 +CPA_C235_6,04.3,37 +CPA_C23OTHER,04.3,121 +CPA_C23OTHER,05.4,3960 +CPA_C23OTHER,09.3,356 +CPA_C23OTHER,12,92 +CPA_C244_5,04.3,12 +CPA_C25,04.3,110 +CPA_C25,05.4,2215 +CPA_C25,05.5,3038 +CPA_C25,05.6,328 +CPA_C25,09.3,164 +CPA_C25,09.5,345 +CPA_C25,12,1955 +CPA_C26,06.1,1111 +CPA_C26,08.2,5477 +CPA_C26,09.1,11568 +CPA_C26,12,848 +CPA_C27 & C28,05.1,1880 +CPA_C27 & C28,05.3,14089 +CPA_C27 & C28,05.5,4744 +CPA_C27 & C28,09.1,2031 +CPA_C27 & C28,09.3,3852 +CPA_C27 & C28,12,1730 +CPA_C29,07.1,58213 +CPA_C29,07.2,4720 +CPA_C29,09.2,2432 +CPA_C301,09.2,2588 +CPA_C303,09.2,270 +CPA_C30OTHER,06.1,63 +CPA_C30OTHER,07.1,2295 +CPA_C30OTHER,09.2,519 +CPA_C31,05.1,15942 +CPA_C31,09.3,219 +CPA_C32,03.1,1619 +CPA_C32,05.1,2529 +CPA_C32,05.6,83 +CPA_C32,06.1,2896 +CPA_C32,09.2,712 +CPA_C32,09.3,11881 +CPA_C32,09.5,281 +CPA_C32,12,16718 +CPA_C3315,09.2,268 +CPA_C3316,09.2,164 +CPA_D351,04.5,28129 +CPA_D352_3,04.5,18088 +CPA_E36,04.4,6346 +CPA_E37,04.4,6053 +CPA_E38,04.4,347 +"CPA_F41, F42 & F43",04.3,2441 +CPA_G45,07.2,20875 +CPA_G45,09.2,606 +CPA_H491_2,07.3,10962 +CPA_H493_5,07.3,13635 +CPA_H50,07.3,10129 +CPA_H51,07.3,17736 +CPA_H52,07.2,1934 +CPA_H52,07.3,578 +CPA_H52,09.2,33 +CPA_H53,08.1,1418 +CPA_I55,11,29930 +CPA_I56,11,128233 +CPA_J58,09.3,5416 +CPA_J58,09.4,286 +CPA_J58,09.5,13522 +CPA_J59 & J60,09.1,5513 +CPA_J59 & J60,09.4,19531 +CPA_J61,08.3,24090 +CPA_J62,12,200 +CPA_K64,12,64096 +CPA_K65.1-2 & K65.3,12,35711 +CPA_K66,12,12741 +CPA_L68BXL683,04.1,101809 +CPA_L68BXL683,04.2,7544 +CPA_L68BXL683,07.2,86 +CPA_L68BXL683,11,2824 +CPA_L68A,04.2,284082 +CPA_L683,12,43 +CPA_M691,12,2315 +CPA_M692,12,40 +CPA_M71,07.2,892 +CPA_M71,12,115 +CPA_M73,12,129 +CPA_M74,09.4,1836 +CPA_M75,09.2,606 +CPA_M75,09.3,6844 +CPA_N77,03.1,28 +CPA_N77,05.6,267 +CPA_N77,07.1,3966 +CPA_N77,07.2,11565 +CPA_N77,09.4,535 +CPA_N78,12,49 +CPA_N79,07.3,21256 +CPA_N79,11,7622 +CPA_N80,12,149 +CPA_N81,05.6,567 +CPA_N82,05.6,71 +CPA_N82,12,384 +CPA_O84,04.1,1262 +CPA_O84,07.2,1479 +CPA_O84,12,663 +CPA_P85,07.2,422 +CPA_P85,10,41836 +CPA_P85,12,43 +CPA_Q86,06.2,10470 +CPA_Q86,06.3,5652 +CPA_Q86,12,3122 +CPA_Q87 & Q88,06.3,5107 +CPA_Q87 & Q88,12,19739 +CPA_R90,09.4,8225 +CPA_R91,09.4,1135 +CPA_R92,09.4,12828 +CPA_R93,09.2,337 +CPA_R93,09.4,20393 +CPA_S94,07.2,3768 +CPA_S94,12,4166 +CPA_S95,03.1,28 +CPA_S95,03.2,43 +CPA_S95,05.1,50 +CPA_S95,05.3,353 +CPA_S95,09.1,64 +CPA_S95,12,80 +CPA_S96,03.1,599 +CPA_S96,05.6,268 +CPA_S96,09.2,1346 +CPA_S96,12,27675 +CPA_T97,05.6,3347 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_supply_use_2024/sut_product_sic_division.csv b/packages/microcosm-build/tests/fixtures/uk/firm_supply_use_2024/sut_product_sic_division.csv new file mode 100644 index 0000000000..6190b6337a --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_supply_use_2024/sut_product_sic_division.csv @@ -0,0 +1,111 @@ +product_code,sic_division,sic_section,map_sic_codes,map_a103_codes +CPA_A01,01,A,01,1 +CPA_A02,02,A,02,2 +CPA_A03,03,A,03,3 +CPA_B05 & B06,05,B,05,4 +CPA_B05 & B06,06,B,06,4 +CPA_B07 & B08,07,B,07,5 +CPA_B07 & B08,08,B,08,5 +CPA_B09,09,B,09,6 +CPA_C101,10,C,10.1;10.2-3;10.4;10.5;10.6;10.7;10.8;10.9,7;8;9;10;11;12;13;14 +CPA_C102_3,10,C,10.1;10.2-3;10.4;10.5;10.6;10.7;10.8;10.9,7;8;9;10;11;12;13;14 +CPA_C104,10,C,10.1;10.2-3;10.4;10.5;10.6;10.7;10.8;10.9,7;8;9;10;11;12;13;14 +CPA_C105,10,C,10.1;10.2-3;10.4;10.5;10.6;10.7;10.8;10.9,7;8;9;10;11;12;13;14 +CPA_C106,10,C,10.1;10.2-3;10.4;10.5;10.6;10.7;10.8;10.9,7;8;9;10;11;12;13;14 +CPA_C107,10,C,10.1;10.2-3;10.4;10.5;10.6;10.7;10.8;10.9,7;8;9;10;11;12;13;14 +CPA_C108,10,C,10.1;10.2-3;10.4;10.5;10.6;10.7;10.8;10.9,7;8;9;10;11;12;13;14 +CPA_C109,10,C,10.1;10.2-3;10.4;10.5;10.6;10.7;10.8;10.9,7;8;9;10;11;12;13;14 +CPA_C11.01-6 & C12,11,C,11.01-6;11.07,15;16 +CPA_C1107,11,C,11.01-6;11.07,15;16 +CPA_C11.01-6 & C12,12,C,12,15 +CPA_C13,13,C,13,17 +CPA_C14,14,C,14,18 +CPA_C15,15,C,15,19 +CPA_C16,16,C,16,20 +CPA_C17,17,C,17,21 +CPA_C18,18,C,18,22 +CPA_C19,19,C,19,23 +CPA_C203,20,C,20A;20B;20C;20.3;20.4;20.5,24;25;26;27;28;29 +CPA_C204,20,C,20A;20B;20C;20.3;20.4;20.5,24;25;26;27;28;29 +CPA_C205,20,C,20A;20B;20C;20.3;20.4;20.5,24;25;26;27;28;29 +CPA_C20A,20,C,20A;20B;20C;20.3;20.4;20.5,24;25;26;27;28;29 +CPA_C20B,20,C,20A;20B;20C;20.3;20.4;20.5,24;25;26;27;28;29 +CPA_C20C,20,C,20A;20B;20C;20.3;20.4;20.5,24;25;26;27;28;29 +CPA_C21,21,C,21,30 +CPA_C22,22,C,22,31 +CPA_C235_6,23,C,23OTHER;23.5-6,32;33 +CPA_C23OTHER,23,C,23OTHER;23.5-6,32;33 +CPA_C241_3,24,C,24.1-3;24.4-5,34;35 +CPA_C244_5,24,C,24.1-3;24.4-5,34;35 +CPA_C25,25,C,25OTHER;25.4,36 +CPA_C26,26,C,26,37 +CPA_C27,27,C,27,38 +CPA_C28,28,C,28,39 +CPA_C29,29,C,29,40 +CPA_C301,30,C,30.1;30.3;30OTHER,41;42;43 +CPA_C303,30,C,30.1;30.3;30OTHER,41;42;43 +CPA_C30OTHER,30,C,30.1;30.3;30OTHER,41;42;43 +CPA_C31,31,C,31,44 +CPA_C32,32,C,32,45 +CPA_C3315,33,C,33.15;33.16;33OTHER,46;47;48 +CPA_C3316,33,C,33.15;33.16;33OTHER,46;47;48 +CPA_C33OTHER,33,C,33.15;33.16;33OTHER,46;47;48 +CPA_D351,35,D,35.1;35.2-3,49;50 +CPA_D352_3,35,D,35.1;35.2-3,49;50 +CPA_E36,36,E,36,51 +CPA_E37,37,E,37,52 +CPA_E38,38,E,38,53 +CPA_E39,39,E,39,54 +"CPA_F41, F42 & F43",41,F,41,55 +"CPA_F41, F42 & F43",42,F,42,55 +"CPA_F41, F42 & F43",43,F,43,55 +CPA_G45,45,G,45,56 +CPA_G46,46,G,46,57 +CPA_G47,47,G,47,58 +CPA_H491_2,49,H,49.1-2;49.3-5,59;60 +CPA_H493_5,49,H,49.1-2;49.3-5,59;60 +CPA_H50,50,H,50,61 +CPA_H51,51,H,51,62 +CPA_H52,52,H,52,63 +CPA_H53,53,H,53,64 +CPA_I55,55,I,55,65 +CPA_I56,56,I,56,66 +CPA_J58,58,J,58,67 +CPA_J59 & J60,59,J,59,68 +CPA_J59 & J60,60,J,60,68 +CPA_J61,61,J,61,69 +CPA_J62,62,J,62,70 +CPA_J63,63,J,63,71 +CPA_K64,64,K,64,72 +CPA_K65.1-2 & K65.3,65,K,65.1-2;65.3,73 +CPA_K66,66,K,66,74 +CPA_L68BXL683,68,L,68B excl. 68.3;68A;68.3,75;76;77 +CPA_L68A,68,L,68B excl. 68.3;68A;68.3,75;76;77 +CPA_L683,68,L,68B excl. 68.3;68A;68.3,75;76;77 +CPA_M691,69,M,69.1;69.2,78;79 +CPA_M692,69,M,69.1;69.2,78;79 +CPA_M70,70,M,70,80 +CPA_M71,71,M,71,81 +CPA_M72,72,M,72,82 +CPA_M73,73,M,73,83 +CPA_M74,74,M,74,84 +CPA_M75,75,M,75,85 +CPA_N77,77,N,77,86 +CPA_N78,78,N,78,87 +CPA_N79,79,N,79,88 +CPA_N80,80,N,80,89 +CPA_N81,81,N,81,90 +CPA_N82,82,N,82,91 +CPA_O84,84,O,84,92 +CPA_P85,85,P,85,93 +CPA_Q86,86,Q,86,94 +CPA_Q87 & Q88,87,Q,87,95 +CPA_Q87 & Q88,88,Q,88,95 +CPA_R90,90,R,90,96 +CPA_R91,91,R,91,97 +CPA_R92,92,R,92,98 +CPA_R93,93,R,93,99 +CPA_S94,94,S,94,100 +CPA_S95,95,S,95,101 +CPA_S96,96,S,96,102 +CPA_T97,97,T,97,103 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_supply_use_2024/sut_product_uses.csv b/packages/microcosm-build/tests/fixtures/uk/firm_supply_use_2024/sut_product_uses.csv new file mode 100644 index 0000000000..7294b07741 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_supply_use_2024/sut_product_uses.csv @@ -0,0 +1,104 @@ +product_code,product_label,intermediate_consumption,households,npish,central_government,local_government,gfcf,valuables,changes_in_inventories,exports,total_demand,domestic_output,imports,distributors_margins,taxes_less_subsidies,total_supply +CPA_A01,"Products of agriculture, hunting and related services",30573,31888,0,0,0,1618,0,-331,2711,66459,37476,17530,9660,1793,66459 +CPA_A02,"Products of forestry, logging and related services",1919,213,0,0,0,0,0,1368,40,3540,2539,247,728,26,3540 +CPA_A03,Fish and other fishing products; aquaculture products; support services to fishing,3015,671,0,0,0,0,0,23,1457,5166,2516,917,1731,2,5166 +CPA_B05 & B06,Coal and lignite & Crude Petroleum And Natural Gas,36053,159,0,0,0,0,0,2609,24173,62994,23358,39140,473,23,62994 +CPA_B07 & B08,Metal Ores & Other mining and quarrying products,8489,57,0,0,0,0,0,-3,502,9045,5546,1993,1129,377,9045 +CPA_B09,Mining support services,3740,0,0,0,0,0,0,-10,1694,5424,5043,381,0,0,5424 +CPA_C101,Preserved meat and meat products,19437,27023,0,0,0,0,0,-135,2985,49310,27657,10034,11490,129,49310 +CPA_C102_3,"Processed and preserved fish, crustaceans, molluscs, fruit and vegetables",11000,19595,0,0,0,0,0,12,1622,32229,12987,9248,7618,2376,32229 +CPA_C104,Vegetable and animal oils and fats,3968,2541,0,0,0,0,0,-82,558,6985,1962,3337,1651,35,6985 +CPA_C105,Dairy products,8362,17805,0,0,0,0,0,-266,2401,28302,13871,4952,7378,2101,28302 +CPA_C106,"Grain mill products, starches and starch products",9240,3946,0,0,0,0,0,-114,1153,14225,7993,2464,3738,30,14225 +CPA_C107,Bakery and farinaceous products,6917,18138,0,0,0,0,0,-83,1648,26620,15734,4600,6218,68,26620 +CPA_C108,Other food products,18241,27942,0,0,0,0,0,-150,6050,52083,22378,12817,13391,3497,52083 +CPA_C109,Prepared animal feeds,4212,10581,0,0,0,0,0,-20,1368,16141,9409,1996,3539,1197,16141 +CPA_C11.01-6 & C12,Alcoholic beverages & Tobacco products,17026,49184,0,0,0,0,0,1272,12892,80374,20044,15410,18853,26067,80374 +CPA_C1107,Soft drinks,4641,11938,0,0,0,0,0,-44,1273,17808,8320,2637,5132,1719,17808 +CPA_C13,Textiles,6554,20351,0,0,0,647,0,-313,2951,30190,7642,6348,13781,2419,30190 +CPA_C14,Wearing apparel,3054,58748,0,0,0,0,0,-563,8076,69315,4694,23636,34259,6726,69315 +CPA_C15,Leather and related products,985,14327,0,0,0,0,0,-104,3186,18394,1046,7902,7769,1677,18394 +CPA_C16,"Wood and of products of wood and cork, except furniture; articles of straw and plaiting materials",16688,2623,0,0,0,0,0,-185,770,19896,11018,5533,2955,390,19896 +CPA_C17,Paper and paper products,24536,6580,0,0,0,0,0,193,2522,33831,14778,8211,9438,1404,33831 +CPA_C18,Printing and recording services,8680,966,0,0,0,0,0,-125,14,9535,8744,14,0,777,9535 +CPA_C19,Coke and refined petroleum products,45446,37920,0,0,0,0,0,674,12820,96860,32495,28699,5973,29693,96860 +CPA_C203,"Paints, varnishes and similar coatings, printing ink and mastics",5877,375,0,0,0,0,0,-28,1720,7944,3820,1319,2708,97,7944 +CPA_C204,"Soap and detergents, cleaning and polishing preparations, perfumes and toilet preparations",3563,21370,0,0,0,0,0,-249,5645,30329,9265,7963,10451,2650,30329 +CPA_C205,Other chemical products,11386,3513,0,0,0,0,0,-106,6931,21724,8785,8583,3660,696,21724 +CPA_C20A,"Industrial gases, inorganics and fertilisers (all inorganic chemicals) - 20.11/13/15",5383,796,0,0,0,0,0,49,4607,10835,4272,3999,2380,184,10835 +CPA_C20B,Petrochemicals - 20.14/16/17/60,17147,0,0,0,0,0,0,12,11733,28892,11382,14008,3313,189,28892 +CPA_C20C,"Dyestuffs, agro-chemicals - 20.12/20",3543,531,0,0,0,0,0,36,1748,5858,2718,1283,1775,82,5858 +CPA_C21,Basic pharmaceutical products and pharmaceutical preparations,29325,11433,0,11981,0,0,0,-70,46472,99141,45734,29241,20538,3628,99141 +CPA_C22,Rubber and plastic products,30999,4734,0,0,0,259,0,-83,9384,45293,24795,15601,3701,1196,45293 +CPA_C235_6,"Manufacture of cement, lime, plaster and articles of concrete, cement and plaster",18592,37,0,0,0,0,0,21,367,19017,9677,1370,7859,111,19017 +CPA_C23OTHER,"Glass, refractory, clay, other porcelain and ceramic, stone and abrasive products - 23.1-4/7-9",13888,4632,0,0,0,155,0,-64,2503,21114,7808,5536,7123,647,21114 +CPA_C241_3,Basic iron and steel,21588,0,0,0,0,0,0,203,4793,26584,8627,7361,10323,273,26584 +CPA_C244_5,Other basic metals and casting,12549,12,0,0,0,0,3556,-111,14217,30223,6597,20409,3093,124,30223 +CPA_C25,Fabricated metal products,49875,8148,0,0,0,10183,0,176,9864,78246,44276,16294,15008,2668,78246 +CPA_C26,"Computer, electronic and optical products",64105,19183,0,0,0,19478,222,401,29407,132796,34675,59190,30571,8360,132796 +CPA_C27,Electrical equipment,21822,24533,0,0,0,5574,0,-655,14327,65601,16218,30587,15035,3761,65601 +CPA_C28,Machinery and equipment n.e.c.,41190,3827,0,0,0,28470,0,108,38650,112245,42341,42844,23792,3268,112245 +CPA_C29,"Motor vehicles, trailers and semi-trailers",51826,65014,0,0,0,30928,0,1483,45439,194690,69758,72202,40752,11978,194690 +CPA_C301,Ships and boats,4592,2588,0,0,0,4316,0,61,2711,14268,8204,2844,2376,844,14268 +CPA_C303,Air and spacecraft and related machinery,17552,270,0,0,0,5019,0,791,44054,67686,30767,32393,3085,1441,67686 +CPA_C30OTHER,Other transport equipment - 30.2/4/9,4860,2989,0,0,0,978,0,-164,1321,9984,3551,3237,2682,514,9984 +CPA_C31,Furniture,3232,16206,0,0,0,9136,0,-210,1677,30041,9403,7874,9704,3060,30041 +CPA_C32,Other manufactured goods,13542,36234,0,0,0,140,866,650,11738,63170,15261,20345,22654,4910,63170 +CPA_C3315,Repair and maintenance of ships and boats,806,268,0,0,0,0,0,0,198,1272,1064,176,0,32,1272 +CPA_C3316,Repair and maintenance of aircraft and spacecraft,4088,164,0,0,0,0,0,0,1670,5922,3934,1970,0,18,5922 +CPA_C33OTHER,Rest of repair; Installation - 33.11-14/17/19/20,27999,0,0,0,0,0,0,0,928,28927,28038,569,0,320,28927 +CPA_D351,"Electricity, transmission and distribution",110337,27550,0,0,0,0,0,-41,1190,139036,130889,3204,0,4943,139036 +CPA_D352_3,Gas; distribution of gaseous fuels through mains; steam and air conditioning supply,55304,17753,0,0,0,0,0,-31,337,73363,71840,22,0,1501,73363 +CPA_E36,Natural water; water treatment and supply services,7116,6223,0,0,0,0,0,19,122,13480,13473,7,0,0,13480 +CPA_E37,Sewerage services; sewage sludge,6048,6049,0,0,0,0,0,-15,0,12082,11491,0,0,591,12082 +CPA_E38,"Waste collection, treatment and disposal services; materials recovery services",19454,249,0,0,8873,0,0,227,7548,36351,30434,4040,0,1877,36351 +CPA_E39,Remediation services and other waste management services,1677,0,0,0,0,0,0,0,0,1677,1513,0,0,164,1677 +"CPA_F41, F42 & F43",Construction,183337,2458,0,0,0,249592,0,1625,3461,440473,398747,3691,0,38035,440473 +CPA_G45,Wholesale and retail trade and repair services of motor vehicles and motorcycles,11673,21469,0,0,0,0,0,0,318,33460,69412,318,-38934,2664,33460 +CPA_G46,"Wholesale trade services, except of motor vehicles and motorcycles",0,0,0,0,0,0,0,0,276,276,201919,411,-202054,0,276 +CPA_G47,"Retail trade services, except of motor vehicles and motorcycles",0,0,0,0,0,0,0,0,0,0,182703,0,-182703,0,0 +CPA_H491_2,Rail transport services,4465,11415,0,0,0,0,0,0,1022,16902,17558,1038,0,-1694,16902 +CPA_H493_5,"Land transport services and transport services via pipelines, excluding rail transport",58765,14558,0,0,8,0,0,0,2115,75446,69200,4985,0,1261,75446 +CPA_H50,Water transport services,6370,10334,0,0,0,0,0,0,8049,24753,18074,5613,0,1066,24753 +CPA_H51,Air transport services,19408,19540,0,0,0,0,0,0,13395,52343,31249,18641,0,2453,52343 +CPA_H52,Warehousing and support services for transportation,45537,2556,0,5301,0,0,0,0,7686,61080,58255,2157,0,668,61080 +CPA_H53,Postal and courier services,23894,1445,0,0,0,0,0,0,1946,27285,25403,1084,0,798,27285 +CPA_I55,Accommodation services,12949,32445,0,0,0,0,0,0,14218,59612,38707,17171,0,3734,59612 +CPA_I56,Food and beverage serving services,14568,130557,0,0,0,0,0,0,8151,153276,127221,12131,0,13924,153276 +CPA_J58,Publishing services,8066,18977,0,0,0,15545,0,43,12023,54654,34647,7165,12221,621,54654 +CPA_J59 & J60,"Motion Picture, Video & TV Programme Production, Sound Recording & Music Publishing Activities & Programming And Broadcasting Activities",29095,25755,0,4393,0,9323,0,437,14844,83847,65409,12454,1983,4001,83847 +CPA_J61,Telecommunications services,33127,23882,0,0,0,0,0,0,9042,66051,56295,5605,0,4151,66051 +CPA_J62,"Computer programming, consultancy and related services",98132,217,0,0,0,55361,0,-941,27416,180185,161722,9815,0,8648,180185 +CPA_J63,Information services,35319,0,0,0,0,0,0,0,9253,44572,40803,3241,0,528,44572 +CPA_K64,"Financial services, except insurance and pension funding",76861,63971,0,0,0,0,0,0,64726,205558,185905,19122,0,531,205558 +CPA_K65.1-2 & K65.3,"Insurance, reinsurance and pension funding services, except compulsory social security",33544,35916,0,0,0,0,0,0,23681,93141,76407,7851,0,8883,93141 +CPA_K66,Services auxiliary to financial services and insurance services,63788,12205,0,0,0,0,0,0,39818,115811,102214,8659,0,4938,115811 +CPA_L68BXL683,"Real estate services, excluding on a fee or contract basis and excluding imputed rent",61684,111286,1428,0,0,0,0,0,2923,177321,174504,2086,0,731,177321 +CPA_L68A,Imputed rents of owner-occupied dwellings,0,288906,0,0,0,0,0,0,811,289717,284071,5646,0,0,289717 +CPA_L683,Real estate activities on a fee or contract basis,9633,57,0,0,0,8649,0,0,617,18956,17909,74,0,973,18956 +CPA_M691,Legal services,37628,2283,265,0,0,5189,0,-354,10004,55015,50191,2331,0,2493,55015 +CPA_M692,"Accounting, bookkeeping and auditing services; tax consulting services",39397,27,0,0,0,0,0,0,4616,44040,40525,2528,0,987,44040 +CPA_M70,Services of head offices; management consulting services,79016,0,0,0,0,654,0,0,50644,130314,106017,21798,0,2499,130314 +CPA_M71,Architectural and engineering services; technical testing and analysis services,45076,1036,0,0,0,9615,0,-625,16075,71177,63444,5633,0,2100,71177 +CPA_M72,Scientific research and development services,8667,0,1532,0,0,70723,0,0,16017,96939,84862,12440,0,-363,96939 +CPA_M73,Advertising and market research services,42877,129,0,0,0,0,0,0,11338,54344,42399,10933,0,1012,54344 +CPA_M74,"Other professional, scientific and technical services",25602,1828,0,0,0,0,0,0,6574,34004,31804,1312,0,888,34004 +CPA_M75,Veterinary services,496,7450,1937,0,0,0,0,0,19,9902,9061,20,0,821,9902 +CPA_N77,Rental and leasing services,52338,15829,0,0,0,0,0,0,11469,79636,66375,10763,0,2498,79636 +CPA_N78,Employment services,59807,51,0,0,0,0,0,0,5133,64991,59794,3422,0,1775,64991 +CPA_N79,"Travel agency, tour operator and other reservation services and related services",9649,28888,0,0,0,0,0,0,266,38803,33314,292,0,5197,38803 +CPA_N80,Security and investigation services,8773,149,0,0,0,0,0,0,462,9384,8883,10,0,491,9384 +CPA_N81,Services to buildings and landscape,32401,567,986,0,0,0,0,0,385,34339,33402,21,0,916,34339 +CPA_N82,"Office administrative, office support and other business support services",43296,459,0,0,0,0,0,0,42162,85917,42579,41775,0,1563,85917 +CPA_O84,Public administration and defence services; compulsory social security services,22040,3404,0,150405,50540,895,0,0,1760,229044,228923,121,0,0,229044 +CPA_P85,Education services,31786,28943,28029,36492,52233,0,0,0,18022,195505,192520,1130,0,1855,195505 +CPA_Q86,Human health services,4660,21372,2940,217447,4618,0,0,0,412,251449,247945,2547,0,957,251449 +CPA_Q87 & Q88,Residential Care & Social Work Activities,17644,24823,11010,599,54986,0,0,0,109,109171,105818,51,0,3302,109171 +CPA_R90,"Creative, arts and entertainment services",7427,9656,3550,0,290,416,515,0,3211,25065,19869,3453,0,1743,25065 +CPA_R91,"Libraries, archives, museums and other cultural services",1138,2249,102,0,1967,0,1875,0,1525,8856,6211,2322,0,323,8856 +CPA_R92,Gambling and betting services,1741,20335,0,0,0,0,0,0,359,22435,11088,6768,0,4579,22435 +CPA_R93,Sports services and amusement and recreation services,8061,21673,783,0,3316,0,0,0,634,34467,30628,1161,0,2678,34467 +CPA_S94,Services furnished by membership organisations,3794,7934,4991,0,0,0,0,0,254,16973,16354,72,0,547,16973 +CPA_S95,Repair services of computers and personal and household goods,2947,679,0,0,0,0,0,0,580,4206,3114,726,0,366,4206 +CPA_S96,Other personal services,3486,29958,0,0,0,0,0,0,323,33767,29908,282,0,3577,33767 +CPA_T97,Services of households as employers of domestic personnel,0,3382,0,0,0,0,0,0,42,3424,3360,64,0,0,3424 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/firm_vat_composition_2024/abs_section_turnover.csv b/packages/microcosm-build/tests/fixtures/uk/firm_vat_composition_2024/abs_section_turnover.csv new file mode 100644 index 0000000000..8d94dfd6bb --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_vat_composition_2024/abs_section_turnover.csv @@ -0,0 +1,25 @@ +sic_section,year,turnover_gbp_million,agva_gbp_million,purchases_gbp_million +A-S (part),2024,5088995,1725172,3346733 +A (part),2024,8115,3738,4565 +B-E,2024,959031,294996,654573 +B,2024,36316,18985,17014 +C,2024,685359,206063,467832 +D,2024,182982,43362,139622 +E,2024,54374,26585,30106 +F,2024,368311,149885,223478 +G-S (part),2024,3753538,1276552,2464117 +G,2024,1793666,254925,1510476 +H-S (part),2024,1959872,1021627,953640 +H,2024,256992,117908,143165 +I,2024,135863,68952,66783 +J,2024,398683,184828,221442 +L,2024,92072,58037,34699 +M,2024,452713,263713,193767 +N,2024,325992,169517,157391 +P (part),2024,66683,40680,26456 +Q (part),2024,90075,58984,31036 +R,2024,97353,36886,57461 +S,2024,43446,22122,21440 +45,2024,261300,38077,224104 +46,2024,1018705,110196,880158 +47,2024,513660,106653,406214 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_vat_composition_2024/hmrc_vat_relief_costs.csv b/packages/microcosm-build/tests/fixtures/uk/firm_vat_composition_2024/hmrc_vat_relief_costs.csv new file mode 100644 index 0000000000..310d8a3153 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_vat_composition_2024/hmrc_vat_relief_costs.csv @@ -0,0 +1,9 @@ +code,name,first_forecast_year,cost_2024_25_gbp_million +VAT - NS1,Zero rate for printed matter and e-publications,2025 to 2026,1700 +VAT - NS2,The VAT Zero rate for children's clothing and protective footwear and helmets,2025 to 2026,2200 +VAT - NS3,Construction and sale of new dwellings (includes refunds to DIY builders),2023 to 2024,14400 +VAT - NS4,Domestic fuel and power,2025 to 2026,6800 +VAT - NS5,Domestic passenger transport,2025 to 2026,5600 +VAT - NS6,Drugs and supplies on prescription,2023 to 2024,3800 +VAT - NS7,Food,2025 to 2026,26300 +VAT - NS16,Water and sewerage services,2024 to 2025,2900 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_vat_composition_2024/provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_vat_composition_2024/provenance.json new file mode 100644 index 0000000000..c056ce2ae3 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_vat_composition_2024/provenance.json @@ -0,0 +1,106 @@ +{ + "kind": "uk_firm_vat_composition_fixture", + "schema_version": 1, + "describes": "tax year 2024-25 VAT treatment applied to calendar-year 2024 Supply and Use Tables", + "accessed": "2026-11-26", + "status": "assumed", + "method": "vat_product_treatment.csv is written by hand from the VAT Act 1994 schedules (provisions as at 1 October 2026, read for their 2024-25 effect): each of the 103 SUT products' sales are split into standard, reduced, zero and exempt shares, by buyer where the law differs (households, other domestic buyers, exports; exports with no row are zero-rated). Rows marked statute have one treatment by law; rows marked assumed carry a share set by judgement and are never tuned to a receipt or relief figure. The four other CSVs are extracted by tools/extract_uk_firm_vat_composition_tables.py from the three files below; none is typed by hand.", + "sources": { + "sut": { + "publisher": "Office for National Statistics", + "dataset_title": "Input-output supply and use tables", + "landing_page": "https://www.ons.gov.uk/economy/nationalaccounts/supplyandusetables/datasets/inputoutputsupplyandusetables", + "url": "https://www.ons.gov.uk/file?uri=/economy/nationalaccounts/supplyandusetables/datasets/inputoutputsupplyandusetables/current/supublicationtablesbb26.xlsx", + "edition": "Supply and Use Tables, 1997 - 2024 (consistent with UK National Accounts 2026 Blue Book), released October 2026", + "file": "supublicationtablesbb26.xlsx", + "size_bytes": 3160155, + "sha256": "716c9e023e95cad60d3ca6affb058540887f436ad21a2f3c0f8f01eec0bbeaa8", + "sheets": [ + "Table 2 - Int Con 2024", + "Table 4 - GFCF 2024" + ], + "note": "The same workbook as firm_supply_use_2024 (same sha256); re-fetched 26 Nov 2026.", + "licence": "Open Government Licence v3.0" + }, + "abs": { + "publisher": "Office for National Statistics", + "dataset_title": "Non-financial business economy, UK: Sections A to S (Annual Business Survey)", + "landing_page": "https://www.ons.gov.uk/businessindustryandtrade/business/businessservices/datasets/uknonfinancialbusinesseconomyannualbusinesssurveysectionsas", + "url": "https://www.ons.gov.uk/file?uri=/businessindustryandtrade/business/businessservices/datasets/uknonfinancialbusinesseconomyannualbusinesssurveysectionsas/current/abssectionsas.xlsx", + "edition": "ABS 2024 results, released 26 May 2026", + "file": "abssectionsas.xlsx", + "size_bytes": 1055873, + "sha256": "9e548c5c410b73e5a7aec1f97db8f92843430cb6ef5457b1459a0e0e9b13e710", + "sheets": [ + "Sections A to S", + "Division 45", + "Division 46", + "Division 47" + ], + "licence": "Open Government Licence v3.0" + }, + "legislation": [ + { + "title": "Value Added Tax Act 1994 (c. 23), Schedule 7A (reduced rate)", + "direct_url": "https://www.legislation.gov.uk/ukpga/1994/23/schedule/7A/data.xml", + "edition": "Latest available revised version (point in time ~2026-10-01 per RestrictStartDate on schedule; dc:modified 2026-10-07)", + "sha256": "9d0c1e13cbf3567f6ea0632a0cdd90b3935d0b83f824633cae41d6d2109bbac7" + }, + { + "title": "Value Added Tax Act 1994 (c. 23), Schedule 8 (zero-rating)", + "direct_url": "https://www.legislation.gov.uk/ukpga/1994/23/schedule/8/data.xml", + "edition": "Latest available revised version (point in time ~2026-10-01 per RestrictStartDate on schedule; dc:modified 2026-10-07)", + "sha256": "cc96189d172d0216029a54ffa628998f1e92587f0ee3c1a7f1bc71b27eec6d27" + }, + { + "title": "Value Added Tax Act 1994 (c. 23), Schedule 9 (exemptions)", + "direct_url": "https://www.legislation.gov.uk/ukpga/1994/23/schedule/9/data.xml", + "edition": "Latest available revised version (point in time ~2026-10-01 per RestrictStartDate on schedule; dc:modified 2026-10-07)", + "sha256": "64bc72f2017ee134c42a8e56739c0aa5b6729ede97fe626e9b58c34764d52788" + }, + { + "title": "Value Added Tax Act 1994 (c. 23), section 30 (zero-rating; s.30(6) exports of goods)", + "direct_url": "https://www.legislation.gov.uk/ukpga/1994/23/section/30/data.xml", + "edition": "Latest available revised version (point in time ~2026-10-01 per RestrictStartDate on schedule; dc:modified 2026-10-07)", + "sha256": "65138eb4b5d766f59924776c7ed87207cfa64f55f70aeef57f1251a6e873f7dd" + } + ], + "hmrc_tax_relief_statistics": { + "title": "Estimated cost of tax reliefs (January 2026) - Tax relief statistics", + "direct_url": "https://assets.publishing.service.gov.uk/media/69a0194e3e672177d0bc76e6/tax_relief_statistics_january_2026.ods", + "edition": "January 2026 (released 22 January 2026; supersedes Dec 2024 non-structural edition)", + "sha256": "fa94a61fe6b6a02c19b87a656154f27eaf5f00f35f0cce9339b8101b9ac8ee4a", + "sheet": "Table_2 (Six-year cost estimates, GBP million; columns 2020 to 2021 .. 2025 to 2026; column J = 2024 to 2025)", + "use": "relief cost / rate compared with the modelled base of each zero- or reduced-rated relief; reported, never a target", + "file": "tax_relief_statistics_january_2026.ods", + "size_bytes": 108228 + } + }, + "files": { + "vat_product_treatment.csv": { + "sha256": "8851ac7bc00404b90bab5ae3e7558f3139a663397f4a09a2cb3f0552c3315bf2", + "bytes": 10497, + "rows": 120 + }, + "sut_intermediate_consumption.csv": { + "sha256": "2fc3bb4ee0fbc3a2b8c5200ddbb6cf18258250fc465190cb7e5419c06e75520f", + "bytes": 113784, + "rows": 5193 + }, + "sut_dwellings_gfcf.csv": { + "sha256": "69f916b05cd5f2cada6a611a95db08bbf166862e649c2fab87b0e208cd9dbb15", + "bytes": 98, + "rows": 1 + }, + "abs_section_turnover.csv": { + "sha256": "ee9c712681512e65821c44c387c0eb6a6ed70db66ad24f394c62b33295f8faaa", + "bytes": 782, + "rows": 24 + }, + "hmrc_vat_relief_costs.csv": { + "sha256": "c21c02f7db6906b44470d539142bacabc63516f0e3b9ec1e59b910fbcf7a5d0b", + "bytes": 603, + "rows": 8 + } + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_vat_composition_2024/sut_dwellings_gfcf.csv b/packages/microcosm-build/tests/fixtures/uk/firm_vat_composition_2024/sut_dwellings_gfcf.csv new file mode 100644 index 0000000000..ecb0e6f786 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_vat_composition_2024/sut_dwellings_gfcf.csv @@ -0,0 +1,2 @@ +product_code,dwellings_gfcf_gbp_million,total_gfcf_gbp_million +"CPA_F41, F42 & F43",107010,249592 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_vat_composition_2024/sut_intermediate_consumption.csv b/packages/microcosm-build/tests/fixtures/uk/firm_vat_composition_2024/sut_intermediate_consumption.csv new file mode 100644 index 0000000000..e2722d67a3 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_vat_composition_2024/sut_intermediate_consumption.csv @@ -0,0 +1,5194 @@ +product_code,industry_product_code,value_gbp_million +CPA_A01,CPA_A01,10841 +CPA_A01,CPA_A02,51 +CPA_A01,CPA_A03,22 +CPA_A01,CPA_B07 & B08,8 +CPA_A01,CPA_C101,7346 +CPA_A01,CPA_C102_3,856 +CPA_A01,CPA_C104,10 +CPA_A01,CPA_C105,5390 +CPA_A01,CPA_C106,1502 +CPA_A01,CPA_C107,5 +CPA_A01,CPA_C108,534 +CPA_A01,CPA_C109,1333 +CPA_A01,CPA_C11.01-6 & C12,1686 +CPA_A01,CPA_C13,45 +CPA_A01,CPA_C14,1 +CPA_A01,CPA_C15,6 +CPA_A01,CPA_C17,24 +CPA_A01,CPA_C20A,2 +CPA_A01,CPA_C20B,39 +CPA_A01,CPA_C21,216 +CPA_A01,CPA_C22,3 +CPA_A01,CPA_C303,3 +CPA_A01,CPA_C31,6 +CPA_A01,CPA_D351,52 +CPA_A01,CPA_D352_3,18 +CPA_A01,CPA_E38,7 +CPA_A01,CPA_G46,249 +CPA_A01,CPA_I55,26 +CPA_A01,CPA_I56,160 +CPA_A01,CPA_K65.1-2 & K65.3,1 +CPA_A01,CPA_K66,3 +CPA_A01,CPA_L68BXL683,11 +CPA_A01,CPA_M75,2 +CPA_A01,CPA_Q86,36 +CPA_A01,CPA_Q87 & Q88,62 +CPA_A01,CPA_R92,16 +CPA_A01,CPA_S95,1 +CPA_A02,CPA_A01,106 +CPA_A02,CPA_A02,718 +CPA_A02,CPA_C16,666 +CPA_A02,CPA_C17,62 +CPA_A02,CPA_C20C,3 +CPA_A02,CPA_C235_6,3 +CPA_A02,CPA_C241_3,3 +CPA_A02,CPA_C25,3 +CPA_A02,CPA_C28,1 +CPA_A02,CPA_C29,6 +CPA_A02,CPA_C31,21 +CPA_A02,CPA_C32,21 +CPA_A02,CPA_C3316,1 +CPA_A02,CPA_D351,294 +CPA_A02,CPA_L68BXL683,11 +CPA_A03,CPA_A03,648 +CPA_A03,CPA_C102_3,1833 +CPA_A03,CPA_I55,84 +CPA_A03,CPA_I56,439 +CPA_A03,CPA_L68BXL683,11 +CPA_B05 & B06,CPA_B05 & B06,997 +CPA_B05 & B06,CPA_B07 & B08,13 +CPA_B05 & B06,CPA_C101,3 +CPA_B05 & B06,CPA_C107,3 +CPA_B05 & B06,CPA_C108,1 +CPA_B05 & B06,CPA_C11.01-6 & C12,1 +CPA_B05 & B06,CPA_C19,24333 +CPA_B05 & B06,CPA_C20A,6 +CPA_B05 & B06,CPA_C20B,9 +CPA_B05 & B06,CPA_C21,2 +CPA_B05 & B06,CPA_C235_6,45 +CPA_B05 & B06,CPA_C23OTHER,22 +CPA_B05 & B06,CPA_C241_3,150 +CPA_B05 & B06,CPA_C244_5,2 +CPA_B05 & B06,CPA_C25,1 +CPA_B05 & B06,CPA_C33OTHER,2 +CPA_B05 & B06,CPA_D351,4201 +CPA_B05 & B06,CPA_D352_3,6096 +CPA_B05 & B06,CPA_E38,8 +CPA_B05 & B06,"CPA_F41, F42 & F43",3 +CPA_B05 & B06,CPA_G46,10 +CPA_B05 & B06,CPA_H50,20 +CPA_B05 & B06,CPA_H52,17 +CPA_B05 & B06,CPA_K66,4 +CPA_B05 & B06,CPA_L68BXL683,80 +CPA_B05 & B06,CPA_O84,4 +CPA_B05 & B06,CPA_P85,4 +CPA_B05 & B06,CPA_R90,2 +CPA_B05 & B06,CPA_R93,3 +CPA_B05 & B06,CPA_S94,10 +CPA_B05 & B06,CPA_S95,1 +CPA_B07 & B08,CPA_B07 & B08,850 +CPA_B07 & B08,CPA_C203,38 +CPA_B07 & B08,CPA_C205,3 +CPA_B07 & B08,CPA_C20A,39 +CPA_B07 & B08,CPA_C20B,240 +CPA_B07 & B08,CPA_C20C,88 +CPA_B07 & B08,CPA_C235_6,461 +CPA_B07 & B08,CPA_C23OTHER,437 +CPA_B07 & B08,CPA_C241_3,619 +CPA_B07 & B08,CPA_C244_5,318 +CPA_B07 & B08,CPA_C25,324 +CPA_B07 & B08,CPA_C32,136 +CPA_B07 & B08,"CPA_F41, F42 & F43",4095 +CPA_B07 & B08,CPA_H52,9 +CPA_B07 & B08,CPA_K66,1 +CPA_B07 & B08,CPA_L68BXL683,22 +CPA_B07 & B08,CPA_M71,101 +CPA_B07 & B08,CPA_N81,675 +CPA_B07 & B08,CPA_O84,4 +CPA_B07 & B08,CPA_S95,29 +CPA_B09,CPA_B05 & B06,1930 +CPA_B09,CPA_B07 & B08,609 +CPA_B09,CPA_B09,1201 +CPA_C101,CPA_A01,22 +CPA_C101,CPA_A02,2 +CPA_C101,CPA_A03,2 +CPA_C101,CPA_B05 & B06,8 +CPA_C101,CPA_B07 & B08,3 +CPA_C101,CPA_B09,2 +CPA_C101,CPA_C101,6816 +CPA_C101,CPA_C102_3,6 +CPA_C101,CPA_C104,3 +CPA_C101,CPA_C105,10 +CPA_C101,CPA_C106,43 +CPA_C101,CPA_C107,232 +CPA_C101,CPA_C108,1315 +CPA_C101,CPA_C109,229 +CPA_C101,CPA_C11.01-6 & C12,81 +CPA_C101,CPA_C1107,1 +CPA_C101,CPA_C13,4 +CPA_C101,CPA_C14,1 +CPA_C101,CPA_C15,2 +CPA_C101,CPA_C16,6 +CPA_C101,CPA_C17,6 +CPA_C101,CPA_C18,2 +CPA_C101,CPA_C19,10 +CPA_C101,CPA_C203,2 +CPA_C101,CPA_C204,1 +CPA_C101,CPA_C205,1 +CPA_C101,CPA_C20B,8 +CPA_C101,CPA_C21,33 +CPA_C101,CPA_C22,13 +CPA_C101,CPA_C235_6,4 +CPA_C101,CPA_C23OTHER,2 +CPA_C101,CPA_C241_3,1 +CPA_C101,CPA_C244_5,3 +CPA_C101,CPA_C25,5 +CPA_C101,CPA_C26,98 +CPA_C101,CPA_C27,72 +CPA_C101,CPA_C28,180 +CPA_C101,CPA_C29,54 +CPA_C101,CPA_C301,3 +CPA_C101,CPA_C303,7 +CPA_C101,CPA_C31,10 +CPA_C101,CPA_C32,3 +CPA_C101,CPA_C3316,2 +CPA_C101,CPA_D351,11 +CPA_C101,CPA_D352_3,3 +CPA_C101,CPA_E36,10 +CPA_C101,CPA_E38,6 +CPA_C101,"CPA_F41, F42 & F43",13 +CPA_C101,CPA_G45,15 +CPA_C101,CPA_G46,1072 +CPA_C101,CPA_G47,99 +CPA_C101,CPA_H491_2,5 +CPA_C101,CPA_I55,991 +CPA_C101,CPA_I56,6294 +CPA_C101,CPA_K64,20 +CPA_C101,CPA_K65.1-2 & K65.3,3 +CPA_C101,CPA_K66,2 +CPA_C101,CPA_L68BXL683,40 +CPA_C101,CPA_M692,2 +CPA_C101,CPA_M74,2 +CPA_C101,CPA_M75,2 +CPA_C101,CPA_N82,11 +CPA_C101,CPA_O84,123 +CPA_C101,CPA_P85,270 +CPA_C101,CPA_Q86,432 +CPA_C101,CPA_Q87 & Q88,645 +CPA_C101,CPA_R92,24 +CPA_C101,CPA_R93,32 +CPA_C101,CPA_S94,2 +CPA_C102_3,CPA_A01,16 +CPA_C102_3,CPA_B05 & B06,5 +CPA_C102_3,CPA_B07 & B08,6 +CPA_C102_3,CPA_B09,4 +CPA_C102_3,CPA_C101,47 +CPA_C102_3,CPA_C102_3,1236 +CPA_C102_3,CPA_C105,62 +CPA_C102_3,CPA_C106,73 +CPA_C102_3,CPA_C107,384 +CPA_C102_3,CPA_C108,1388 +CPA_C102_3,CPA_C109,111 +CPA_C102_3,CPA_C11.01-6 & C12,141 +CPA_C102_3,CPA_C1107,810 +CPA_C102_3,CPA_C13,1 +CPA_C102_3,CPA_C16,4 +CPA_C102_3,CPA_C17,9 +CPA_C102_3,CPA_C18,2 +CPA_C102_3,CPA_C19,6 +CPA_C102_3,CPA_C203,2 +CPA_C102_3,CPA_C204,2 +CPA_C102_3,CPA_C205,1 +CPA_C102_3,CPA_C20A,2 +CPA_C102_3,CPA_C20B,3 +CPA_C102_3,CPA_C21,17 +CPA_C102_3,CPA_C22,9 +CPA_C102_3,CPA_C235_6,3 +CPA_C102_3,CPA_C244_5,1 +CPA_C102_3,CPA_C25,2 +CPA_C102_3,CPA_C26,67 +CPA_C102_3,CPA_C27,49 +CPA_C102_3,CPA_C28,117 +CPA_C102_3,CPA_C29,36 +CPA_C102_3,CPA_C301,1 +CPA_C102_3,CPA_C303,3 +CPA_C102_3,CPA_C31,6 +CPA_C102_3,CPA_C32,3 +CPA_C102_3,CPA_D351,8 +CPA_C102_3,CPA_D352_3,2 +CPA_C102_3,CPA_E36,3 +CPA_C102_3,CPA_E38,6 +CPA_C102_3,"CPA_F41, F42 & F43",15 +CPA_C102_3,CPA_G45,9 +CPA_C102_3,CPA_G47,61 +CPA_C102_3,CPA_H491_2,27 +CPA_C102_3,CPA_H52,8 +CPA_C102_3,CPA_I55,801 +CPA_C102_3,CPA_I56,3749 +CPA_C102_3,CPA_K64,89 +CPA_C102_3,CPA_K65.1-2 & K65.3,9 +CPA_C102_3,CPA_K66,1 +CPA_C102_3,CPA_L68BXL683,39 +CPA_C102_3,CPA_M692,2 +CPA_C102_3,CPA_N80,2 +CPA_C102_3,CPA_N82,509 +CPA_C102_3,CPA_O84,71 +CPA_C102_3,CPA_P85,274 +CPA_C102_3,CPA_Q86,228 +CPA_C102_3,CPA_Q87 & Q88,332 +CPA_C102_3,CPA_R92,20 +CPA_C102_3,CPA_R93,103 +CPA_C102_3,CPA_S94,1 +CPA_C102_3,CPA_S95,2 +CPA_C104,CPA_A01,1 +CPA_C104,CPA_C101,68 +CPA_C104,CPA_C102_3,415 +CPA_C104,CPA_C104,638 +CPA_C104,CPA_C105,115 +CPA_C104,CPA_C106,460 +CPA_C104,CPA_C107,432 +CPA_C104,CPA_C108,271 +CPA_C104,CPA_C109,300 +CPA_C104,CPA_C11.01-6 & C12,5 +CPA_C104,CPA_C19,1 +CPA_C104,CPA_C203,2 +CPA_C104,CPA_C204,34 +CPA_C104,CPA_C20B,1 +CPA_C104,CPA_C21,2 +CPA_C104,CPA_C22,2 +CPA_C104,CPA_C241_3,2 +CPA_C104,CPA_C26,6 +CPA_C104,CPA_C27,3 +CPA_C104,CPA_C28,11 +CPA_C104,CPA_C29,3 +CPA_C104,CPA_D351,1 +CPA_C104,CPA_G47,5 +CPA_C104,CPA_H53,1 +CPA_C104,CPA_I55,78 +CPA_C104,CPA_I56,652 +CPA_C104,CPA_K64,20 +CPA_C104,CPA_L68BXL683,39 +CPA_C104,CPA_N82,225 +CPA_C104,CPA_O84,4 +CPA_C104,CPA_P85,33 +CPA_C104,CPA_Q86,33 +CPA_C104,CPA_Q87 & Q88,76 +CPA_C104,CPA_R92,2 +CPA_C104,CPA_R93,25 +CPA_C104,CPA_S94,2 +CPA_C105,CPA_A01,17 +CPA_C105,CPA_B05 & B06,6 +CPA_C105,CPA_B07 & B08,3 +CPA_C105,CPA_B09,5 +CPA_C105,CPA_C101,42 +CPA_C105,CPA_C102_3,66 +CPA_C105,CPA_C104,44 +CPA_C105,CPA_C105,2316 +CPA_C105,CPA_C106,62 +CPA_C105,CPA_C107,991 +CPA_C105,CPA_C108,762 +CPA_C105,CPA_C109,4 +CPA_C105,CPA_C11.01-6 & C12,52 +CPA_C105,CPA_C1107,1 +CPA_C105,CPA_C13,2 +CPA_C105,CPA_C16,4 +CPA_C105,CPA_C17,6 +CPA_C105,CPA_C18,3 +CPA_C105,CPA_C19,8 +CPA_C105,CPA_C203,1 +CPA_C105,CPA_C204,2 +CPA_C105,CPA_C205,1 +CPA_C105,CPA_C20A,1 +CPA_C105,CPA_C20B,5 +CPA_C105,CPA_C21,22 +CPA_C105,CPA_C22,8 +CPA_C105,CPA_C235_6,4 +CPA_C105,CPA_C244_5,4 +CPA_C105,CPA_C25,3 +CPA_C105,CPA_C26,10 +CPA_C105,CPA_C27,13 +CPA_C105,CPA_C28,19 +CPA_C105,CPA_C29,4 +CPA_C105,CPA_C303,3 +CPA_C105,CPA_C31,4 +CPA_C105,CPA_C32,3 +CPA_C105,CPA_D351,7 +CPA_C105,CPA_D352_3,1 +CPA_C105,CPA_E36,5 +CPA_C105,CPA_E38,7 +CPA_C105,"CPA_F41, F42 & F43",8 +CPA_C105,CPA_G45,21 +CPA_C105,CPA_G47,72 +CPA_C105,CPA_H491_2,2 +CPA_C105,CPA_H52,5 +CPA_C105,CPA_I55,268 +CPA_C105,CPA_I56,2739 +CPA_C105,CPA_K64,48 +CPA_C105,CPA_K65.1-2 & K65.3,4 +CPA_C105,CPA_K66,47 +CPA_C105,CPA_L68BXL683,34 +CPA_C105,CPA_N82,56 +CPA_C105,CPA_O84,5 +CPA_C105,CPA_P85,182 +CPA_C105,CPA_Q86,83 +CPA_C105,CPA_Q87 & Q88,135 +CPA_C105,CPA_R92,28 +CPA_C105,CPA_R93,102 +CPA_C105,CPA_S94,2 +CPA_C106,CPA_A01,3 +CPA_C106,CPA_C101,741 +CPA_C106,CPA_C102_3,297 +CPA_C106,CPA_C105,9 +CPA_C106,CPA_C106,1312 +CPA_C106,CPA_C107,1509 +CPA_C106,CPA_C108,499 +CPA_C106,CPA_C109,1942 +CPA_C106,CPA_C11.01-6 & C12,1439 +CPA_C106,CPA_C17,28 +CPA_C106,CPA_C21,2 +CPA_C106,CPA_G47,50 +CPA_C106,CPA_I55,100 +CPA_C106,CPA_I56,981 +CPA_C106,CPA_K64,1 +CPA_C106,CPA_K66,1 +CPA_C106,CPA_L68BXL683,11 +CPA_C106,CPA_M692,2 +CPA_C106,CPA_O84,4 +CPA_C106,CPA_P85,90 +CPA_C106,CPA_Q86,49 +CPA_C106,CPA_Q87 & Q88,136 +CPA_C106,CPA_R92,2 +CPA_C106,CPA_R93,31 +CPA_C106,CPA_S96,1 +CPA_C107,CPA_A01,23 +CPA_C107,CPA_A02,3 +CPA_C107,CPA_A03,2 +CPA_C107,CPA_B05 & B06,6 +CPA_C107,CPA_B07 & B08,2 +CPA_C107,CPA_B09,6 +CPA_C107,CPA_C101,59 +CPA_C107,CPA_C102_3,4 +CPA_C107,CPA_C104,3 +CPA_C107,CPA_C105,12 +CPA_C107,CPA_C106,9 +CPA_C107,CPA_C107,355 +CPA_C107,CPA_C108,236 +CPA_C107,CPA_C109,6 +CPA_C107,CPA_C11.01-6 & C12,76 +CPA_C107,CPA_C1107,1 +CPA_C107,CPA_C13,4 +CPA_C107,CPA_C14,1 +CPA_C107,CPA_C16,7 +CPA_C107,CPA_C17,8 +CPA_C107,CPA_C18,4 +CPA_C107,CPA_C19,7 +CPA_C107,CPA_C203,1 +CPA_C107,CPA_C204,3 +CPA_C107,CPA_C205,3 +CPA_C107,CPA_C20B,6 +CPA_C107,CPA_C21,28 +CPA_C107,CPA_C22,10 +CPA_C107,CPA_C235_6,5 +CPA_C107,CPA_C241_3,8 +CPA_C107,CPA_C244_5,4 +CPA_C107,CPA_C25,5 +CPA_C107,CPA_C26,80 +CPA_C107,CPA_C27,71 +CPA_C107,CPA_C28,177 +CPA_C107,CPA_C29,46 +CPA_C107,CPA_C301,3 +CPA_C107,CPA_C303,7 +CPA_C107,CPA_C31,9 +CPA_C107,CPA_C32,3 +CPA_C107,CPA_D351,23 +CPA_C107,CPA_D352_3,5 +CPA_C107,CPA_E36,4 +CPA_C107,CPA_E38,9 +CPA_C107,"CPA_F41, F42 & F43",12 +CPA_C107,CPA_G45,11 +CPA_C107,CPA_G47,220 +CPA_C107,CPA_H491_2,5 +CPA_C107,CPA_H493_5,285 +CPA_C107,CPA_H52,400 +CPA_C107,CPA_I55,467 +CPA_C107,CPA_I56,3320 +CPA_C107,CPA_K64,43 +CPA_C107,CPA_K65.1-2 & K65.3,7 +CPA_C107,CPA_K66,19 +CPA_C107,CPA_L68BXL683,45 +CPA_C107,CPA_M692,1 +CPA_C107,CPA_M71,3 +CPA_C107,CPA_N82,80 +CPA_C107,CPA_O84,7 +CPA_C107,CPA_P85,146 +CPA_C107,CPA_Q86,145 +CPA_C107,CPA_Q87 & Q88,230 +CPA_C107,CPA_R92,18 +CPA_C107,CPA_R93,109 +CPA_C108,CPA_A01,10 +CPA_C108,CPA_B05 & B06,3 +CPA_C108,CPA_B07 & B08,6 +CPA_C108,CPA_B09,3 +CPA_C108,CPA_C101,223 +CPA_C108,CPA_C102_3,619 +CPA_C108,CPA_C104,1 +CPA_C108,CPA_C105,296 +CPA_C108,CPA_C106,520 +CPA_C108,CPA_C107,1493 +CPA_C108,CPA_C108,4934 +CPA_C108,CPA_C109,266 +CPA_C108,CPA_C11.01-6 & C12,176 +CPA_C108,CPA_C1107,487 +CPA_C108,CPA_C13,3 +CPA_C108,CPA_C16,4 +CPA_C108,CPA_C17,8 +CPA_C108,CPA_C18,3 +CPA_C108,CPA_C19,3 +CPA_C108,CPA_C205,6 +CPA_C108,CPA_C20B,4 +CPA_C108,CPA_C21,9 +CPA_C108,CPA_C22,6 +CPA_C108,CPA_C235_6,3 +CPA_C108,CPA_C244_5,1 +CPA_C108,CPA_C25,2 +CPA_C108,CPA_C26,35 +CPA_C108,CPA_C27,26 +CPA_C108,CPA_C28,62 +CPA_C108,CPA_C29,19 +CPA_C108,CPA_C303,2 +CPA_C108,CPA_C31,4 +CPA_C108,CPA_C32,1 +CPA_C108,CPA_D351,4 +CPA_C108,CPA_D352_3,2 +CPA_C108,CPA_E36,1 +CPA_C108,CPA_E38,6 +CPA_C108,"CPA_F41, F42 & F43",5 +CPA_C108,CPA_G45,1 +CPA_C108,CPA_G47,145 +CPA_C108,CPA_H491_2,3 +CPA_C108,CPA_H52,9 +CPA_C108,CPA_I55,1195 +CPA_C108,CPA_I56,5220 +CPA_C108,CPA_J59 & J60,8 +CPA_C108,CPA_K64,108 +CPA_C108,CPA_K65.1-2 & K65.3,14 +CPA_C108,CPA_K66,57 +CPA_C108,CPA_L68BXL683,43 +CPA_C108,CPA_M692,1 +CPA_C108,CPA_M71,10 +CPA_C108,CPA_M73,1 +CPA_C108,CPA_M74,1 +CPA_C108,CPA_O84,9 +CPA_C108,CPA_P85,561 +CPA_C108,CPA_Q86,386 +CPA_C108,CPA_Q87 & Q88,882 +CPA_C108,CPA_R90,29 +CPA_C108,CPA_R92,31 +CPA_C108,CPA_R93,254 +CPA_C108,CPA_S94,17 +CPA_C109,CPA_A01,1896 +CPA_C109,CPA_A03,460 +CPA_C109,CPA_C101,1 +CPA_C109,CPA_C109,1703 +CPA_C109,CPA_C21,1 +CPA_C109,CPA_J59 & J60,40 +CPA_C109,CPA_L68BXL683,43 +CPA_C109,CPA_M75,11 +CPA_C109,CPA_R91,4 +CPA_C109,CPA_R92,5 +CPA_C109,CPA_R93,34 +CPA_C109,CPA_S94,12 +CPA_C109,CPA_S96,2 +CPA_C11.01-6 & C12,CPA_C106,7 +CPA_C11.01-6 & C12,CPA_C108,4 +CPA_C11.01-6 & C12,CPA_C11.01-6 & C12,1295 +CPA_C11.01-6 & C12,CPA_C1107,2 +CPA_C11.01-6 & C12,CPA_G47,8 +CPA_C11.01-6 & C12,CPA_H50,11 +CPA_C11.01-6 & C12,CPA_H52,8 +CPA_C11.01-6 & C12,CPA_H53,2 +CPA_C11.01-6 & C12,CPA_I55,2753 +CPA_C11.01-6 & C12,CPA_I56,12166 +CPA_C11.01-6 & C12,CPA_K64,62 +CPA_C11.01-6 & C12,CPA_K65.1-2 & K65.3,3 +CPA_C11.01-6 & C12,CPA_K66,22 +CPA_C11.01-6 & C12,CPA_L68BXL683,41 +CPA_C11.01-6 & C12,CPA_M692,2 +CPA_C11.01-6 & C12,CPA_Q87 & Q88,8 +CPA_C11.01-6 & C12,CPA_R90,15 +CPA_C11.01-6 & C12,CPA_R91,21 +CPA_C11.01-6 & C12,CPA_R92,30 +CPA_C11.01-6 & C12,CPA_R93,287 +CPA_C11.01-6 & C12,CPA_S94,277 +CPA_C11.01-6 & C12,CPA_S96,2 +CPA_C1107,CPA_C11.01-6 & C12,22 +CPA_C1107,CPA_C1107,573 +CPA_C1107,CPA_G47,6 +CPA_C1107,CPA_H50,3 +CPA_C1107,CPA_H52,9 +CPA_C1107,CPA_H53,1 +CPA_C1107,CPA_I55,379 +CPA_C1107,CPA_I56,3014 +CPA_C1107,CPA_J59 & J60,96 +CPA_C1107,CPA_K64,65 +CPA_C1107,CPA_K65.1-2 & K65.3,2 +CPA_C1107,CPA_K66,25 +CPA_C1107,CPA_L68BXL683,38 +CPA_C1107,CPA_M692,1 +CPA_C1107,CPA_O84,9 +CPA_C1107,CPA_P85,108 +CPA_C1107,CPA_Q87 & Q88,105 +CPA_C1107,CPA_R91,27 +CPA_C1107,CPA_R92,8 +CPA_C1107,CPA_R93,102 +CPA_C1107,CPA_S94,46 +CPA_C1107,CPA_S96,2 +CPA_C13,CPA_A03,5 +CPA_C13,CPA_C13,1330 +CPA_C13,CPA_C14,706 +CPA_C13,CPA_C15,25 +CPA_C13,CPA_C17,51 +CPA_C13,CPA_C18,3 +CPA_C13,CPA_C204,1 +CPA_C13,CPA_C20B,1 +CPA_C13,CPA_C22,55 +CPA_C13,CPA_C23OTHER,22 +CPA_C13,CPA_C25,7 +CPA_C13,CPA_C28,1 +CPA_C13,CPA_C29,597 +CPA_C13,CPA_C301,6 +CPA_C13,CPA_C31,363 +CPA_C13,CPA_C32,165 +CPA_C13,CPA_C33OTHER,9 +CPA_C13,"CPA_F41, F42 & F43",1095 +CPA_C13,CPA_G45,4 +CPA_C13,CPA_G46,1152 +CPA_C13,CPA_H52,2 +CPA_C13,CPA_I56,16 +CPA_C13,CPA_K64,43 +CPA_C13,CPA_K65.1-2 & K65.3,5 +CPA_C13,CPA_K66,1 +CPA_C13,CPA_L68BXL683,37 +CPA_C13,CPA_L68A,18 +CPA_C13,CPA_M74,278 +CPA_C13,CPA_O84,46 +CPA_C13,CPA_P85,59 +CPA_C13,CPA_Q86,245 +CPA_C13,CPA_R93,17 +CPA_C13,CPA_S94,1 +CPA_C13,CPA_S95,1 +CPA_C13,CPA_S96,187 +CPA_C14,CPA_C107,1 +CPA_C14,CPA_C108,2 +CPA_C14,CPA_C13,5 +CPA_C14,CPA_C14,189 +CPA_C14,CPA_C30OTHER,3 +CPA_C14,CPA_C32,1 +CPA_C14,CPA_E38,16 +CPA_C14,"CPA_F41, F42 & F43",7 +CPA_C14,CPA_G46,531 +CPA_C14,CPA_G47,697 +CPA_C14,CPA_H51,1 +CPA_C14,CPA_H53,1 +CPA_C14,CPA_I56,23 +CPA_C14,CPA_K64,29 +CPA_C14,CPA_K65.1-2 & K65.3,6 +CPA_C14,CPA_K66,23 +CPA_C14,CPA_L68BXL683,38 +CPA_C14,CPA_L68A,1 +CPA_C14,CPA_O84,598 +CPA_C14,CPA_P85,73 +CPA_C14,CPA_Q86,410 +CPA_C14,CPA_Q87 & Q88,121 +CPA_C14,CPA_R92,4 +CPA_C14,CPA_R93,49 +CPA_C14,CPA_S94,10 +CPA_C14,CPA_S96,215 +CPA_C15,CPA_C14,1 +CPA_C15,CPA_C15,25 +CPA_C15,CPA_C29,100 +CPA_C15,CPA_C303,3 +CPA_C15,CPA_C31,9 +CPA_C15,"CPA_F41, F42 & F43",8 +CPA_C15,CPA_G45,14 +CPA_C15,CPA_G46,268 +CPA_C15,CPA_G47,122 +CPA_C15,CPA_K64,16 +CPA_C15,CPA_K65.1-2 & K65.3,3 +CPA_C15,CPA_K66,21 +CPA_C15,CPA_L68BXL683,43 +CPA_C15,CPA_O84,306 +CPA_C15,CPA_R91,1 +CPA_C15,CPA_R92,1 +CPA_C15,CPA_R93,3 +CPA_C15,CPA_S95,1 +CPA_C15,CPA_S96,40 +CPA_C16,CPA_B05 & B06,20 +CPA_C16,CPA_C101,1 +CPA_C16,CPA_C105,1 +CPA_C16,CPA_C108,1 +CPA_C16,CPA_C13,1 +CPA_C16,CPA_C16,3139 +CPA_C16,CPA_C17,678 +CPA_C16,CPA_C22,1 +CPA_C16,CPA_C235_6,152 +CPA_C16,CPA_C25,316 +CPA_C16,CPA_C27,17 +CPA_C16,CPA_C28,1 +CPA_C16,CPA_C29,233 +CPA_C16,CPA_C301,189 +CPA_C16,CPA_C303,1 +CPA_C16,CPA_C31,1489 +CPA_C16,CPA_C32,282 +CPA_C16,CPA_C3315,21 +CPA_C16,CPA_C3316,1 +CPA_C16,CPA_C33OTHER,51 +CPA_C16,CPA_E38,2 +CPA_C16,"CPA_F41, F42 & F43",8048 +CPA_C16,CPA_G46,404 +CPA_C16,CPA_G47,9 +CPA_C16,CPA_H52,6 +CPA_C16,CPA_K64,8 +CPA_C16,CPA_K65.1-2 & K65.3,8 +CPA_C16,CPA_K66,26 +CPA_C16,CPA_L68BXL683,46 +CPA_C16,CPA_L68A,654 +CPA_C16,CPA_N81,628 +CPA_C16,CPA_O84,17 +CPA_C16,CPA_P85,132 +CPA_C16,CPA_R90,10 +CPA_C16,CPA_S94,5 +CPA_C16,CPA_S95,10 +CPA_C16,CPA_S96,80 +CPA_C17,CPA_A01,129 +CPA_C17,CPA_A02,5 +CPA_C17,CPA_A03,1 +CPA_C17,CPA_B05 & B06,2 +CPA_C17,CPA_B07 & B08,10 +CPA_C17,CPA_B09,2 +CPA_C17,CPA_C101,353 +CPA_C17,CPA_C102_3,140 +CPA_C17,CPA_C104,4 +CPA_C17,CPA_C105,87 +CPA_C17,CPA_C106,224 +CPA_C17,CPA_C107,434 +CPA_C17,CPA_C108,450 +CPA_C17,CPA_C109,100 +CPA_C17,CPA_C11.01-6 & C12,348 +CPA_C17,CPA_C1107,129 +CPA_C17,CPA_C13,24 +CPA_C17,CPA_C14,13 +CPA_C17,CPA_C15,3 +CPA_C17,CPA_C16,50 +CPA_C17,CPA_C17,3180 +CPA_C17,CPA_C18,1870 +CPA_C17,CPA_C19,9 +CPA_C17,CPA_C203,13 +CPA_C17,CPA_C204,310 +CPA_C17,CPA_C205,71 +CPA_C17,CPA_C20A,15 +CPA_C17,CPA_C20B,22 +CPA_C17,CPA_C20C,5 +CPA_C17,CPA_C21,110 +CPA_C17,CPA_C22,237 +CPA_C17,CPA_C235_6,63 +CPA_C17,CPA_C23OTHER,107 +CPA_C17,CPA_C241_3,9 +CPA_C17,CPA_C244_5,3 +CPA_C17,CPA_C25,100 +CPA_C17,CPA_C26,77 +CPA_C17,CPA_C27,65 +CPA_C17,CPA_C28,40 +CPA_C17,CPA_C29,63 +CPA_C17,CPA_C301,9 +CPA_C17,CPA_C303,8 +CPA_C17,CPA_C30OTHER,2 +CPA_C17,CPA_C31,54 +CPA_C17,CPA_C32,174 +CPA_C17,CPA_C3315,3 +CPA_C17,CPA_C3316,6 +CPA_C17,CPA_C33OTHER,60 +CPA_C17,CPA_D351,38 +CPA_C17,CPA_D352_3,5 +CPA_C17,CPA_E36,4 +CPA_C17,CPA_E37,2 +CPA_C17,CPA_E38,90 +CPA_C17,CPA_E39,59 +CPA_C17,"CPA_F41, F42 & F43",262 +CPA_C17,CPA_G45,126 +CPA_C17,CPA_G46,1197 +CPA_C17,CPA_G47,816 +CPA_C17,CPA_H491_2,2 +CPA_C17,CPA_H493_5,216 +CPA_C17,CPA_H50,149 +CPA_C17,CPA_H51,6 +CPA_C17,CPA_H52,579 +CPA_C17,CPA_H53,179 +CPA_C17,CPA_I55,158 +CPA_C17,CPA_I56,504 +CPA_C17,CPA_J58,1910 +CPA_C17,CPA_J59 & J60,133 +CPA_C17,CPA_J61,59 +CPA_C17,CPA_J62,160 +CPA_C17,CPA_J63,149 +CPA_C17,CPA_K64,378 +CPA_C17,CPA_K65.1-2 & K65.3,40 +CPA_C17,CPA_K66,371 +CPA_C17,CPA_L68BXL683,278 +CPA_C17,CPA_L68A,40 +CPA_C17,CPA_L683,53 +CPA_C17,CPA_M691,238 +CPA_C17,CPA_M692,84 +CPA_C17,CPA_M70,534 +CPA_C17,CPA_M71,79 +CPA_C17,CPA_M72,434 +CPA_C17,CPA_M73,377 +CPA_C17,CPA_M74,209 +CPA_C17,CPA_M75,50 +CPA_C17,CPA_N77,122 +CPA_C17,CPA_N78,75 +CPA_C17,CPA_N79,187 +CPA_C17,CPA_N80,23 +CPA_C17,CPA_N81,135 +CPA_C17,CPA_N82,355 +CPA_C17,CPA_O84,1431 +CPA_C17,CPA_P85,885 +CPA_C17,CPA_Q86,1195 +CPA_C17,CPA_Q87 & Q88,262 +CPA_C17,CPA_R90,23 +CPA_C17,CPA_R91,23 +CPA_C17,CPA_R92,57 +CPA_C17,CPA_R93,203 +CPA_C17,CPA_S94,211 +CPA_C17,CPA_S95,10 +CPA_C17,CPA_S96,178 +CPA_C18,CPA_C13,5 +CPA_C18,CPA_C17,4 +CPA_C18,CPA_C18,417 +CPA_C18,CPA_C22,1 +CPA_C18,CPA_C25,2 +CPA_C18,CPA_C28,1 +CPA_C18,CPA_E38,37 +CPA_C18,CPA_G45,52 +CPA_C18,CPA_G46,412 +CPA_C18,CPA_G47,537 +CPA_C18,CPA_H52,15 +CPA_C18,CPA_H53,4 +CPA_C18,CPA_J58,887 +CPA_C18,CPA_J59 & J60,18 +CPA_C18,CPA_J61,12 +CPA_C18,CPA_K64,426 +CPA_C18,CPA_K65.1-2 & K65.3,476 +CPA_C18,CPA_K66,328 +CPA_C18,CPA_L68A,34 +CPA_C18,CPA_M691,72 +CPA_C18,CPA_N79,24 +CPA_C18,CPA_N81,9 +CPA_C18,CPA_O84,1208 +CPA_C18,CPA_P85,1644 +CPA_C18,CPA_Q86,1532 +CPA_C18,CPA_Q87 & Q88,118 +CPA_C18,CPA_R90,20 +CPA_C18,CPA_R91,89 +CPA_C18,CPA_R93,296 +CPA_C19,CPA_A01,1874 +CPA_C19,CPA_A02,49 +CPA_C19,CPA_A03,54 +CPA_C19,CPA_B05 & B06,222 +CPA_C19,CPA_B07 & B08,228 +CPA_C19,CPA_B09,8 +CPA_C19,CPA_C101,94 +CPA_C19,CPA_C102_3,22 +CPA_C19,CPA_C104,5 +CPA_C19,CPA_C105,43 +CPA_C19,CPA_C106,14 +CPA_C19,CPA_C107,52 +CPA_C19,CPA_C108,29 +CPA_C19,CPA_C109,94 +CPA_C19,CPA_C11.01-6 & C12,134 +CPA_C19,CPA_C1107,13 +CPA_C19,CPA_C13,15 +CPA_C19,CPA_C14,12 +CPA_C19,CPA_C16,58 +CPA_C19,CPA_C17,69 +CPA_C19,CPA_C18,14 +CPA_C19,CPA_C19,2087 +CPA_C19,CPA_C203,10 +CPA_C19,CPA_C204,14 +CPA_C19,CPA_C205,4 +CPA_C19,CPA_C20A,13 +CPA_C19,CPA_C20B,90 +CPA_C19,CPA_C20C,1 +CPA_C19,CPA_C21,4 +CPA_C19,CPA_C22,101 +CPA_C19,CPA_C235_6,146 +CPA_C19,CPA_C23OTHER,39 +CPA_C19,CPA_C241_3,161 +CPA_C19,CPA_C244_5,9 +CPA_C19,CPA_C25,83 +CPA_C19,CPA_C26,10 +CPA_C19,CPA_C27,42 +CPA_C19,CPA_C28,62 +CPA_C19,CPA_C29,49 +CPA_C19,CPA_C301,9 +CPA_C19,CPA_C303,7 +CPA_C19,CPA_C30OTHER,3 +CPA_C19,CPA_C31,37 +CPA_C19,CPA_C32,32 +CPA_C19,CPA_C3315,4 +CPA_C19,CPA_C3316,17 +CPA_C19,CPA_C33OTHER,211 +CPA_C19,CPA_D351,203 +CPA_C19,CPA_D352_3,1 +CPA_C19,CPA_E36,48 +CPA_C19,CPA_E37,123 +CPA_C19,CPA_E38,281 +CPA_C19,CPA_E39,29 +CPA_C19,"CPA_F41, F42 & F43",3632 +CPA_C19,CPA_G45,915 +CPA_C19,CPA_G46,4737 +CPA_C19,CPA_G47,1735 +CPA_C19,CPA_H491_2,670 +CPA_C19,CPA_H493_5,5024 +CPA_C19,CPA_H50,1178 +CPA_C19,CPA_H51,6933 +CPA_C19,CPA_H52,1856 +CPA_C19,CPA_H53,750 +CPA_C19,CPA_I55,114 +CPA_C19,CPA_I56,91 +CPA_C19,CPA_J58,7 +CPA_C19,CPA_J59 & J60,57 +CPA_C19,CPA_J61,245 +CPA_C19,CPA_J62,182 +CPA_C19,CPA_J63,7 +CPA_C19,CPA_K64,751 +CPA_C19,CPA_K65.1-2 & K65.3,108 +CPA_C19,CPA_K66,506 +CPA_C19,CPA_L68BXL683,307 +CPA_C19,CPA_L68A,10 +CPA_C19,CPA_L683,60 +CPA_C19,CPA_M691,78 +CPA_C19,CPA_M692,32 +CPA_C19,CPA_M70,196 +CPA_C19,CPA_M71,422 +CPA_C19,CPA_M72,52 +CPA_C19,CPA_M73,16 +CPA_C19,CPA_M74,141 +CPA_C19,CPA_M75,18 +CPA_C19,CPA_N77,386 +CPA_C19,CPA_N78,62 +CPA_C19,CPA_N79,1126 +CPA_C19,CPA_N80,26 +CPA_C19,CPA_N81,447 +CPA_C19,CPA_N82,235 +CPA_C19,CPA_O84,2172 +CPA_C19,CPA_P85,1055 +CPA_C19,CPA_Q86,889 +CPA_C19,CPA_Q87 & Q88,374 +CPA_C19,CPA_R90,78 +CPA_C19,CPA_R91,41 +CPA_C19,CPA_R92,5 +CPA_C19,CPA_R93,187 +CPA_C19,CPA_S94,131 +CPA_C19,CPA_S95,38 +CPA_C19,CPA_S96,331 +CPA_C203,CPA_C16,31 +CPA_C203,CPA_C17,154 +CPA_C203,CPA_C18,208 +CPA_C203,CPA_C203,107 +CPA_C203,CPA_C205,13 +CPA_C203,CPA_C20C,1 +CPA_C203,CPA_C22,103 +CPA_C203,CPA_C235_6,8 +CPA_C203,CPA_C23OTHER,18 +CPA_C203,CPA_C25,332 +CPA_C203,CPA_C26,2 +CPA_C203,CPA_C27,65 +CPA_C203,CPA_C28,115 +CPA_C203,CPA_C29,1419 +CPA_C203,CPA_C301,34 +CPA_C203,CPA_C30OTHER,9 +CPA_C203,CPA_C31,20 +CPA_C203,CPA_C32,5 +CPA_C203,CPA_C3315,29 +CPA_C203,CPA_C3316,1 +CPA_C203,CPA_C33OTHER,62 +CPA_C203,CPA_E38,19 +CPA_C203,"CPA_F41, F42 & F43",2412 +CPA_C203,CPA_G46,30 +CPA_C203,CPA_J58,285 +CPA_C203,CPA_J62,3 +CPA_C203,CPA_K64,7 +CPA_C203,CPA_K65.1-2 & K65.3,3 +CPA_C203,CPA_K66,26 +CPA_C203,CPA_L68BXL683,44 +CPA_C203,CPA_L68A,9 +CPA_C203,CPA_M73,14 +CPA_C203,CPA_O84,140 +CPA_C203,CPA_P85,114 +CPA_C203,CPA_Q87 & Q88,18 +CPA_C203,CPA_R93,16 +CPA_C203,CPA_S95,1 +CPA_C204,CPA_C101,5 +CPA_C204,CPA_C102_3,2 +CPA_C204,CPA_C105,14 +CPA_C204,CPA_C107,3 +CPA_C204,CPA_C108,2 +CPA_C204,CPA_C204,323 +CPA_C204,CPA_C22,2 +CPA_C204,CPA_C27,1 +CPA_C204,CPA_C32,2 +CPA_C204,CPA_E37,1 +CPA_C204,CPA_E38,64 +CPA_C204,CPA_E39,29 +CPA_C204,"CPA_F41, F42 & F43",1 +CPA_C204,CPA_G46,129 +CPA_C204,CPA_G47,409 +CPA_C204,CPA_I56,212 +CPA_C204,CPA_K64,14 +CPA_C204,CPA_K66,32 +CPA_C204,CPA_L68BXL683,42 +CPA_C204,CPA_M73,13 +CPA_C204,CPA_M75,3 +CPA_C204,CPA_N81,540 +CPA_C204,CPA_O84,196 +CPA_C204,CPA_P85,399 +CPA_C204,CPA_Q86,118 +CPA_C204,CPA_Q87 & Q88,382 +CPA_C204,CPA_R90,9 +CPA_C204,CPA_R91,12 +CPA_C204,CPA_R93,34 +CPA_C204,CPA_S94,1 +CPA_C204,CPA_S96,569 +CPA_C205,CPA_A02,1 +CPA_C205,CPA_B05 & B06,2 +CPA_C205,CPA_B07 & B08,77 +CPA_C205,CPA_B09,39 +CPA_C205,CPA_C101,14 +CPA_C205,CPA_C102_3,1 +CPA_C205,CPA_C105,8 +CPA_C205,CPA_C106,3 +CPA_C205,CPA_C108,204 +CPA_C205,CPA_C109,59 +CPA_C205,CPA_C15,36 +CPA_C205,CPA_C16,418 +CPA_C205,CPA_C17,455 +CPA_C205,CPA_C18,357 +CPA_C205,CPA_C19,183 +CPA_C205,CPA_C203,234 +CPA_C205,CPA_C204,745 +CPA_C205,CPA_C205,2190 +CPA_C205,CPA_C20A,3 +CPA_C205,CPA_C20B,347 +CPA_C205,CPA_C21,459 +CPA_C205,CPA_C22,595 +CPA_C205,CPA_C235_6,161 +CPA_C205,CPA_C244_5,2 +CPA_C205,CPA_C25,416 +CPA_C205,CPA_C26,241 +CPA_C205,CPA_C27,3 +CPA_C205,CPA_C28,406 +CPA_C205,CPA_C303,3 +CPA_C205,CPA_C30OTHER,2 +CPA_C205,CPA_C31,19 +CPA_C205,CPA_C32,16 +CPA_C205,CPA_E37,2 +CPA_C205,CPA_E39,2 +CPA_C205,"CPA_F41, F42 & F43",279 +CPA_C205,CPA_G46,135 +CPA_C205,CPA_H52,8 +CPA_C205,CPA_J58,30 +CPA_C205,CPA_J59 & J60,21 +CPA_C205,CPA_K64,4 +CPA_C205,CPA_K65.1-2 & K65.3,2 +CPA_C205,CPA_K66,5 +CPA_C205,CPA_L68BXL683,35 +CPA_C205,CPA_M71,458 +CPA_C205,CPA_M72,297 +CPA_C205,CPA_N81,408 +CPA_C205,CPA_O84,36 +CPA_C205,CPA_P85,15 +CPA_C205,CPA_Q86,1905 +CPA_C205,CPA_Q87 & Q88,11 +CPA_C205,CPA_S94,3 +CPA_C205,CPA_S96,31 +CPA_C20A,CPA_A01,648 +CPA_C20A,CPA_B07 & B08,11 +CPA_C20A,CPA_C101,1 +CPA_C20A,CPA_C102_3,1 +CPA_C20A,CPA_C106,1 +CPA_C20A,CPA_C107,2 +CPA_C20A,CPA_C108,4 +CPA_C20A,CPA_C11.01-6 & C12,28 +CPA_C20A,CPA_C1107,27 +CPA_C20A,CPA_C13,2 +CPA_C20A,CPA_C17,30 +CPA_C20A,CPA_C203,43 +CPA_C20A,CPA_C204,16 +CPA_C20A,CPA_C205,31 +CPA_C20A,CPA_C20A,1384 +CPA_C20A,CPA_C20B,1111 +CPA_C20A,CPA_C20C,113 +CPA_C20A,CPA_C21,55 +CPA_C20A,CPA_C22,68 +CPA_C20A,CPA_C235_6,10 +CPA_C20A,CPA_C23OTHER,151 +CPA_C20A,CPA_C241_3,19 +CPA_C20A,CPA_C244_5,7 +CPA_C20A,CPA_C25,141 +CPA_C20A,CPA_C26,39 +CPA_C20A,CPA_C27,7 +CPA_C20A,CPA_C29,20 +CPA_C20A,CPA_C303,6 +CPA_C20A,CPA_C32,7 +CPA_C20A,CPA_C33OTHER,14 +CPA_C20A,CPA_D351,618 +CPA_C20A,CPA_E36,179 +CPA_C20A,CPA_E38,1 +CPA_C20A,"CPA_F41, F42 & F43",2 +CPA_C20A,CPA_K64,9 +CPA_C20A,CPA_K65.1-2 & K65.3,3 +CPA_C20A,CPA_L68BXL683,50 +CPA_C20A,CPA_M72,39 +CPA_C20A,CPA_O84,23 +CPA_C20A,CPA_Q86,440 +CPA_C20A,CPA_R90,11 +CPA_C20A,CPA_S94,7 +CPA_C20A,CPA_S95,4 +CPA_C20B,CPA_B07 & B08,157 +CPA_C20B,CPA_C1107,334 +CPA_C20B,CPA_C13,418 +CPA_C20B,CPA_C15,46 +CPA_C20B,CPA_C16,58 +CPA_C20B,CPA_C17,254 +CPA_C20B,CPA_C18,7 +CPA_C20B,CPA_C19,522 +CPA_C20B,CPA_C203,790 +CPA_C20B,CPA_C204,114 +CPA_C20B,CPA_C205,1086 +CPA_C20B,CPA_C20A,413 +CPA_C20B,CPA_C20B,3132 +CPA_C20B,CPA_C20C,225 +CPA_C20B,CPA_C21,830 +CPA_C20B,CPA_C22,3874 +CPA_C20B,CPA_C235_6,400 +CPA_C20B,CPA_C23OTHER,364 +CPA_C20B,CPA_C241_3,25 +CPA_C20B,CPA_C244_5,8 +CPA_C20B,CPA_C25,34 +CPA_C20B,CPA_C26,150 +CPA_C20B,CPA_C27,265 +CPA_C20B,CPA_C29,1112 +CPA_C20B,CPA_C301,28 +CPA_C20B,CPA_C303,113 +CPA_C20B,CPA_C31,134 +CPA_C20B,CPA_C32,216 +CPA_C20B,CPA_C3315,28 +CPA_C20B,CPA_E36,162 +CPA_C20B,CPA_E37,25 +CPA_C20B,CPA_E38,11 +CPA_C20B,"CPA_F41, F42 & F43",1 +CPA_C20B,CPA_G46,98 +CPA_C20B,CPA_H52,7 +CPA_C20B,CPA_I56,2 +CPA_C20B,CPA_J62,7 +CPA_C20B,CPA_K64,8 +CPA_C20B,CPA_K65.1-2 & K65.3,1 +CPA_C20B,CPA_K66,1 +CPA_C20B,CPA_L68BXL683,56 +CPA_C20B,CPA_M71,825 +CPA_C20B,CPA_M72,737 +CPA_C20B,CPA_O84,53 +CPA_C20B,CPA_P85,13 +CPA_C20B,CPA_S95,3 +CPA_C20C,CPA_A01,2446 +CPA_C20C,CPA_C102_3,2 +CPA_C20C,CPA_C13,8 +CPA_C20C,CPA_C17,48 +CPA_C20C,CPA_C203,184 +CPA_C20C,CPA_C204,8 +CPA_C20C,CPA_C205,37 +CPA_C20C,CPA_C20A,29 +CPA_C20C,CPA_C20B,7 +CPA_C20C,CPA_C20C,526 +CPA_C20C,CPA_C21,1 +CPA_C20C,CPA_C22,50 +CPA_C20C,CPA_C235_6,32 +CPA_C20C,CPA_C27,1 +CPA_C20C,CPA_C32,6 +CPA_C20C,CPA_E36,9 +CPA_C20C,"CPA_F41, F42 & F43",2 +CPA_C20C,CPA_J59 & J60,12 +CPA_C20C,CPA_J62,6 +CPA_C20C,CPA_K64,5 +CPA_C20C,CPA_K65.1-2 & K65.3,2 +CPA_C20C,CPA_L68BXL683,50 +CPA_C20C,CPA_M72,7 +CPA_C20C,CPA_O84,56 +CPA_C20C,CPA_P85,5 +CPA_C20C,CPA_Q86,1 +CPA_C20C,CPA_R91,3 +CPA_C21,CPA_A01,85 +CPA_C21,CPA_C106,3 +CPA_C21,CPA_C109,24 +CPA_C21,CPA_C204,26 +CPA_C21,CPA_C20B,1 +CPA_C21,CPA_C21,8893 +CPA_C21,CPA_C28,40 +CPA_C21,CPA_C32,153 +CPA_C21,CPA_D351,17 +CPA_C21,CPA_G47,2 +CPA_C21,CPA_K66,1 +CPA_C21,CPA_L68BXL683,38 +CPA_C21,CPA_M72,711 +CPA_C21,CPA_M75,1043 +CPA_C21,CPA_O84,350 +CPA_C21,CPA_P85,21 +CPA_C21,CPA_Q86,17821 +CPA_C21,CPA_Q87 & Q88,68 +CPA_C21,CPA_S94,28 +CPA_C22,CPA_A01,719 +CPA_C22,CPA_A03,8 +CPA_C22,CPA_B05 & B06,2 +CPA_C22,CPA_B07 & B08,31 +CPA_C22,CPA_C101,594 +CPA_C22,CPA_C102_3,337 +CPA_C22,CPA_C104,16 +CPA_C22,CPA_C105,595 +CPA_C22,CPA_C106,88 +CPA_C22,CPA_C107,684 +CPA_C22,CPA_C108,812 +CPA_C22,CPA_C109,28 +CPA_C22,CPA_C11.01-6 & C12,54 +CPA_C22,CPA_C1107,1019 +CPA_C22,CPA_C13,205 +CPA_C22,CPA_C14,11 +CPA_C22,CPA_C15,2 +CPA_C22,CPA_C16,29 +CPA_C22,CPA_C17,463 +CPA_C22,CPA_C18,220 +CPA_C22,CPA_C19,6 +CPA_C22,CPA_C203,112 +CPA_C22,CPA_C204,559 +CPA_C22,CPA_C205,184 +CPA_C22,CPA_C20A,66 +CPA_C22,CPA_C20B,18 +CPA_C22,CPA_C21,82 +CPA_C22,CPA_C22,4792 +CPA_C22,CPA_C235_6,57 +CPA_C22,CPA_C23OTHER,196 +CPA_C22,CPA_C241_3,4 +CPA_C22,CPA_C244_5,2 +CPA_C22,CPA_C25,615 +CPA_C22,CPA_C26,258 +CPA_C22,CPA_C27,525 +CPA_C22,CPA_C28,1006 +CPA_C22,CPA_C29,3613 +CPA_C22,CPA_C301,27 +CPA_C22,CPA_C303,176 +CPA_C22,CPA_C30OTHER,41 +CPA_C22,CPA_C31,248 +CPA_C22,CPA_C32,363 +CPA_C22,CPA_C3315,8 +CPA_C22,CPA_C33OTHER,173 +CPA_C22,CPA_E36,1 +CPA_C22,CPA_E37,67 +CPA_C22,CPA_E38,360 +CPA_C22,CPA_E39,13 +CPA_C22,"CPA_F41, F42 & F43",4416 +CPA_C22,CPA_G45,713 +CPA_C22,CPA_G46,1958 +CPA_C22,CPA_G47,713 +CPA_C22,CPA_H491_2,11 +CPA_C22,CPA_H493_5,609 +CPA_C22,CPA_H52,334 +CPA_C22,CPA_I56,45 +CPA_C22,CPA_J61,47 +CPA_C22,CPA_J62,64 +CPA_C22,CPA_K64,199 +CPA_C22,CPA_K65.1-2 & K65.3,19 +CPA_C22,CPA_K66,90 +CPA_C22,CPA_L68BXL683,41 +CPA_C22,CPA_L68A,11 +CPA_C22,CPA_M691,2 +CPA_C22,CPA_M70,3 +CPA_C22,CPA_M72,37 +CPA_C22,CPA_M75,1 +CPA_C22,CPA_N81,411 +CPA_C22,CPA_N82,331 +CPA_C22,CPA_O84,233 +CPA_C22,CPA_P85,163 +CPA_C22,CPA_Q86,659 +CPA_C22,CPA_Q87 & Q88,85 +CPA_C22,CPA_R90,150 +CPA_C22,CPA_R93,4 +CPA_C22,CPA_S94,25 +CPA_C22,CPA_S95,1 +CPA_C22,CPA_S96,135 +CPA_C235_6,CPA_B07 & B08,436 +CPA_C235_6,CPA_C16,2 +CPA_C235_6,CPA_C203,8 +CPA_C235_6,CPA_C204,1 +CPA_C235_6,CPA_C205,4 +CPA_C235_6,CPA_C235_6,1113 +CPA_C235_6,CPA_C23OTHER,272 +CPA_C235_6,CPA_C25,143 +CPA_C235_6,CPA_C31,1 +CPA_C235_6,CPA_E36,2 +CPA_C235_6,CPA_E37,16 +CPA_C235_6,CPA_E38,44 +CPA_C235_6,"CPA_F41, F42 & F43",15142 +CPA_C235_6,CPA_G46,366 +CPA_C235_6,CPA_H52,2 +CPA_C235_6,CPA_K65.1-2 & K65.3,1 +CPA_C235_6,CPA_K66,1 +CPA_C235_6,CPA_L68BXL683,35 +CPA_C235_6,CPA_L68A,225 +CPA_C235_6,CPA_O84,257 +CPA_C235_6,CPA_P85,305 +CPA_C235_6,CPA_Q86,73 +CPA_C235_6,CPA_R90,24 +CPA_C235_6,CPA_R91,36 +CPA_C235_6,CPA_R93,69 +CPA_C235_6,CPA_S94,14 +CPA_C23OTHER,CPA_B07 & B08,326 +CPA_C23OTHER,CPA_C102_3,2 +CPA_C23OTHER,CPA_C105,1 +CPA_C23OTHER,CPA_C108,229 +CPA_C23OTHER,CPA_C11.01-6 & C12,743 +CPA_C23OTHER,CPA_C1107,246 +CPA_C23OTHER,CPA_C13,1 +CPA_C23OTHER,CPA_C16,47 +CPA_C23OTHER,CPA_C204,61 +CPA_C23OTHER,CPA_C20B,8 +CPA_C23OTHER,CPA_C21,26 +CPA_C23OTHER,CPA_C22,509 +CPA_C23OTHER,CPA_C235_6,16 +CPA_C23OTHER,CPA_C23OTHER,582 +CPA_C23OTHER,CPA_C241_3,121 +CPA_C23OTHER,CPA_C244_5,5 +CPA_C23OTHER,CPA_C25,157 +CPA_C23OTHER,CPA_C26,96 +CPA_C23OTHER,CPA_C27,148 +CPA_C23OTHER,CPA_C28,1 +CPA_C23OTHER,CPA_C29,1195 +CPA_C23OTHER,CPA_C301,48 +CPA_C23OTHER,CPA_C303,1 +CPA_C23OTHER,CPA_C31,2 +CPA_C23OTHER,CPA_C32,1 +CPA_C23OTHER,CPA_C3315,3 +CPA_C23OTHER,CPA_E38,42 +CPA_C23OTHER,"CPA_F41, F42 & F43",6205 +CPA_C23OTHER,CPA_G45,73 +CPA_C23OTHER,CPA_G46,1572 +CPA_C23OTHER,CPA_G47,283 +CPA_C23OTHER,CPA_H491_2,6 +CPA_C23OTHER,CPA_H52,6 +CPA_C23OTHER,CPA_I55,61 +CPA_C23OTHER,CPA_I56,129 +CPA_C23OTHER,CPA_K65.1-2 & K65.3,2 +CPA_C23OTHER,CPA_K66,1 +CPA_C23OTHER,CPA_L68BXL683,43 +CPA_C23OTHER,CPA_L68A,284 +CPA_C23OTHER,CPA_N81,34 +CPA_C23OTHER,CPA_O84,151 +CPA_C23OTHER,CPA_P85,186 +CPA_C23OTHER,CPA_Q86,63 +CPA_C23OTHER,CPA_R90,35 +CPA_C23OTHER,CPA_R91,15 +CPA_C23OTHER,CPA_S94,24 +CPA_C23OTHER,CPA_S96,98 +CPA_C241_3,CPA_B05 & B06,17 +CPA_C241_3,CPA_B09,40 +CPA_C241_3,CPA_C101,2 +CPA_C241_3,CPA_C102_3,1 +CPA_C241_3,CPA_C105,1 +CPA_C241_3,CPA_C19,6 +CPA_C241_3,CPA_C22,2 +CPA_C241_3,CPA_C235_6,99 +CPA_C241_3,CPA_C23OTHER,8 +CPA_C241_3,CPA_C241_3,2626 +CPA_C241_3,CPA_C244_5,185 +CPA_C241_3,CPA_C25,3692 +CPA_C241_3,CPA_C26,212 +CPA_C241_3,CPA_C27,1106 +CPA_C241_3,CPA_C28,2142 +CPA_C241_3,CPA_C29,4836 +CPA_C241_3,CPA_C301,91 +CPA_C241_3,CPA_C303,1555 +CPA_C241_3,CPA_C30OTHER,47 +CPA_C241_3,CPA_C31,259 +CPA_C241_3,CPA_C32,792 +CPA_C241_3,CPA_C3315,73 +CPA_C241_3,CPA_C33OTHER,295 +CPA_C241_3,CPA_E38,1676 +CPA_C241_3,"CPA_F41, F42 & F43",477 +CPA_C241_3,CPA_G46,518 +CPA_C241_3,CPA_K65.1-2 & K65.3,6 +CPA_C241_3,CPA_K66,7 +CPA_C241_3,CPA_L68BXL683,47 +CPA_C241_3,CPA_M71,742 +CPA_C241_3,CPA_R90,7 +CPA_C241_3,CPA_R91,19 +CPA_C241_3,CPA_S95,2 +CPA_C244_5,CPA_C102_3,4 +CPA_C244_5,CPA_C108,3 +CPA_C244_5,CPA_C205,101 +CPA_C244_5,CPA_C20B,37 +CPA_C244_5,CPA_C21,9 +CPA_C244_5,CPA_C22,173 +CPA_C244_5,CPA_C235_6,2 +CPA_C244_5,CPA_C23OTHER,26 +CPA_C244_5,CPA_C241_3,289 +CPA_C244_5,CPA_C244_5,1641 +CPA_C244_5,CPA_C25,2042 +CPA_C244_5,CPA_C26,258 +CPA_C244_5,CPA_C27,960 +CPA_C244_5,CPA_C28,1839 +CPA_C244_5,CPA_C29,1658 +CPA_C244_5,CPA_C301,34 +CPA_C244_5,CPA_C303,782 +CPA_C244_5,CPA_C30OTHER,41 +CPA_C244_5,CPA_C31,50 +CPA_C244_5,CPA_C32,313 +CPA_C244_5,CPA_C3315,47 +CPA_C244_5,CPA_C3316,32 +CPA_C244_5,CPA_C33OTHER,62 +CPA_C244_5,CPA_E36,1 +CPA_C244_5,"CPA_F41, F42 & F43",2007 +CPA_C244_5,CPA_G46,78 +CPA_C244_5,CPA_K64,1 +CPA_C244_5,CPA_K65.1-2 & K65.3,1 +CPA_C244_5,CPA_K66,1 +CPA_C244_5,CPA_L68BXL683,48 +CPA_C244_5,CPA_N81,4 +CPA_C244_5,CPA_R91,4 +CPA_C244_5,CPA_S95,1 +CPA_C25,CPA_A01,350 +CPA_C25,CPA_A03,2 +CPA_C25,CPA_B05 & B06,145 +CPA_C25,CPA_B07 & B08,18 +CPA_C25,CPA_B09,259 +CPA_C25,CPA_C101,8 +CPA_C25,CPA_C102_3,160 +CPA_C25,CPA_C105,11 +CPA_C25,CPA_C107,45 +CPA_C25,CPA_C108,132 +CPA_C25,CPA_C109,1 +CPA_C25,CPA_C11.01-6 & C12,226 +CPA_C25,CPA_C1107,8 +CPA_C25,CPA_C13,21 +CPA_C25,CPA_C14,1 +CPA_C25,CPA_C15,2 +CPA_C25,CPA_C16,232 +CPA_C25,CPA_C17,129 +CPA_C25,CPA_C18,59 +CPA_C25,CPA_C19,9 +CPA_C25,CPA_C203,11 +CPA_C25,CPA_C204,313 +CPA_C25,CPA_C205,128 +CPA_C25,CPA_C20A,142 +CPA_C25,CPA_C20B,6 +CPA_C25,CPA_C21,11 +CPA_C25,CPA_C22,765 +CPA_C25,CPA_C235_6,70 +CPA_C25,CPA_C23OTHER,275 +CPA_C25,CPA_C241_3,972 +CPA_C25,CPA_C244_5,36 +CPA_C25,CPA_C25,7634 +CPA_C25,CPA_C26,926 +CPA_C25,CPA_C27,817 +CPA_C25,CPA_C28,5667 +CPA_C25,CPA_C29,3995 +CPA_C25,CPA_C301,127 +CPA_C25,CPA_C303,1765 +CPA_C25,CPA_C30OTHER,94 +CPA_C25,CPA_C31,259 +CPA_C25,CPA_C32,426 +CPA_C25,CPA_C3315,12 +CPA_C25,CPA_C3316,98 +CPA_C25,CPA_C33OTHER,631 +CPA_C25,CPA_D351,382 +CPA_C25,CPA_D352_3,3 +CPA_C25,CPA_E36,60 +CPA_C25,CPA_E38,813 +CPA_C25,"CPA_F41, F42 & F43",12466 +CPA_C25,CPA_G45,190 +CPA_C25,CPA_G46,2104 +CPA_C25,CPA_G47,257 +CPA_C25,CPA_H491_2,35 +CPA_C25,CPA_H52,6 +CPA_C25,CPA_K64,37 +CPA_C25,CPA_K65.1-2 & K65.3,11 +CPA_C25,CPA_K66,62 +CPA_C25,CPA_L68BXL683,57 +CPA_C25,CPA_L68A,442 +CPA_C25,CPA_M71,258 +CPA_C25,CPA_N81,714 +CPA_C25,CPA_N82,824 +CPA_C25,CPA_O84,3823 +CPA_C25,CPA_P85,112 +CPA_C25,CPA_Q86,152 +CPA_C25,CPA_Q87 & Q88,5 +CPA_C25,CPA_R93,12 +CPA_C25,CPA_S95,30 +CPA_C25,CPA_S96,22 +CPA_C26,CPA_A01,33 +CPA_C26,CPA_A02,3 +CPA_C26,CPA_A03,2 +CPA_C26,CPA_B05 & B06,22 +CPA_C26,CPA_B07 & B08,5 +CPA_C26,CPA_B09,27 +CPA_C26,CPA_C101,11 +CPA_C26,CPA_C102_3,13 +CPA_C26,CPA_C104,1 +CPA_C26,CPA_C105,6 +CPA_C26,CPA_C106,5 +CPA_C26,CPA_C107,23 +CPA_C26,CPA_C108,31 +CPA_C26,CPA_C109,13 +CPA_C26,CPA_C11.01-6 & C12,16 +CPA_C26,CPA_C1107,15 +CPA_C26,CPA_C13,16 +CPA_C26,CPA_C14,14 +CPA_C26,CPA_C15,2 +CPA_C26,CPA_C16,18 +CPA_C26,CPA_C17,16 +CPA_C26,CPA_C18,247 +CPA_C26,CPA_C19,9 +CPA_C26,CPA_C203,7 +CPA_C26,CPA_C204,8 +CPA_C26,CPA_C205,35 +CPA_C26,CPA_C20A,96 +CPA_C26,CPA_C20B,8 +CPA_C26,CPA_C20C,3 +CPA_C26,CPA_C21,95 +CPA_C26,CPA_C22,66 +CPA_C26,CPA_C235_6,11 +CPA_C26,CPA_C23OTHER,16 +CPA_C26,CPA_C241_3,6 +CPA_C26,CPA_C244_5,5 +CPA_C26,CPA_C25,639 +CPA_C26,CPA_C26,2684 +CPA_C26,CPA_C27,760 +CPA_C26,CPA_C28,435 +CPA_C26,CPA_C29,1676 +CPA_C26,CPA_C301,12 +CPA_C26,CPA_C303,232 +CPA_C26,CPA_C30OTHER,3 +CPA_C26,CPA_C31,45 +CPA_C26,CPA_C32,78 +CPA_C26,CPA_C3315,8 +CPA_C26,CPA_C3316,8 +CPA_C26,CPA_C33OTHER,412 +CPA_C26,CPA_D351,608 +CPA_C26,CPA_D352_3,20 +CPA_C26,CPA_E36,78 +CPA_C26,CPA_E37,7 +CPA_C26,CPA_E38,158 +CPA_C26,CPA_E39,21 +CPA_C26,"CPA_F41, F42 & F43",1431 +CPA_C26,CPA_G45,185 +CPA_C26,CPA_G46,1023 +CPA_C26,CPA_G47,1185 +CPA_C26,CPA_H491_2,6 +CPA_C26,CPA_H493_5,164 +CPA_C26,CPA_H50,65 +CPA_C26,CPA_H51,1 +CPA_C26,CPA_H52,459 +CPA_C26,CPA_H53,71 +CPA_C26,CPA_I55,94 +CPA_C26,CPA_I56,234 +CPA_C26,CPA_J58,377 +CPA_C26,CPA_J59 & J60,3860 +CPA_C26,CPA_J61,3151 +CPA_C26,CPA_J62,2107 +CPA_C26,CPA_J63,274 +CPA_C26,CPA_K64,137 +CPA_C26,CPA_K65.1-2 & K65.3,30 +CPA_C26,CPA_K66,127 +CPA_C26,CPA_L68BXL683,1009 +CPA_C26,CPA_L68A,33 +CPA_C26,CPA_L683,143 +CPA_C26,CPA_M691,392 +CPA_C26,CPA_M692,33 +CPA_C26,CPA_M70,154 +CPA_C26,CPA_M71,1940 +CPA_C26,CPA_M72,113 +CPA_C26,CPA_M73,207 +CPA_C26,CPA_M74,1004 +CPA_C26,CPA_M75,48 +CPA_C26,CPA_N77,330 +CPA_C26,CPA_N78,272 +CPA_C26,CPA_N79,301 +CPA_C26,CPA_N80,113 +CPA_C26,CPA_N81,346 +CPA_C26,CPA_N82,645 +CPA_C26,CPA_O84,13023 +CPA_C26,CPA_P85,3003 +CPA_C26,CPA_Q86,14517 +CPA_C26,CPA_Q87 & Q88,891 +CPA_C26,CPA_R90,328 +CPA_C26,CPA_R91,56 +CPA_C26,CPA_R92,59 +CPA_C26,CPA_R93,192 +CPA_C26,CPA_S94,693 +CPA_C26,CPA_S95,340 +CPA_C26,CPA_S96,151 +CPA_C27,CPA_C21,330 +CPA_C27,CPA_C22,5 +CPA_C27,CPA_C235_6,4 +CPA_C27,CPA_C23OTHER,4 +CPA_C27,CPA_C244_5,2 +CPA_C27,CPA_C25,275 +CPA_C27,CPA_C26,1155 +CPA_C27,CPA_C27,1610 +CPA_C27,CPA_C28,445 +CPA_C27,CPA_C29,445 +CPA_C27,CPA_C301,28 +CPA_C27,CPA_C303,1016 +CPA_C27,CPA_C30OTHER,16 +CPA_C27,CPA_C31,2 +CPA_C27,CPA_C32,362 +CPA_C27,CPA_C3315,8 +CPA_C27,CPA_C3316,7 +CPA_C27,CPA_C33OTHER,105 +CPA_C27,CPA_D351,1466 +CPA_C27,CPA_D352_3,3 +CPA_C27,CPA_E38,208 +CPA_C27,"CPA_F41, F42 & F43",8369 +CPA_C27,CPA_G45,101 +CPA_C27,CPA_G46,909 +CPA_C27,CPA_G47,1046 +CPA_C27,CPA_H493_5,78 +CPA_C27,CPA_H52,6 +CPA_C27,CPA_H53,1 +CPA_C27,CPA_J59 & J60,15 +CPA_C27,CPA_J61,428 +CPA_C27,CPA_J62,89 +CPA_C27,CPA_J63,24 +CPA_C27,CPA_K64,94 +CPA_C27,CPA_K65.1-2 & K65.3,11 +CPA_C27,CPA_K66,47 +CPA_C27,CPA_L68BXL683,47 +CPA_C27,CPA_L68A,20 +CPA_C27,CPA_M70,102 +CPA_C27,CPA_M71,699 +CPA_C27,CPA_M72,93 +CPA_C27,CPA_N77,263 +CPA_C27,CPA_N80,390 +CPA_C27,CPA_O84,847 +CPA_C27,CPA_P85,127 +CPA_C27,CPA_Q86,40 +CPA_C27,CPA_Q87 & Q88,86 +CPA_C27,CPA_R91,12 +CPA_C27,CPA_R93,60 +CPA_C27,CPA_S95,116 +CPA_C27,CPA_S96,206 +CPA_C28,CPA_A01,15 +CPA_C28,CPA_A02,84 +CPA_C28,CPA_B05 & B06,1288 +CPA_C28,CPA_B07 & B08,112 +CPA_C28,CPA_B09,385 +CPA_C28,CPA_C101,164 +CPA_C28,CPA_C102_3,3 +CPA_C28,CPA_C104,1 +CPA_C28,CPA_C105,3 +CPA_C28,CPA_C106,44 +CPA_C28,CPA_C107,165 +CPA_C28,CPA_C108,197 +CPA_C28,CPA_C109,3 +CPA_C28,CPA_C11.01-6 & C12,192 +CPA_C28,CPA_C1107,492 +CPA_C28,CPA_C13,237 +CPA_C28,CPA_C14,14 +CPA_C28,CPA_C16,131 +CPA_C28,CPA_C17,173 +CPA_C28,CPA_C18,36 +CPA_C28,CPA_C19,161 +CPA_C28,CPA_C203,10 +CPA_C28,CPA_C204,1 +CPA_C28,CPA_C205,49 +CPA_C28,CPA_C20A,89 +CPA_C28,CPA_C20B,37 +CPA_C28,CPA_C20C,28 +CPA_C28,CPA_C21,238 +CPA_C28,CPA_C22,245 +CPA_C28,CPA_C235_6,102 +CPA_C28,CPA_C23OTHER,158 +CPA_C28,CPA_C241_3,230 +CPA_C28,CPA_C244_5,39 +CPA_C28,CPA_C25,1534 +CPA_C28,CPA_C26,1141 +CPA_C28,CPA_C27,846 +CPA_C28,CPA_C28,7193 +CPA_C28,CPA_C29,3488 +CPA_C28,CPA_C301,73 +CPA_C28,CPA_C303,303 +CPA_C28,CPA_C30OTHER,56 +CPA_C28,CPA_C31,21 +CPA_C28,CPA_C32,582 +CPA_C28,CPA_C3315,26 +CPA_C28,CPA_C3316,31 +CPA_C28,CPA_C33OTHER,1013 +CPA_C28,CPA_D351,4103 +CPA_C28,CPA_D352_3,25 +CPA_C28,CPA_E36,335 +CPA_C28,CPA_E38,634 +CPA_C28,"CPA_F41, F42 & F43",5891 +CPA_C28,CPA_G45,472 +CPA_C28,CPA_G46,1968 +CPA_C28,CPA_G47,609 +CPA_C28,CPA_H491_2,23 +CPA_C28,CPA_H52,82 +CPA_C28,CPA_H53,2 +CPA_C28,CPA_J59 & J60,14 +CPA_C28,CPA_J61,604 +CPA_C28,CPA_K64,58 +CPA_C28,CPA_K65.1-2 & K65.3,4 +CPA_C28,CPA_K66,29 +CPA_C28,CPA_L68BXL683,40 +CPA_C28,CPA_M70,4 +CPA_C28,CPA_M71,1164 +CPA_C28,CPA_M73,38 +CPA_C28,CPA_N77,1933 +CPA_C28,CPA_N80,83 +CPA_C28,CPA_N81,626 +CPA_C28,CPA_O84,351 +CPA_C28,CPA_R92,20 +CPA_C28,CPA_R93,318 +CPA_C28,CPA_S94,3 +CPA_C28,CPA_S95,17 +CPA_C28,CPA_S96,307 +CPA_C29,CPA_A02,48 +CPA_C29,CPA_B05 & B06,1 +CPA_C29,CPA_B07 & B08,26 +CPA_C29,CPA_C101,4 +CPA_C29,CPA_C102_3,2 +CPA_C29,CPA_C105,1 +CPA_C29,CPA_C107,4 +CPA_C29,CPA_C108,1 +CPA_C29,CPA_C1107,6 +CPA_C29,CPA_C203,2 +CPA_C29,CPA_C20A,4 +CPA_C29,CPA_C20C,2 +CPA_C29,CPA_C22,31 +CPA_C29,CPA_C235_6,57 +CPA_C29,CPA_C23OTHER,17 +CPA_C29,CPA_C241_3,8 +CPA_C29,CPA_C244_5,8 +CPA_C29,CPA_C25,43 +CPA_C29,CPA_C26,19 +CPA_C29,CPA_C27,14 +CPA_C29,CPA_C28,759 +CPA_C29,CPA_C29,22341 +CPA_C29,CPA_C30OTHER,3 +CPA_C29,CPA_C31,64 +CPA_C29,CPA_C32,11 +CPA_C29,CPA_C33OTHER,142 +CPA_C29,CPA_E36,4 +CPA_C29,CPA_E37,119 +CPA_C29,CPA_E38,76 +CPA_C29,"CPA_F41, F42 & F43",647 +CPA_C29,CPA_G45,16778 +CPA_C29,CPA_G46,909 +CPA_C29,CPA_G47,545 +CPA_C29,CPA_H493_5,2552 +CPA_C29,CPA_H52,507 +CPA_C29,CPA_H53,72 +CPA_C29,CPA_J59 & J60,12 +CPA_C29,CPA_J61,464 +CPA_C29,CPA_J62,175 +CPA_C29,CPA_J63,50 +CPA_C29,CPA_K64,168 +CPA_C29,CPA_K65.1-2 & K65.3,50 +CPA_C29,CPA_K66,145 +CPA_C29,CPA_L68BXL683,41 +CPA_C29,CPA_L68A,25 +CPA_C29,CPA_M70,458 +CPA_C29,CPA_M73,3 +CPA_C29,CPA_N77,1511 +CPA_C29,CPA_N78,154 +CPA_C29,CPA_N80,141 +CPA_C29,CPA_N81,10 +CPA_C29,CPA_O84,667 +CPA_C29,CPA_P85,665 +CPA_C29,CPA_Q86,228 +CPA_C29,CPA_Q87 & Q88,472 +CPA_C29,CPA_R91,8 +CPA_C29,CPA_R93,531 +CPA_C29,CPA_S94,3 +CPA_C29,CPA_S95,8 +CPA_C29,CPA_S96,10 +CPA_C301,CPA_A03,1 +CPA_C301,CPA_B05 & B06,200 +CPA_C301,CPA_C20B,2 +CPA_C301,CPA_C26,32 +CPA_C301,CPA_C29,28 +CPA_C301,CPA_C301,3265 +CPA_C301,CPA_C3315,41 +CPA_C301,CPA_H50,390 +CPA_C301,CPA_K65.1-2 & K65.3,2 +CPA_C301,CPA_L68BXL683,44 +CPA_C301,CPA_O84,585 +CPA_C301,CPA_R90,2 +CPA_C303,CPA_C25,3 +CPA_C303,CPA_C26,16 +CPA_C303,CPA_C29,12 +CPA_C303,CPA_C303,9392 +CPA_C303,CPA_C3316,2188 +CPA_C303,CPA_H51,369 +CPA_C303,CPA_H52,2 +CPA_C303,CPA_K64,1 +CPA_C303,CPA_K65.1-2 & K65.3,12 +CPA_C303,CPA_K66,5 +CPA_C303,CPA_L68BXL683,36 +CPA_C303,CPA_O84,5506 +CPA_C303,CPA_R90,7 +CPA_C303,CPA_R91,3 +CPA_C30OTHER,CPA_C25,5 +CPA_C30OTHER,CPA_C26,2007 +CPA_C30OTHER,CPA_C28,1 +CPA_C30OTHER,CPA_C303,1 +CPA_C30OTHER,CPA_C30OTHER,822 +CPA_C30OTHER,CPA_C33OTHER,1081 +CPA_C30OTHER,CPA_H491_2,444 +CPA_C30OTHER,CPA_H52,6 +CPA_C30OTHER,CPA_K64,2 +CPA_C30OTHER,CPA_K65.1-2 & K65.3,2 +CPA_C30OTHER,CPA_L68BXL683,43 +CPA_C30OTHER,CPA_O84,12 +CPA_C30OTHER,CPA_Q86,432 +CPA_C30OTHER,CPA_S94,2 +CPA_C31,CPA_C13,3 +CPA_C31,CPA_C16,7 +CPA_C31,CPA_C22,3 +CPA_C31,CPA_C25,12 +CPA_C31,CPA_C28,1 +CPA_C31,CPA_C29,8 +CPA_C31,CPA_C301,18 +CPA_C31,CPA_C303,1 +CPA_C31,CPA_C30OTHER,1 +CPA_C31,CPA_C31,759 +CPA_C31,CPA_C32,3 +CPA_C31,"CPA_F41, F42 & F43",516 +CPA_C31,CPA_K64,30 +CPA_C31,CPA_K66,9 +CPA_C31,CPA_L68BXL683,31 +CPA_C31,CPA_L68A,4 +CPA_C31,CPA_O84,992 +CPA_C31,CPA_P85,397 +CPA_C31,CPA_Q86,240 +CPA_C31,CPA_Q87 & Q88,144 +CPA_C31,CPA_R90,2 +CPA_C31,CPA_R91,2 +CPA_C31,CPA_R93,42 +CPA_C31,CPA_S94,6 +CPA_C31,CPA_S95,1 +CPA_C32,CPA_A01,104 +CPA_C32,CPA_A02,9 +CPA_C32,CPA_A03,3 +CPA_C32,CPA_B05 & B06,22 +CPA_C32,CPA_B07 & B08,11 +CPA_C32,CPA_B09,20 +CPA_C32,CPA_C101,35 +CPA_C32,CPA_C102_3,26 +CPA_C32,CPA_C106,4 +CPA_C32,CPA_C107,12 +CPA_C32,CPA_C108,11 +CPA_C32,CPA_C109,2 +CPA_C32,CPA_C13,40 +CPA_C32,CPA_C14,51 +CPA_C32,CPA_C15,3 +CPA_C32,CPA_C16,8 +CPA_C32,CPA_C17,3 +CPA_C32,CPA_C18,24 +CPA_C32,CPA_C19,3 +CPA_C32,CPA_C203,2 +CPA_C32,CPA_C204,5 +CPA_C32,CPA_C205,2 +CPA_C32,CPA_C20A,3 +CPA_C32,CPA_C20B,2 +CPA_C32,CPA_C20C,1 +CPA_C32,CPA_C21,135 +CPA_C32,CPA_C22,54 +CPA_C32,CPA_C235_6,9 +CPA_C32,CPA_C23OTHER,27 +CPA_C32,CPA_C241_3,1 +CPA_C32,CPA_C244_5,11 +CPA_C32,CPA_C25,19 +CPA_C32,CPA_C26,397 +CPA_C32,CPA_C27,5 +CPA_C32,CPA_C28,36 +CPA_C32,CPA_C29,8 +CPA_C32,CPA_C301,11 +CPA_C32,CPA_C303,10 +CPA_C32,CPA_C30OTHER,1 +CPA_C32,CPA_C31,8 +CPA_C32,CPA_C32,1439 +CPA_C32,CPA_C3315,29 +CPA_C32,CPA_C33OTHER,116 +CPA_C32,CPA_D351,181 +CPA_C32,CPA_D352_3,8 +CPA_C32,CPA_E36,10 +CPA_C32,CPA_E37,12 +CPA_C32,CPA_E38,146 +CPA_C32,CPA_E39,6 +CPA_C32,"CPA_F41, F42 & F43",1157 +CPA_C32,CPA_G45,81 +CPA_C32,CPA_G46,179 +CPA_C32,CPA_G47,118 +CPA_C32,CPA_H491_2,6 +CPA_C32,CPA_H493_5,136 +CPA_C32,CPA_H50,243 +CPA_C32,CPA_H51,2 +CPA_C32,CPA_H52,183 +CPA_C32,CPA_H53,57 +CPA_C32,CPA_I55,39 +CPA_C32,CPA_I56,22 +CPA_C32,CPA_J58,20 +CPA_C32,CPA_J59 & J60,122 +CPA_C32,CPA_J61,34 +CPA_C32,CPA_J62,81 +CPA_C32,CPA_J63,8 +CPA_C32,CPA_K64,248 +CPA_C32,CPA_K65.1-2 & K65.3,49 +CPA_C32,CPA_K66,369 +CPA_C32,CPA_L68BXL683,76 +CPA_C32,CPA_L68A,6 +CPA_C32,CPA_L683,20 +CPA_C32,CPA_M691,26 +CPA_C32,CPA_M692,7 +CPA_C32,CPA_M70,60 +CPA_C32,CPA_M71,27 +CPA_C32,CPA_M72,64 +CPA_C32,CPA_M73,11 +CPA_C32,CPA_M74,227 +CPA_C32,CPA_M75,85 +CPA_C32,CPA_N77,272 +CPA_C32,CPA_N78,27 +CPA_C32,CPA_N80,4 +CPA_C32,CPA_N81,325 +CPA_C32,CPA_N82,95 +CPA_C32,CPA_O84,96 +CPA_C32,CPA_P85,339 +CPA_C32,CPA_Q86,4754 +CPA_C32,CPA_Q87 & Q88,251 +CPA_C32,CPA_R90,90 +CPA_C32,CPA_R91,25 +CPA_C32,CPA_R92,60 +CPA_C32,CPA_R93,132 +CPA_C32,CPA_S94,4 +CPA_C32,CPA_S95,5 +CPA_C32,CPA_S96,215 +CPA_C3315,CPA_A03,36 +CPA_C3315,CPA_B05 & B06,95 +CPA_C3315,CPA_B09,15 +CPA_C3315,CPA_C301,17 +CPA_C3315,CPA_C3315,20 +CPA_C3315,CPA_C33OTHER,1 +CPA_C3315,CPA_H50,589 +CPA_C3315,CPA_H52,8 +CPA_C3315,CPA_K66,25 +CPA_C3316,CPA_C303,414 +CPA_C3316,CPA_C3316,405 +CPA_C3316,CPA_C33OTHER,1 +CPA_C3316,CPA_H51,3259 +CPA_C3316,CPA_H52,9 +CPA_C33OTHER,CPA_A01,164 +CPA_C33OTHER,CPA_A02,15 +CPA_C33OTHER,CPA_A03,26 +CPA_C33OTHER,CPA_B05 & B06,583 +CPA_C33OTHER,CPA_B07 & B08,192 +CPA_C33OTHER,CPA_B09,105 +CPA_C33OTHER,CPA_C101,280 +CPA_C33OTHER,CPA_C102_3,122 +CPA_C33OTHER,CPA_C104,22 +CPA_C33OTHER,CPA_C105,134 +CPA_C33OTHER,CPA_C106,81 +CPA_C33OTHER,CPA_C107,220 +CPA_C33OTHER,CPA_C108,271 +CPA_C33OTHER,CPA_C109,90 +CPA_C33OTHER,CPA_C11.01-6 & C12,213 +CPA_C33OTHER,CPA_C1107,71 +CPA_C33OTHER,CPA_C13,53 +CPA_C33OTHER,CPA_C14,6 +CPA_C33OTHER,CPA_C15,1 +CPA_C33OTHER,CPA_C16,99 +CPA_C33OTHER,CPA_C17,108 +CPA_C33OTHER,CPA_C18,160 +CPA_C33OTHER,CPA_C19,82 +CPA_C33OTHER,CPA_C203,44 +CPA_C33OTHER,CPA_C204,64 +CPA_C33OTHER,CPA_C205,49 +CPA_C33OTHER,CPA_C20A,70 +CPA_C33OTHER,CPA_C20B,25 +CPA_C33OTHER,CPA_C20C,23 +CPA_C33OTHER,CPA_C21,119 +CPA_C33OTHER,CPA_C22,336 +CPA_C33OTHER,CPA_C235_6,247 +CPA_C33OTHER,CPA_C23OTHER,149 +CPA_C33OTHER,CPA_C241_3,67 +CPA_C33OTHER,CPA_C244_5,74 +CPA_C33OTHER,CPA_C25,416 +CPA_C33OTHER,CPA_C26,143 +CPA_C33OTHER,CPA_C27,84 +CPA_C33OTHER,CPA_C28,253 +CPA_C33OTHER,CPA_C29,1184 +CPA_C33OTHER,CPA_C301,3 +CPA_C33OTHER,CPA_C303,328 +CPA_C33OTHER,CPA_C30OTHER,56 +CPA_C33OTHER,CPA_C31,94 +CPA_C33OTHER,CPA_C32,119 +CPA_C33OTHER,CPA_C3315,3 +CPA_C33OTHER,CPA_C3316,48 +CPA_C33OTHER,CPA_C33OTHER,1717 +CPA_C33OTHER,CPA_D351,3477 +CPA_C33OTHER,CPA_D352_3,1764 +CPA_C33OTHER,CPA_E36,191 +CPA_C33OTHER,CPA_E37,6 +CPA_C33OTHER,CPA_E38,263 +CPA_C33OTHER,CPA_E39,19 +CPA_C33OTHER,"CPA_F41, F42 & F43",249 +CPA_C33OTHER,CPA_G45,274 +CPA_C33OTHER,CPA_G46,649 +CPA_C33OTHER,CPA_G47,1611 +CPA_C33OTHER,CPA_H491_2,1051 +CPA_C33OTHER,CPA_H493_5,476 +CPA_C33OTHER,CPA_H50,51 +CPA_C33OTHER,CPA_H51,11 +CPA_C33OTHER,CPA_H52,1017 +CPA_C33OTHER,CPA_H53,172 +CPA_C33OTHER,CPA_I55,200 +CPA_C33OTHER,CPA_I56,481 +CPA_C33OTHER,CPA_J58,27 +CPA_C33OTHER,CPA_J59 & J60,129 +CPA_C33OTHER,CPA_J61,1340 +CPA_C33OTHER,CPA_J62,223 +CPA_C33OTHER,CPA_J63,52 +CPA_C33OTHER,CPA_K64,21 +CPA_C33OTHER,CPA_K65.1-2 & K65.3,2 +CPA_C33OTHER,CPA_K66,31 +CPA_C33OTHER,CPA_L68BXL683,160 +CPA_C33OTHER,CPA_L683,202 +CPA_C33OTHER,CPA_M691,75 +CPA_C33OTHER,CPA_M692,57 +CPA_C33OTHER,CPA_M70,195 +CPA_C33OTHER,CPA_M71,239 +CPA_C33OTHER,CPA_M72,237 +CPA_C33OTHER,CPA_M73,42 +CPA_C33OTHER,CPA_M74,109 +CPA_C33OTHER,CPA_M75,34 +CPA_C33OTHER,CPA_N77,860 +CPA_C33OTHER,CPA_N78,19 +CPA_C33OTHER,CPA_N79,25 +CPA_C33OTHER,CPA_N80,44 +CPA_C33OTHER,CPA_N81,155 +CPA_C33OTHER,CPA_N82,270 +CPA_C33OTHER,CPA_P85,196 +CPA_C33OTHER,CPA_Q86,361 +CPA_C33OTHER,CPA_Q87 & Q88,1214 +CPA_C33OTHER,CPA_R90,78 +CPA_C33OTHER,CPA_R91,44 +CPA_C33OTHER,CPA_R92,101 +CPA_C33OTHER,CPA_R93,484 +CPA_C33OTHER,CPA_S94,113 +CPA_C33OTHER,CPA_S95,7 +CPA_C33OTHER,CPA_S96,78 +CPA_D351,CPA_A01,619 +CPA_D351,CPA_A02,6 +CPA_D351,CPA_A03,31 +CPA_D351,CPA_B05 & B06,111 +CPA_D351,CPA_B07 & B08,343 +CPA_D351,CPA_B09,55 +CPA_D351,CPA_C101,410 +CPA_D351,CPA_C102_3,248 +CPA_D351,CPA_C104,37 +CPA_D351,CPA_C105,144 +CPA_D351,CPA_C106,118 +CPA_D351,CPA_C107,338 +CPA_D351,CPA_C108,366 +CPA_D351,CPA_C109,143 +CPA_D351,CPA_C11.01-6 & C12,222 +CPA_D351,CPA_C1107,93 +CPA_D351,CPA_C13,127 +CPA_D351,CPA_C14,36 +CPA_D351,CPA_C15,8 +CPA_D351,CPA_C16,192 +CPA_D351,CPA_C17,470 +CPA_D351,CPA_C18,184 +CPA_D351,CPA_C19,288 +CPA_D351,CPA_C203,41 +CPA_D351,CPA_C204,94 +CPA_D351,CPA_C205,69 +CPA_D351,CPA_C20A,167 +CPA_D351,CPA_C20B,167 +CPA_D351,CPA_C20C,55 +CPA_D351,CPA_C21,223 +CPA_D351,CPA_C22,750 +CPA_D351,CPA_C235_6,237 +CPA_D351,CPA_C23OTHER,274 +CPA_D351,CPA_C241_3,128 +CPA_D351,CPA_C244_5,210 +CPA_D351,CPA_C25,765 +CPA_D351,CPA_C26,233 +CPA_D351,CPA_C27,96 +CPA_D351,CPA_C28,260 +CPA_D351,CPA_C29,532 +CPA_D351,CPA_C301,64 +CPA_D351,CPA_C303,252 +CPA_D351,CPA_C30OTHER,17 +CPA_D351,CPA_C31,87 +CPA_D351,CPA_C32,199 +CPA_D351,CPA_C3315,7 +CPA_D351,CPA_C3316,130 +CPA_D351,CPA_C33OTHER,139 +CPA_D351,CPA_D351,62886 +CPA_D351,CPA_D352_3,5389 +CPA_D351,CPA_E36,931 +CPA_D351,CPA_E37,244 +CPA_D351,CPA_E38,227 +CPA_D351,CPA_E39,8 +CPA_D351,"CPA_F41, F42 & F43",1164 +CPA_D351,CPA_G45,785 +CPA_D351,CPA_G46,2008 +CPA_D351,CPA_G47,4516 +CPA_D351,CPA_H491_2,633 +CPA_D351,CPA_H493_5,320 +CPA_D351,CPA_H50,12 +CPA_D351,CPA_H51,24 +CPA_D351,CPA_H52,1097 +CPA_D351,CPA_H53,174 +CPA_D351,CPA_I55,1412 +CPA_D351,CPA_I56,1881 +CPA_D351,CPA_J58,54 +CPA_D351,CPA_J59 & J60,361 +CPA_D351,CPA_J61,1236 +CPA_D351,CPA_J62,890 +CPA_D351,CPA_J63,478 +CPA_D351,CPA_K64,550 +CPA_D351,CPA_K65.1-2 & K65.3,29 +CPA_D351,CPA_K66,631 +CPA_D351,CPA_L68BXL683,515 +CPA_D351,CPA_L68A,2045 +CPA_D351,CPA_L683,283 +CPA_D351,CPA_M691,220 +CPA_D351,CPA_M692,111 +CPA_D351,CPA_M70,626 +CPA_D351,CPA_M71,284 +CPA_D351,CPA_M72,211 +CPA_D351,CPA_M73,57 +CPA_D351,CPA_M74,156 +CPA_D351,CPA_M75,73 +CPA_D351,CPA_N77,203 +CPA_D351,CPA_N78,134 +CPA_D351,CPA_N79,51 +CPA_D351,CPA_N80,22 +CPA_D351,CPA_N81,285 +CPA_D351,CPA_N82,485 +CPA_D351,CPA_O84,1168 +CPA_D351,CPA_P85,1656 +CPA_D351,CPA_Q86,2046 +CPA_D351,CPA_Q87 & Q88,578 +CPA_D351,CPA_R90,138 +CPA_D351,CPA_R91,97 +CPA_D351,CPA_R92,76 +CPA_D351,CPA_R93,672 +CPA_D351,CPA_S94,144 +CPA_D351,CPA_S95,27 +CPA_D351,CPA_S96,249 +CPA_D352_3,CPA_A01,3 +CPA_D352_3,CPA_B05 & B06,13 +CPA_D352_3,CPA_B07 & B08,64 +CPA_D352_3,CPA_B09,8 +CPA_D352_3,CPA_C101,94 +CPA_D352_3,CPA_C102_3,183 +CPA_D352_3,CPA_C104,34 +CPA_D352_3,CPA_C105,106 +CPA_D352_3,CPA_C106,50 +CPA_D352_3,CPA_C107,217 +CPA_D352_3,CPA_C108,314 +CPA_D352_3,CPA_C109,37 +CPA_D352_3,CPA_C11.01-6 & C12,260 +CPA_D352_3,CPA_C1107,22 +CPA_D352_3,CPA_C13,43 +CPA_D352_3,CPA_C14,18 +CPA_D352_3,CPA_C15,3 +CPA_D352_3,CPA_C16,70 +CPA_D352_3,CPA_C17,294 +CPA_D352_3,CPA_C18,29 +CPA_D352_3,CPA_C19,22 +CPA_D352_3,CPA_C203,8 +CPA_D352_3,CPA_C204,25 +CPA_D352_3,CPA_C205,40 +CPA_D352_3,CPA_C20A,172 +CPA_D352_3,CPA_C20B,275 +CPA_D352_3,CPA_C20C,80 +CPA_D352_3,CPA_C21,113 +CPA_D352_3,CPA_C22,257 +CPA_D352_3,CPA_C235_6,66 +CPA_D352_3,CPA_C23OTHER,184 +CPA_D352_3,CPA_C241_3,49 +CPA_D352_3,CPA_C244_5,91 +CPA_D352_3,CPA_C25,236 +CPA_D352_3,CPA_C26,75 +CPA_D352_3,CPA_C27,39 +CPA_D352_3,CPA_C28,198 +CPA_D352_3,CPA_C29,148 +CPA_D352_3,CPA_C301,11 +CPA_D352_3,CPA_C303,57 +CPA_D352_3,CPA_C30OTHER,6 +CPA_D352_3,CPA_C31,43 +CPA_D352_3,CPA_C32,26 +CPA_D352_3,CPA_C3316,16 +CPA_D352_3,CPA_C33OTHER,172 +CPA_D352_3,CPA_D351,22782 +CPA_D352_3,CPA_D352_3,20272 +CPA_D352_3,CPA_E36,26 +CPA_D352_3,CPA_E37,2 +CPA_D352_3,CPA_E38,37 +CPA_D352_3,CPA_E39,2 +CPA_D352_3,"CPA_F41, F42 & F43",737 +CPA_D352_3,CPA_G45,128 +CPA_D352_3,CPA_G46,176 +CPA_D352_3,CPA_G47,619 +CPA_D352_3,CPA_H491_2,8 +CPA_D352_3,CPA_H493_5,39 +CPA_D352_3,CPA_H50,3 +CPA_D352_3,CPA_H51,30 +CPA_D352_3,CPA_H52,116 +CPA_D352_3,CPA_H53,45 +CPA_D352_3,CPA_I55,290 +CPA_D352_3,CPA_I56,659 +CPA_D352_3,CPA_J58,7 +CPA_D352_3,CPA_J59 & J60,59 +CPA_D352_3,CPA_J61,29 +CPA_D352_3,CPA_J62,68 +CPA_D352_3,CPA_J63,22 +CPA_D352_3,CPA_K64,107 +CPA_D352_3,CPA_K65.1-2 & K65.3,7 +CPA_D352_3,CPA_K66,50 +CPA_D352_3,CPA_L68BXL683,206 +CPA_D352_3,CPA_L683,38 +CPA_D352_3,CPA_M691,67 +CPA_D352_3,CPA_M692,20 +CPA_D352_3,CPA_M70,75 +CPA_D352_3,CPA_M71,73 +CPA_D352_3,CPA_M72,47 +CPA_D352_3,CPA_M73,21 +CPA_D352_3,CPA_M74,41 +CPA_D352_3,CPA_M75,15 +CPA_D352_3,CPA_N77,80 +CPA_D352_3,CPA_N78,17 +CPA_D352_3,CPA_N79,12 +CPA_D352_3,CPA_N80,1 +CPA_D352_3,CPA_N81,131 +CPA_D352_3,CPA_N82,142 +CPA_D352_3,CPA_O84,653 +CPA_D352_3,CPA_P85,845 +CPA_D352_3,CPA_Q86,1133 +CPA_D352_3,CPA_Q87 & Q88,373 +CPA_D352_3,CPA_R90,21 +CPA_D352_3,CPA_R91,40 +CPA_D352_3,CPA_R92,73 +CPA_D352_3,CPA_R93,328 +CPA_D352_3,CPA_S94,186 +CPA_D352_3,CPA_S95,1 +CPA_D352_3,CPA_S96,74 +CPA_E36,CPA_A01,96 +CPA_E36,CPA_A03,4 +CPA_E36,CPA_B05 & B06,7 +CPA_E36,CPA_B07 & B08,11 +CPA_E36,CPA_B09,3 +CPA_E36,CPA_C101,52 +CPA_E36,CPA_C102_3,43 +CPA_E36,CPA_C104,6 +CPA_E36,CPA_C105,21 +CPA_E36,CPA_C106,18 +CPA_E36,CPA_C107,22 +CPA_E36,CPA_C108,47 +CPA_E36,CPA_C109,10 +CPA_E36,CPA_C11.01-6 & C12,48 +CPA_E36,CPA_C1107,35 +CPA_E36,CPA_C13,10 +CPA_E36,CPA_C14,4 +CPA_E36,CPA_C15,2 +CPA_E36,CPA_C16,10 +CPA_E36,CPA_C17,50 +CPA_E36,CPA_C18,8 +CPA_E36,CPA_C19,39 +CPA_E36,CPA_C203,6 +CPA_E36,CPA_C204,15 +CPA_E36,CPA_C205,14 +CPA_E36,CPA_C20A,30 +CPA_E36,CPA_C20B,41 +CPA_E36,CPA_C20C,10 +CPA_E36,CPA_C21,14 +CPA_E36,CPA_C22,28 +CPA_E36,CPA_C235_6,19 +CPA_E36,CPA_C23OTHER,17 +CPA_E36,CPA_C241_3,13 +CPA_E36,CPA_C244_5,8 +CPA_E36,CPA_C25,47 +CPA_E36,CPA_C26,18 +CPA_E36,CPA_C27,10 +CPA_E36,CPA_C28,24 +CPA_E36,CPA_C29,23 +CPA_E36,CPA_C301,4 +CPA_E36,CPA_C303,18 +CPA_E36,CPA_C30OTHER,1 +CPA_E36,CPA_C31,11 +CPA_E36,CPA_C32,37 +CPA_E36,CPA_C3315,1 +CPA_E36,CPA_C3316,6 +CPA_E36,CPA_C33OTHER,5 +CPA_E36,CPA_D351,116 +CPA_E36,CPA_D352_3,4 +CPA_E36,CPA_E36,1218 +CPA_E36,CPA_E37,202 +CPA_E36,CPA_E38,230 +CPA_E36,CPA_E39,1 +CPA_E36,"CPA_F41, F42 & F43",272 +CPA_E36,CPA_G45,142 +CPA_E36,CPA_G46,157 +CPA_E36,CPA_G47,370 +CPA_E36,CPA_H491_2,10 +CPA_E36,CPA_H493_5,56 +CPA_E36,CPA_H50,6 +CPA_E36,CPA_H51,6 +CPA_E36,CPA_H52,91 +CPA_E36,CPA_H53,10 +CPA_E36,CPA_I55,388 +CPA_E36,CPA_I56,394 +CPA_E36,CPA_J58,3 +CPA_E36,CPA_J59 & J60,32 +CPA_E36,CPA_J61,17 +CPA_E36,CPA_J62,31 +CPA_E36,CPA_J63,3 +CPA_E36,CPA_K64,8 +CPA_E36,CPA_K65.1-2 & K65.3,118 +CPA_E36,CPA_L68BXL683,92 +CPA_E36,CPA_L683,47 +CPA_E36,CPA_M691,45 +CPA_E36,CPA_M692,20 +CPA_E36,CPA_M70,52 +CPA_E36,CPA_M71,60 +CPA_E36,CPA_M72,7 +CPA_E36,CPA_M73,36 +CPA_E36,CPA_M74,9 +CPA_E36,CPA_M75,12 +CPA_E36,CPA_N77,37 +CPA_E36,CPA_N78,16 +CPA_E36,CPA_N79,8 +CPA_E36,CPA_N80,4 +CPA_E36,CPA_N81,71 +CPA_E36,CPA_N82,77 +CPA_E36,CPA_O84,459 +CPA_E36,CPA_P85,279 +CPA_E36,CPA_Q86,264 +CPA_E36,CPA_Q87 & Q88,320 +CPA_E36,CPA_R90,20 +CPA_E36,CPA_R91,28 +CPA_E36,CPA_R92,18 +CPA_E36,CPA_R93,150 +CPA_E36,CPA_S94,36 +CPA_E36,CPA_S95,12 +CPA_E36,CPA_S96,86 +CPA_E37,CPA_A01,7 +CPA_E37,CPA_A03,2 +CPA_E37,CPA_B05 & B06,2 +CPA_E37,CPA_B09,6 +CPA_E37,CPA_C101,27 +CPA_E37,CPA_C102_3,8 +CPA_E37,CPA_C104,2 +CPA_E37,CPA_C105,17 +CPA_E37,CPA_C106,3 +CPA_E37,CPA_C107,8 +CPA_E37,CPA_C108,27 +CPA_E37,CPA_C109,2 +CPA_E37,CPA_C11.01-6 & C12,38 +CPA_E37,CPA_C1107,6 +CPA_E37,CPA_C13,7 +CPA_E37,CPA_C15,2 +CPA_E37,CPA_C16,2 +CPA_E37,CPA_C17,18 +CPA_E37,CPA_C18,2 +CPA_E37,CPA_C19,1 +CPA_E37,CPA_C203,1 +CPA_E37,CPA_C205,8 +CPA_E37,CPA_C20A,1 +CPA_E37,CPA_C20B,27 +CPA_E37,CPA_C20C,30 +CPA_E37,CPA_C21,20 +CPA_E37,CPA_C22,8 +CPA_E37,CPA_C235_6,1 +CPA_E37,CPA_C23OTHER,1 +CPA_E37,CPA_C241_3,1 +CPA_E37,CPA_C244_5,3 +CPA_E37,CPA_C25,28 +CPA_E37,CPA_C26,3 +CPA_E37,CPA_C28,14 +CPA_E37,CPA_C29,2 +CPA_E37,CPA_C301,4 +CPA_E37,CPA_C303,16 +CPA_E37,CPA_C31,4 +CPA_E37,CPA_C32,5 +CPA_E37,CPA_C3315,1 +CPA_E37,CPA_C33OTHER,1 +CPA_E37,CPA_D351,2 +CPA_E37,CPA_E36,93 +CPA_E37,CPA_E37,522 +CPA_E37,CPA_E38,2294 +CPA_E37,CPA_E39,2 +CPA_E37,"CPA_F41, F42 & F43",232 +CPA_E37,CPA_G45,26 +CPA_E37,CPA_G46,83 +CPA_E37,CPA_G47,124 +CPA_E37,CPA_H493_5,15 +CPA_E37,CPA_H51,4 +CPA_E37,CPA_H52,19 +CPA_E37,CPA_H53,7 +CPA_E37,CPA_I55,82 +CPA_E37,CPA_I56,29 +CPA_E37,CPA_J58,1 +CPA_E37,CPA_J59 & J60,6 +CPA_E37,CPA_J61,1 +CPA_E37,CPA_J62,8 +CPA_E37,CPA_J63,5 +CPA_E37,CPA_K64,11 +CPA_E37,CPA_K65.1-2 & K65.3,7 +CPA_E37,CPA_K66,20 +CPA_E37,CPA_L68BXL683,31 +CPA_E37,CPA_L68A,6 +CPA_E37,CPA_L683,2 +CPA_E37,CPA_M691,6 +CPA_E37,CPA_M692,1 +CPA_E37,CPA_M70,3 +CPA_E37,CPA_M71,35 +CPA_E37,CPA_M73,1 +CPA_E37,CPA_M74,19 +CPA_E37,CPA_N77,22 +CPA_E37,CPA_N78,1 +CPA_E37,CPA_N79,1 +CPA_E37,CPA_N81,77 +CPA_E37,CPA_N82,26 +CPA_E37,CPA_O84,1041 +CPA_E37,CPA_P85,70 +CPA_E37,CPA_Q86,626 +CPA_E37,CPA_Q87 & Q88,34 +CPA_E37,CPA_R90,4 +CPA_E37,CPA_R91,6 +CPA_E37,CPA_R92,14 +CPA_E37,CPA_R93,24 +CPA_E37,CPA_S94,4 +CPA_E37,CPA_S95,1 +CPA_E37,CPA_S96,34 +CPA_E38,CPA_A01,210 +CPA_E38,CPA_A02,2 +CPA_E38,CPA_A03,18 +CPA_E38,CPA_B05 & B06,23 +CPA_E38,CPA_B07 & B08,28 +CPA_E38,CPA_B09,2 +CPA_E38,CPA_C101,83 +CPA_E38,CPA_C102_3,39 +CPA_E38,CPA_C104,2 +CPA_E38,CPA_C105,43 +CPA_E38,CPA_C106,9 +CPA_E38,CPA_C107,31 +CPA_E38,CPA_C108,63 +CPA_E38,CPA_C109,17 +CPA_E38,CPA_C11.01-6 & C12,176 +CPA_E38,CPA_C1107,26 +CPA_E38,CPA_C13,22 +CPA_E38,CPA_C14,4 +CPA_E38,CPA_C15,3 +CPA_E38,CPA_C16,35 +CPA_E38,CPA_C17,119 +CPA_E38,CPA_C18,16 +CPA_E38,CPA_C19,83 +CPA_E38,CPA_C203,19 +CPA_E38,CPA_C204,23 +CPA_E38,CPA_C205,29 +CPA_E38,CPA_C20A,21 +CPA_E38,CPA_C20B,51 +CPA_E38,CPA_C20C,29 +CPA_E38,CPA_C21,43 +CPA_E38,CPA_C22,117 +CPA_E38,CPA_C235_6,24 +CPA_E38,CPA_C23OTHER,34 +CPA_E38,CPA_C241_3,453 +CPA_E38,CPA_C244_5,127 +CPA_E38,CPA_C25,93 +CPA_E38,CPA_C26,14 +CPA_E38,CPA_C27,13 +CPA_E38,CPA_C28,44 +CPA_E38,CPA_C29,174 +CPA_E38,CPA_C301,30 +CPA_E38,CPA_C303,19 +CPA_E38,CPA_C30OTHER,5 +CPA_E38,CPA_C31,19 +CPA_E38,CPA_C32,31 +CPA_E38,CPA_C3315,2 +CPA_E38,CPA_C3316,7 +CPA_E38,CPA_C33OTHER,26 +CPA_E38,CPA_D351,547 +CPA_E38,CPA_E36,141 +CPA_E38,CPA_E37,137 +CPA_E38,CPA_E38,7324 +CPA_E38,CPA_E39,13 +CPA_E38,"CPA_F41, F42 & F43",1176 +CPA_E38,CPA_G45,248 +CPA_E38,CPA_G46,582 +CPA_E38,CPA_G47,621 +CPA_E38,CPA_H491_2,11 +CPA_E38,CPA_H493_5,311 +CPA_E38,CPA_H50,23 +CPA_E38,CPA_H51,3 +CPA_E38,CPA_H52,203 +CPA_E38,CPA_H53,27 +CPA_E38,CPA_I55,167 +CPA_E38,CPA_I56,562 +CPA_E38,CPA_J58,3 +CPA_E38,CPA_J59 & J60,31 +CPA_E38,CPA_J61,10 +CPA_E38,CPA_J62,29 +CPA_E38,CPA_J63,3 +CPA_E38,CPA_K64,78 +CPA_E38,CPA_K65.1-2 & K65.3,9 +CPA_E38,CPA_K66,128 +CPA_E38,CPA_L68BXL683,71 +CPA_E38,CPA_L68A,64 +CPA_E38,CPA_L683,38 +CPA_E38,CPA_M691,21 +CPA_E38,CPA_M692,22 +CPA_E38,CPA_M70,58 +CPA_E38,CPA_M71,46 +CPA_E38,CPA_M72,18 +CPA_E38,CPA_M73,11 +CPA_E38,CPA_M74,5 +CPA_E38,CPA_M75,27 +CPA_E38,CPA_N77,67 +CPA_E38,CPA_N78,12 +CPA_E38,CPA_N79,15 +CPA_E38,CPA_N80,11 +CPA_E38,CPA_N81,275 +CPA_E38,CPA_N82,96 +CPA_E38,CPA_O84,1559 +CPA_E38,CPA_P85,210 +CPA_E38,CPA_Q86,1350 +CPA_E38,CPA_Q87 & Q88,238 +CPA_E38,CPA_R90,20 +CPA_E38,CPA_R91,20 +CPA_E38,CPA_R92,80 +CPA_E38,CPA_R93,141 +CPA_E38,CPA_S94,23 +CPA_E38,CPA_S95,14 +CPA_E38,CPA_S96,54 +CPA_E39,CPA_E38,691 +CPA_E39,CPA_E39,172 +CPA_E39,CPA_J59 & J60,6 +CPA_E39,CPA_L68BXL683,12 +CPA_E39,CPA_O84,738 +CPA_E39,CPA_P85,54 +CPA_E39,CPA_R93,4 +"CPA_F41, F42 & F43",CPA_A01,249 +"CPA_F41, F42 & F43",CPA_A02,9 +"CPA_F41, F42 & F43",CPA_A03,4 +"CPA_F41, F42 & F43",CPA_B05 & B06,229 +"CPA_F41, F42 & F43",CPA_B07 & B08,7 +"CPA_F41, F42 & F43",CPA_B09,180 +"CPA_F41, F42 & F43",CPA_C101,78 +"CPA_F41, F42 & F43",CPA_C102_3,26 +"CPA_F41, F42 & F43",CPA_C14,2 +"CPA_F41, F42 & F43",CPA_C16,12 +"CPA_F41, F42 & F43",CPA_C17,1 +"CPA_F41, F42 & F43",CPA_C18,3 +"CPA_F41, F42 & F43",CPA_C19,297 +"CPA_F41, F42 & F43",CPA_C203,4 +"CPA_F41, F42 & F43",CPA_C20A,41 +"CPA_F41, F42 & F43",CPA_C20B,29 +"CPA_F41, F42 & F43",CPA_C20C,1 +"CPA_F41, F42 & F43",CPA_C22,156 +"CPA_F41, F42 & F43",CPA_C235_6,13 +"CPA_F41, F42 & F43",CPA_C23OTHER,2 +"CPA_F41, F42 & F43",CPA_C25,859 +"CPA_F41, F42 & F43",CPA_C28,113 +"CPA_F41, F42 & F43",CPA_C29,138 +"CPA_F41, F42 & F43",CPA_C301,111 +"CPA_F41, F42 & F43",CPA_C303,33 +"CPA_F41, F42 & F43",CPA_C30OTHER,5 +"CPA_F41, F42 & F43",CPA_C31,3 +"CPA_F41, F42 & F43",CPA_C32,2 +"CPA_F41, F42 & F43",CPA_C3315,1 +"CPA_F41, F42 & F43",CPA_C33OTHER,462 +"CPA_F41, F42 & F43",CPA_D351,2996 +"CPA_F41, F42 & F43",CPA_D352_3,1990 +"CPA_F41, F42 & F43",CPA_E36,323 +"CPA_F41, F42 & F43",CPA_E37,261 +"CPA_F41, F42 & F43",CPA_E38,334 +"CPA_F41, F42 & F43","CPA_F41, F42 & F43",127211 +"CPA_F41, F42 & F43",CPA_G45,111 +"CPA_F41, F42 & F43",CPA_G46,3237 +"CPA_F41, F42 & F43",CPA_G47,2153 +"CPA_F41, F42 & F43",CPA_H491_2,17 +"CPA_F41, F42 & F43",CPA_H493_5,14 +"CPA_F41, F42 & F43",CPA_H52,461 +"CPA_F41, F42 & F43",CPA_H53,28 +"CPA_F41, F42 & F43",CPA_I55,36 +"CPA_F41, F42 & F43",CPA_I56,87 +"CPA_F41, F42 & F43",CPA_J58,2 +"CPA_F41, F42 & F43",CPA_J59 & J60,14 +"CPA_F41, F42 & F43",CPA_J61,175 +"CPA_F41, F42 & F43",CPA_J62,10 +"CPA_F41, F42 & F43",CPA_J63,46 +"CPA_F41, F42 & F43",CPA_K64,1686 +"CPA_F41, F42 & F43",CPA_K65.1-2 & K65.3,1197 +"CPA_F41, F42 & F43",CPA_K66,181 +"CPA_F41, F42 & F43",CPA_L68BXL683,11726 +"CPA_F41, F42 & F43",CPA_L68A,11088 +"CPA_F41, F42 & F43",CPA_L683,398 +"CPA_F41, F42 & F43",CPA_M691,2 +"CPA_F41, F42 & F43",CPA_M692,1 +"CPA_F41, F42 & F43",CPA_M70,1447 +"CPA_F41, F42 & F43",CPA_M71,703 +"CPA_F41, F42 & F43",CPA_M74,246 +"CPA_F41, F42 & F43",CPA_M75,1 +"CPA_F41, F42 & F43",CPA_N77,192 +"CPA_F41, F42 & F43",CPA_N78,21 +"CPA_F41, F42 & F43",CPA_N79,115 +"CPA_F41, F42 & F43",CPA_N81,535 +"CPA_F41, F42 & F43",CPA_N82,268 +"CPA_F41, F42 & F43",CPA_O84,8080 +"CPA_F41, F42 & F43",CPA_P85,698 +"CPA_F41, F42 & F43",CPA_Q86,1392 +"CPA_F41, F42 & F43",CPA_Q87 & Q88,454 +"CPA_F41, F42 & F43",CPA_R90,67 +"CPA_F41, F42 & F43",CPA_R91,100 +"CPA_F41, F42 & F43",CPA_R93,141 +"CPA_F41, F42 & F43",CPA_S94,16 +"CPA_F41, F42 & F43",CPA_S96,6 +CPA_G45,CPA_A01,516 +CPA_G45,CPA_A02,33 +CPA_G45,CPA_B09,1 +CPA_G45,CPA_E36,42 +CPA_G45,CPA_E37,8 +CPA_G45,CPA_E38,274 +CPA_G45,"CPA_F41, F42 & F43",295 +CPA_G45,CPA_G45,2073 +CPA_G45,CPA_G46,1127 +CPA_G45,CPA_G47,957 +CPA_G45,CPA_H491_2,22 +CPA_G45,CPA_H493_5,1242 +CPA_G45,CPA_H50,6 +CPA_G45,CPA_H51,4 +CPA_G45,CPA_H52,34 +CPA_G45,CPA_H53,411 +CPA_G45,CPA_I55,20 +CPA_G45,CPA_I56,61 +CPA_G45,CPA_J58,2 +CPA_G45,CPA_J59 & J60,12 +CPA_G45,CPA_J62,92 +CPA_G45,CPA_J63,18 +CPA_G45,CPA_K64,503 +CPA_G45,CPA_K65.1-2 & K65.3,242 +CPA_G45,CPA_K66,79 +CPA_G45,CPA_M691,27 +CPA_G45,CPA_M692,30 +CPA_G45,CPA_M72,5 +CPA_G45,CPA_N77,2206 +CPA_G45,CPA_N78,107 +CPA_G45,CPA_O84,374 +CPA_G45,CPA_P85,247 +CPA_G45,CPA_Q86,248 +CPA_G45,CPA_Q87 & Q88,220 +CPA_G45,CPA_R93,12 +CPA_G45,CPA_S95,13 +CPA_G45,CPA_S96,110 +CPA_H491_2,CPA_A02,2 +CPA_H491_2,CPA_B05 & B06,15 +CPA_H491_2,CPA_B07 & B08,57 +CPA_H491_2,CPA_B09,2 +CPA_H491_2,CPA_C101,3 +CPA_H491_2,CPA_C104,1 +CPA_H491_2,CPA_C105,1 +CPA_H491_2,CPA_C11.01-6 & C12,15 +CPA_H491_2,CPA_C13,3 +CPA_H491_2,CPA_C204,1 +CPA_H491_2,CPA_C21,1 +CPA_H491_2,CPA_C235_6,2 +CPA_H491_2,CPA_C23OTHER,5 +CPA_H491_2,CPA_C241_3,25 +CPA_H491_2,CPA_C25,16 +CPA_H491_2,CPA_C26,10 +CPA_H491_2,CPA_C27,1 +CPA_H491_2,CPA_C29,5 +CPA_H491_2,CPA_C303,1 +CPA_H491_2,CPA_C30OTHER,2 +CPA_H491_2,CPA_C31,3 +CPA_H491_2,CPA_C32,1 +CPA_H491_2,CPA_C33OTHER,3 +CPA_H491_2,CPA_E38,2 +CPA_H491_2,"CPA_F41, F42 & F43",11 +CPA_H491_2,CPA_H491_2,2316 +CPA_H491_2,CPA_H51,73 +CPA_H491_2,CPA_H52,6 +CPA_H491_2,CPA_K64,23 +CPA_H491_2,CPA_K65.1-2 & K65.3,10 +CPA_H491_2,CPA_K66,13 +CPA_H491_2,CPA_L68BXL683,9 +CPA_H491_2,CPA_M72,1 +CPA_H491_2,CPA_N77,2 +CPA_H491_2,CPA_N79,82 +CPA_H491_2,CPA_O84,1003 +CPA_H491_2,CPA_P85,207 +CPA_H491_2,CPA_Q86,481 +CPA_H491_2,CPA_Q87 & Q88,1 +CPA_H491_2,CPA_R91,14 +CPA_H491_2,CPA_R93,35 +CPA_H491_2,CPA_S95,1 +CPA_H493_5,CPA_A01,366 +CPA_H493_5,CPA_A02,13 +CPA_H493_5,CPA_B05 & B06,103 +CPA_H493_5,CPA_B07 & B08,858 +CPA_H493_5,CPA_B09,51 +CPA_H493_5,CPA_C101,529 +CPA_H493_5,CPA_C102_3,399 +CPA_H493_5,CPA_C104,21 +CPA_H493_5,CPA_C105,225 +CPA_H493_5,CPA_C106,148 +CPA_H493_5,CPA_C107,371 +CPA_H493_5,CPA_C108,605 +CPA_H493_5,CPA_C109,171 +CPA_H493_5,CPA_C11.01-6 & C12,562 +CPA_H493_5,CPA_C1107,277 +CPA_H493_5,CPA_C13,144 +CPA_H493_5,CPA_C14,23 +CPA_H493_5,CPA_C15,26 +CPA_H493_5,CPA_C16,307 +CPA_H493_5,CPA_C17,511 +CPA_H493_5,CPA_C18,208 +CPA_H493_5,CPA_C19,107 +CPA_H493_5,CPA_C203,192 +CPA_H493_5,CPA_C204,119 +CPA_H493_5,CPA_C205,90 +CPA_H493_5,CPA_C20A,234 +CPA_H493_5,CPA_C20B,71 +CPA_H493_5,CPA_C20C,37 +CPA_H493_5,CPA_C21,141 +CPA_H493_5,CPA_C22,719 +CPA_H493_5,CPA_C235_6,635 +CPA_H493_5,CPA_C23OTHER,129 +CPA_H493_5,CPA_C241_3,209 +CPA_H493_5,CPA_C244_5,78 +CPA_H493_5,CPA_C25,504 +CPA_H493_5,CPA_C26,146 +CPA_H493_5,CPA_C27,223 +CPA_H493_5,CPA_C28,561 +CPA_H493_5,CPA_C29,559 +CPA_H493_5,CPA_C301,8 +CPA_H493_5,CPA_C303,241 +CPA_H493_5,CPA_C30OTHER,35 +CPA_H493_5,CPA_C31,196 +CPA_H493_5,CPA_C32,287 +CPA_H493_5,CPA_C3315,1 +CPA_H493_5,CPA_C3316,56 +CPA_H493_5,CPA_C33OTHER,205 +CPA_H493_5,CPA_D351,26 +CPA_H493_5,CPA_D352_3,5 +CPA_H493_5,CPA_E36,80 +CPA_H493_5,CPA_E37,25 +CPA_H493_5,CPA_E38,561 +CPA_H493_5,CPA_E39,1 +CPA_H493_5,"CPA_F41, F42 & F43",1905 +CPA_H493_5,CPA_G45,1363 +CPA_H493_5,CPA_G46,10079 +CPA_H493_5,CPA_G47,8872 +CPA_H493_5,CPA_H491_2,227 +CPA_H493_5,CPA_H493_5,8548 +CPA_H493_5,CPA_H50,40 +CPA_H493_5,CPA_H51,151 +CPA_H493_5,CPA_H52,2686 +CPA_H493_5,CPA_H53,735 +CPA_H493_5,CPA_I55,75 +CPA_H493_5,CPA_I56,366 +CPA_H493_5,CPA_J58,179 +CPA_H493_5,CPA_J59 & J60,177 +CPA_H493_5,CPA_J61,52 +CPA_H493_5,CPA_J62,352 +CPA_H493_5,CPA_J63,30 +CPA_H493_5,CPA_K64,722 +CPA_H493_5,CPA_K65.1-2 & K65.3,168 +CPA_H493_5,CPA_K66,195 +CPA_H493_5,CPA_L68BXL683,176 +CPA_H493_5,CPA_L683,37 +CPA_H493_5,CPA_M691,104 +CPA_H493_5,CPA_M692,18 +CPA_H493_5,CPA_M70,231 +CPA_H493_5,CPA_M71,307 +CPA_H493_5,CPA_M72,103 +CPA_H493_5,CPA_M73,28 +CPA_H493_5,CPA_M74,72 +CPA_H493_5,CPA_M75,7 +CPA_H493_5,CPA_N77,553 +CPA_H493_5,CPA_N78,132 +CPA_H493_5,CPA_N79,155 +CPA_H493_5,CPA_N80,18 +CPA_H493_5,CPA_N81,232 +CPA_H493_5,CPA_N82,486 +CPA_H493_5,CPA_O84,1001 +CPA_H493_5,CPA_P85,1736 +CPA_H493_5,CPA_Q86,2612 +CPA_H493_5,CPA_Q87 & Q88,1016 +CPA_H493_5,CPA_R90,58 +CPA_H493_5,CPA_R91,8 +CPA_H493_5,CPA_R92,18 +CPA_H493_5,CPA_R93,142 +CPA_H493_5,CPA_S94,19 +CPA_H493_5,CPA_S95,73 +CPA_H493_5,CPA_S96,102 +CPA_H50,CPA_A03,48 +CPA_H50,CPA_B05 & B06,296 +CPA_H50,CPA_B07 & B08,58 +CPA_H50,CPA_C101,3 +CPA_H50,CPA_C105,1 +CPA_H50,CPA_C106,3 +CPA_H50,CPA_C108,1 +CPA_H50,CPA_C11.01-6 & C12,8 +CPA_H50,CPA_C18,2 +CPA_H50,CPA_C19,157 +CPA_H50,CPA_C204,1 +CPA_H50,CPA_C20B,2 +CPA_H50,CPA_C22,2 +CPA_H50,CPA_C235_6,1 +CPA_H50,CPA_C23OTHER,10 +CPA_H50,CPA_C241_3,10 +CPA_H50,CPA_C25,26 +CPA_H50,CPA_C26,5 +CPA_H50,CPA_C27,1 +CPA_H50,CPA_C29,18 +CPA_H50,CPA_C303,1 +CPA_H50,CPA_C30OTHER,19 +CPA_H50,CPA_C33OTHER,1 +CPA_H50,CPA_D351,2 +CPA_H50,"CPA_F41, F42 & F43",8 +CPA_H50,CPA_H50,2278 +CPA_H50,CPA_H52,2368 +CPA_H50,CPA_K64,66 +CPA_H50,CPA_K65.1-2 & K65.3,13 +CPA_H50,CPA_K66,56 +CPA_H50,CPA_N79,839 +CPA_H50,CPA_O84,38 +CPA_H50,CPA_Q86,28 +CPA_H51,CPA_B05 & B06,218 +CPA_H51,CPA_B07 & B08,3 +CPA_H51,CPA_C108,3 +CPA_H51,CPA_C11.01-6 & C12,7 +CPA_H51,CPA_C13,6 +CPA_H51,CPA_C17,2 +CPA_H51,CPA_C21,1 +CPA_H51,CPA_C22,1 +CPA_H51,CPA_C241_3,24 +CPA_H51,CPA_C25,7 +CPA_H51,CPA_C26,4 +CPA_H51,CPA_C27,3 +CPA_H51,CPA_C29,2 +CPA_H51,CPA_C303,95 +CPA_H51,CPA_C30OTHER,15 +CPA_H51,CPA_C31,11 +CPA_H51,CPA_C32,3 +CPA_H51,CPA_C33OTHER,2 +CPA_H51,CPA_E38,10 +CPA_H51,"CPA_F41, F42 & F43",40 +CPA_H51,CPA_G45,114 +CPA_H51,CPA_H50,420 +CPA_H51,CPA_H51,6009 +CPA_H51,CPA_H52,2660 +CPA_H51,CPA_H53,528 +CPA_H51,CPA_I55,2 +CPA_H51,CPA_I56,140 +CPA_H51,CPA_J59 & J60,27 +CPA_H51,CPA_J61,26 +CPA_H51,CPA_J63,3 +CPA_H51,CPA_K64,1577 +CPA_H51,CPA_K65.1-2 & K65.3,170 +CPA_H51,CPA_K66,189 +CPA_H51,CPA_L68BXL683,6 +CPA_H51,CPA_M692,275 +CPA_H51,CPA_M70,665 +CPA_H51,CPA_M73,288 +CPA_H51,CPA_M74,96 +CPA_H51,CPA_N78,152 +CPA_H51,CPA_N79,4642 +CPA_H51,CPA_N80,16 +CPA_H51,CPA_N82,247 +CPA_H51,CPA_O84,340 +CPA_H51,CPA_Q86,65 +CPA_H51,CPA_R90,14 +CPA_H51,CPA_R93,56 +CPA_H51,CPA_S94,223 +CPA_H51,CPA_S96,1 +CPA_H52,CPA_A03,61 +CPA_H52,CPA_B05 & B06,5 +CPA_H52,CPA_B07 & B08,4 +CPA_H52,CPA_C101,69 +CPA_H52,CPA_C102_3,13 +CPA_H52,CPA_C104,1 +CPA_H52,CPA_C105,11 +CPA_H52,CPA_C106,16 +CPA_H52,CPA_C107,17 +CPA_H52,CPA_C108,25 +CPA_H52,CPA_C11.01-6 & C12,249 +CPA_H52,CPA_C1107,11 +CPA_H52,CPA_C13,23 +CPA_H52,CPA_C14,66 +CPA_H52,CPA_C15,3 +CPA_H52,CPA_C16,2 +CPA_H52,CPA_C17,30 +CPA_H52,CPA_C18,10 +CPA_H52,CPA_C203,19 +CPA_H52,CPA_C204,14 +CPA_H52,CPA_C205,29 +CPA_H52,CPA_C20B,42 +CPA_H52,CPA_C21,573 +CPA_H52,CPA_C22,50 +CPA_H52,CPA_C235_6,2 +CPA_H52,CPA_C23OTHER,20 +CPA_H52,CPA_C244_5,12 +CPA_H52,CPA_C25,64 +CPA_H52,CPA_C26,160 +CPA_H52,CPA_C27,56 +CPA_H52,CPA_C28,863 +CPA_H52,CPA_C29,1168 +CPA_H52,CPA_C303,146 +CPA_H52,CPA_C30OTHER,2 +CPA_H52,CPA_C32,30 +CPA_H52,CPA_C3316,3 +CPA_H52,CPA_C33OTHER,66 +CPA_H52,CPA_E36,34 +CPA_H52,CPA_E37,1 +CPA_H52,CPA_E38,281 +CPA_H52,CPA_E39,6 +CPA_H52,CPA_G45,506 +CPA_H52,CPA_G46,9980 +CPA_H52,CPA_G47,6161 +CPA_H52,CPA_H491_2,3972 +CPA_H52,CPA_H493_5,1057 +CPA_H52,CPA_H50,1816 +CPA_H52,CPA_H51,362 +CPA_H52,CPA_H52,10921 +CPA_H52,CPA_H53,962 +CPA_H52,CPA_I56,140 +CPA_H52,CPA_J59 & J60,34 +CPA_H52,CPA_J61,528 +CPA_H52,CPA_J62,678 +CPA_H52,CPA_K64,1458 +CPA_H52,CPA_K65.1-2 & K65.3,21 +CPA_H52,CPA_K66,403 +CPA_H52,CPA_L68BXL683,2 +CPA_H52,CPA_L683,7 +CPA_H52,CPA_M70,3 +CPA_H52,CPA_M71,82 +CPA_H52,CPA_N77,560 +CPA_H52,CPA_N78,27 +CPA_H52,CPA_N80,3 +CPA_H52,CPA_N81,12 +CPA_H52,CPA_N82,1205 +CPA_H52,CPA_O84,304 +CPA_H52,CPA_P85,33 +CPA_H52,CPA_Q87 & Q88,10 +CPA_H52,CPA_S96,33 +CPA_H53,CPA_A01,125 +CPA_H53,CPA_A02,4 +CPA_H53,CPA_A03,9 +CPA_H53,CPA_B05 & B06,2 +CPA_H53,CPA_B07 & B08,10 +CPA_H53,CPA_B09,8 +CPA_H53,CPA_C101,102 +CPA_H53,CPA_C102_3,129 +CPA_H53,CPA_C104,14 +CPA_H53,CPA_C105,43 +CPA_H53,CPA_C106,26 +CPA_H53,CPA_C107,93 +CPA_H53,CPA_C108,265 +CPA_H53,CPA_C109,63 +CPA_H53,CPA_C11.01-6 & C12,92 +CPA_H53,CPA_C1107,63 +CPA_H53,CPA_C13,86 +CPA_H53,CPA_C14,24 +CPA_H53,CPA_C15,40 +CPA_H53,CPA_C16,96 +CPA_H53,CPA_C17,47 +CPA_H53,CPA_C18,67 +CPA_H53,CPA_C19,2 +CPA_H53,CPA_C203,137 +CPA_H53,CPA_C204,139 +CPA_H53,CPA_C205,46 +CPA_H53,CPA_C20A,10 +CPA_H53,CPA_C20B,72 +CPA_H53,CPA_C20C,14 +CPA_H53,CPA_C21,32 +CPA_H53,CPA_C22,161 +CPA_H53,CPA_C235_6,38 +CPA_H53,CPA_C23OTHER,147 +CPA_H53,CPA_C241_3,11 +CPA_H53,CPA_C244_5,47 +CPA_H53,CPA_C25,106 +CPA_H53,CPA_C26,439 +CPA_H53,CPA_C27,99 +CPA_H53,CPA_C28,160 +CPA_H53,CPA_C29,143 +CPA_H53,CPA_C301,36 +CPA_H53,CPA_C303,22 +CPA_H53,CPA_C30OTHER,3 +CPA_H53,CPA_C31,135 +CPA_H53,CPA_C32,179 +CPA_H53,CPA_C3315,2 +CPA_H53,CPA_C3316,4 +CPA_H53,CPA_C33OTHER,173 +CPA_H53,CPA_D351,75 +CPA_H53,CPA_D352_3,26 +CPA_H53,CPA_E36,13 +CPA_H53,CPA_E37,1 +CPA_H53,CPA_E38,21 +CPA_H53,CPA_E39,5 +CPA_H53,"CPA_F41, F42 & F43",63 +CPA_H53,CPA_G45,272 +CPA_H53,CPA_G46,2313 +CPA_H53,CPA_G47,2283 +CPA_H53,CPA_H491_2,7 +CPA_H53,CPA_H493_5,187 +CPA_H53,CPA_H50,8 +CPA_H53,CPA_H51,8 +CPA_H53,CPA_H52,297 +CPA_H53,CPA_H53,4706 +CPA_H53,CPA_I55,13 +CPA_H53,CPA_I56,74 +CPA_H53,CPA_J58,294 +CPA_H53,CPA_J59 & J60,109 +CPA_H53,CPA_J61,174 +CPA_H53,CPA_J62,203 +CPA_H53,CPA_J63,311 +CPA_H53,CPA_K64,1679 +CPA_H53,CPA_K65.1-2 & K65.3,440 +CPA_H53,CPA_K66,1216 +CPA_H53,CPA_L68BXL683,106 +CPA_H53,CPA_L683,35 +CPA_H53,CPA_M691,133 +CPA_H53,CPA_M692,100 +CPA_H53,CPA_M70,264 +CPA_H53,CPA_M71,71 +CPA_H53,CPA_M72,65 +CPA_H53,CPA_M73,144 +CPA_H53,CPA_M74,293 +CPA_H53,CPA_M75,37 +CPA_H53,CPA_N77,137 +CPA_H53,CPA_N78,48 +CPA_H53,CPA_N79,126 +CPA_H53,CPA_N80,4 +CPA_H53,CPA_N81,15 +CPA_H53,CPA_N82,847 +CPA_H53,CPA_O84,1255 +CPA_H53,CPA_P85,225 +CPA_H53,CPA_Q86,582 +CPA_H53,CPA_Q87 & Q88,234 +CPA_H53,CPA_R90,118 +CPA_H53,CPA_R91,13 +CPA_H53,CPA_R92,9 +CPA_H53,CPA_R93,140 +CPA_H53,CPA_S94,241 +CPA_H53,CPA_S95,66 +CPA_H53,CPA_S96,23 +CPA_I55,"CPA_F41, F42 & F43",42 +CPA_I55,CPA_G47,298 +CPA_I55,CPA_H491_2,2 +CPA_I55,CPA_H493_5,9 +CPA_I55,CPA_H51,1007 +CPA_I55,CPA_H52,44 +CPA_I55,CPA_H53,4 +CPA_I55,CPA_I55,837 +CPA_I55,CPA_I56,5 +CPA_I55,CPA_J59 & J60,82 +CPA_I55,CPA_J62,377 +CPA_I55,CPA_K64,919 +CPA_I55,CPA_K65.1-2 & K65.3,678 +CPA_I55,CPA_K66,418 +CPA_I55,CPA_L68BXL683,45 +CPA_I55,CPA_M691,220 +CPA_I55,CPA_M692,223 +CPA_I55,CPA_M70,710 +CPA_I55,CPA_M73,173 +CPA_I55,CPA_M74,190 +CPA_I55,CPA_N78,177 +CPA_I55,CPA_N79,4192 +CPA_I55,CPA_N82,291 +CPA_I55,CPA_O84,1096 +CPA_I55,CPA_P85,117 +CPA_I55,CPA_Q86,281 +CPA_I55,CPA_Q87 & Q88,480 +CPA_I55,CPA_R90,20 +CPA_I55,CPA_R93,12 +CPA_I56,CPA_A01,7 +CPA_I56,CPA_A02,4 +CPA_I56,CPA_A03,2 +CPA_I56,CPA_B05 & B06,74 +CPA_I56,CPA_B07 & B08,6 +CPA_I56,CPA_B09,45 +CPA_I56,CPA_C101,117 +CPA_I56,CPA_C102_3,50 +CPA_I56,CPA_C104,9 +CPA_I56,CPA_C105,60 +CPA_I56,CPA_C106,38 +CPA_I56,CPA_C107,37 +CPA_I56,CPA_C108,163 +CPA_I56,CPA_C109,8 +CPA_I56,CPA_C11.01-6 & C12,14 +CPA_I56,CPA_C1107,15 +CPA_I56,CPA_C13,2 +CPA_I56,CPA_C14,10 +CPA_I56,CPA_C15,2 +CPA_I56,CPA_C16,26 +CPA_I56,CPA_C17,14 +CPA_I56,CPA_C19,4 +CPA_I56,CPA_C203,5 +CPA_I56,CPA_C204,20 +CPA_I56,CPA_C205,6 +CPA_I56,CPA_C20A,3 +CPA_I56,CPA_C20B,13 +CPA_I56,CPA_C20C,6 +CPA_I56,CPA_C21,34 +CPA_I56,CPA_C22,33 +CPA_I56,CPA_C235_6,10 +CPA_I56,CPA_C23OTHER,7 +CPA_I56,CPA_C241_3,15 +CPA_I56,CPA_C244_5,4 +CPA_I56,CPA_C25,12 +CPA_I56,CPA_C26,53 +CPA_I56,CPA_C27,15 +CPA_I56,CPA_C28,47 +CPA_I56,CPA_C29,36 +CPA_I56,CPA_C301,20 +CPA_I56,CPA_C303,16 +CPA_I56,CPA_C30OTHER,1 +CPA_I56,CPA_C31,3 +CPA_I56,CPA_C32,15 +CPA_I56,CPA_C3316,1 +CPA_I56,CPA_C33OTHER,6 +CPA_I56,CPA_D351,12 +CPA_I56,CPA_D352_3,54 +CPA_I56,CPA_E36,5 +CPA_I56,CPA_E38,6 +CPA_I56,"CPA_F41, F42 & F43",46 +CPA_I56,CPA_G45,37 +CPA_I56,CPA_G46,197 +CPA_I56,CPA_G47,246 +CPA_I56,CPA_H491_2,53 +CPA_I56,CPA_H493_5,37 +CPA_I56,CPA_H50,54 +CPA_I56,CPA_H51,581 +CPA_I56,CPA_H52,128 +CPA_I56,CPA_H53,15 +CPA_I56,CPA_I55,209 +CPA_I56,CPA_I56,1326 +CPA_I56,CPA_J58,92 +CPA_I56,CPA_J59 & J60,322 +CPA_I56,CPA_J61,44 +CPA_I56,CPA_J62,598 +CPA_I56,CPA_J63,66 +CPA_I56,CPA_K64,639 +CPA_I56,CPA_K65.1-2 & K65.3,158 +CPA_I56,CPA_K66,87 +CPA_I56,CPA_L68BXL683,82 +CPA_I56,CPA_L683,92 +CPA_I56,CPA_M691,191 +CPA_I56,CPA_M692,66 +CPA_I56,CPA_M70,311 +CPA_I56,CPA_M71,125 +CPA_I56,CPA_M72,36 +CPA_I56,CPA_M73,144 +CPA_I56,CPA_M74,274 +CPA_I56,CPA_N77,29 +CPA_I56,CPA_N78,133 +CPA_I56,CPA_N79,160 +CPA_I56,CPA_N80,26 +CPA_I56,CPA_N81,93 +CPA_I56,CPA_N82,255 +CPA_I56,CPA_O84,1153 +CPA_I56,CPA_P85,1512 +CPA_I56,CPA_Q86,1749 +CPA_I56,CPA_Q87 & Q88,878 +CPA_I56,CPA_R90,178 +CPA_I56,CPA_R91,80 +CPA_I56,CPA_R92,40 +CPA_I56,CPA_R93,496 +CPA_I56,CPA_S94,303 +CPA_I56,CPA_S95,36 +CPA_I56,CPA_S96,26 +CPA_J58,CPA_A01,4 +CPA_J58,CPA_C101,12 +CPA_J58,CPA_C102_3,3 +CPA_J58,CPA_C104,1 +CPA_J58,CPA_C105,6 +CPA_J58,CPA_C106,1 +CPA_J58,CPA_C107,4 +CPA_J58,CPA_C108,14 +CPA_J58,CPA_C109,7 +CPA_J58,CPA_C11.01-6 & C12,29 +CPA_J58,CPA_C13,2 +CPA_J58,CPA_C14,21 +CPA_J58,CPA_C15,1 +CPA_J58,CPA_C17,5 +CPA_J58,CPA_C18,4 +CPA_J58,CPA_C203,1 +CPA_J58,CPA_C204,13 +CPA_J58,CPA_C205,5 +CPA_J58,CPA_C20B,4 +CPA_J58,CPA_C21,66 +CPA_J58,CPA_C241_3,18 +CPA_J58,CPA_C244_5,15 +CPA_J58,CPA_C25,10 +CPA_J58,CPA_C27,55 +CPA_J58,CPA_C28,3 +CPA_J58,CPA_C29,19 +CPA_J58,CPA_C303,100 +CPA_J58,CPA_C32,30 +CPA_J58,CPA_C3316,4 +CPA_J58,CPA_C33OTHER,52 +CPA_J58,CPA_D351,6 +CPA_J58,CPA_E36,21 +CPA_J58,CPA_E38,14 +CPA_J58,"CPA_F41, F42 & F43",26 +CPA_J58,CPA_G45,55 +CPA_J58,CPA_G46,182 +CPA_J58,CPA_G47,304 +CPA_J58,CPA_H51,13 +CPA_J58,CPA_H52,20 +CPA_J58,CPA_I55,27 +CPA_J58,CPA_I56,32 +CPA_J58,CPA_J58,3236 +CPA_J58,CPA_J59 & J60,68 +CPA_J58,CPA_J61,31 +CPA_J58,CPA_J62,390 +CPA_J58,CPA_J63,20 +CPA_J58,CPA_K64,136 +CPA_J58,CPA_K65.1-2 & K65.3,49 +CPA_J58,CPA_K66,45 +CPA_J58,CPA_L68BXL683,7 +CPA_J58,CPA_L683,14 +CPA_J58,CPA_M691,9 +CPA_J58,CPA_M692,4 +CPA_J58,CPA_M70,60 +CPA_J58,CPA_M71,7 +CPA_J58,CPA_M72,8 +CPA_J58,CPA_M73,175 +CPA_J58,CPA_M74,10 +CPA_J58,CPA_N77,11 +CPA_J58,CPA_N78,21 +CPA_J58,CPA_N79,41 +CPA_J58,CPA_N82,33 +CPA_J58,CPA_O84,493 +CPA_J58,CPA_P85,1018 +CPA_J58,CPA_Q86,9 +CPA_J58,CPA_Q87 & Q88,286 +CPA_J58,CPA_R90,11 +CPA_J58,CPA_R91,31 +CPA_J58,CPA_R92,18 +CPA_J58,CPA_R93,207 +CPA_J58,CPA_S94,401 +CPA_J58,CPA_S96,8 +CPA_J59 & J60,CPA_A01,26 +CPA_J59 & J60,CPA_C106,5 +CPA_J59 & J60,CPA_C107,21 +CPA_J59 & J60,CPA_C108,45 +CPA_J59 & J60,CPA_C11.01-6 & C12,87 +CPA_J59 & J60,CPA_C204,31 +CPA_J59 & J60,CPA_C21,79 +CPA_J59 & J60,CPA_C22,12 +CPA_J59 & J60,CPA_C28,12 +CPA_J59 & J60,CPA_C29,83 +CPA_J59 & J60,CPA_D351,27 +CPA_J59 & J60,CPA_E38,48 +CPA_J59 & J60,"CPA_F41, F42 & F43",117 +CPA_J59 & J60,CPA_G45,240 +CPA_J59 & J60,CPA_G46,788 +CPA_J59 & J60,CPA_G47,1123 +CPA_J59 & J60,CPA_H51,60 +CPA_J59 & J60,CPA_H52,43 +CPA_J59 & J60,CPA_I55,144 +CPA_J59 & J60,CPA_I56,129 +CPA_J59 & J60,CPA_J58,88 +CPA_J59 & J60,CPA_J59 & J60,21630 +CPA_J59 & J60,CPA_J61,137 +CPA_J59 & J60,CPA_J62,264 +CPA_J59 & J60,CPA_J63,87 +CPA_J59 & J60,CPA_K64,1 +CPA_J59 & J60,CPA_K66,2 +CPA_J59 & J60,CPA_L68BXL683,29 +CPA_J59 & J60,CPA_L683,70 +CPA_J59 & J60,CPA_M691,61 +CPA_J59 & J60,CPA_M692,17 +CPA_J59 & J60,CPA_M70,240 +CPA_J59 & J60,CPA_M71,41 +CPA_J59 & J60,CPA_M72,37 +CPA_J59 & J60,CPA_M73,919 +CPA_J59 & J60,CPA_M74,39 +CPA_J59 & J60,CPA_N77,47 +CPA_J59 & J60,CPA_N78,132 +CPA_J59 & J60,CPA_N79,139 +CPA_J59 & J60,CPA_N82,138 +CPA_J59 & J60,CPA_O84,378 +CPA_J59 & J60,CPA_P85,262 +CPA_J59 & J60,CPA_Q86,99 +CPA_J59 & J60,CPA_Q87 & Q88,96 +CPA_J59 & J60,CPA_R90,152 +CPA_J59 & J60,CPA_R91,63 +CPA_J59 & J60,CPA_R92,357 +CPA_J59 & J60,CPA_R93,196 +CPA_J59 & J60,CPA_S94,218 +CPA_J59 & J60,CPA_S96,36 +CPA_J61,CPA_A01,339 +CPA_J61,CPA_A02,8 +CPA_J61,CPA_A03,8 +CPA_J61,CPA_B05 & B06,15 +CPA_J61,CPA_B07 & B08,10 +CPA_J61,CPA_B09,28 +CPA_J61,CPA_C101,8 +CPA_J61,CPA_C102_3,8 +CPA_J61,CPA_C104,1 +CPA_J61,CPA_C105,3 +CPA_J61,CPA_C106,5 +CPA_J61,CPA_C107,33 +CPA_J61,CPA_C108,19 +CPA_J61,CPA_C109,8 +CPA_J61,CPA_C11.01-6 & C12,19 +CPA_J61,CPA_C1107,9 +CPA_J61,CPA_C13,10 +CPA_J61,CPA_C14,5 +CPA_J61,CPA_C15,2 +CPA_J61,CPA_C16,25 +CPA_J61,CPA_C17,27 +CPA_J61,CPA_C18,63 +CPA_J61,CPA_C19,7 +CPA_J61,CPA_C203,8 +CPA_J61,CPA_C204,5 +CPA_J61,CPA_C205,9 +CPA_J61,CPA_C20A,6 +CPA_J61,CPA_C20B,6 +CPA_J61,CPA_C20C,1 +CPA_J61,CPA_C21,80 +CPA_J61,CPA_C22,49 +CPA_J61,CPA_C235_6,13 +CPA_J61,CPA_C23OTHER,11 +CPA_J61,CPA_C241_3,14 +CPA_J61,CPA_C244_5,6 +CPA_J61,CPA_C25,76 +CPA_J61,CPA_C26,53 +CPA_J61,CPA_C27,28 +CPA_J61,CPA_C28,53 +CPA_J61,CPA_C29,60 +CPA_J61,CPA_C301,6 +CPA_J61,CPA_C303,25 +CPA_J61,CPA_C30OTHER,5 +CPA_J61,CPA_C31,27 +CPA_J61,CPA_C32,43 +CPA_J61,CPA_C3315,3 +CPA_J61,CPA_C3316,7 +CPA_J61,CPA_C33OTHER,94 +CPA_J61,CPA_D351,274 +CPA_J61,CPA_D352_3,33 +CPA_J61,CPA_E36,63 +CPA_J61,CPA_E37,20 +CPA_J61,CPA_E38,57 +CPA_J61,CPA_E39,4 +CPA_J61,"CPA_F41, F42 & F43",1025 +CPA_J61,CPA_G45,252 +CPA_J61,CPA_G46,871 +CPA_J61,CPA_G47,715 +CPA_J61,CPA_H491_2,57 +CPA_J61,CPA_H493_5,209 +CPA_J61,CPA_H50,81 +CPA_J61,CPA_H51,52 +CPA_J61,CPA_H52,320 +CPA_J61,CPA_H53,87 +CPA_J61,CPA_I55,138 +CPA_J61,CPA_I56,289 +CPA_J61,CPA_J58,61 +CPA_J61,CPA_J59 & J60,1200 +CPA_J61,CPA_J61,5746 +CPA_J61,CPA_J62,873 +CPA_J61,CPA_J63,175 +CPA_J61,CPA_K64,3537 +CPA_J61,CPA_K65.1-2 & K65.3,639 +CPA_J61,CPA_K66,4016 +CPA_J61,CPA_L68BXL683,306 +CPA_J61,CPA_L68A,497 +CPA_J61,CPA_L683,143 +CPA_J61,CPA_M691,353 +CPA_J61,CPA_M692,89 +CPA_J61,CPA_M70,798 +CPA_J61,CPA_M71,270 +CPA_J61,CPA_M72,39 +CPA_J61,CPA_M73,139 +CPA_J61,CPA_M74,179 +CPA_J61,CPA_M75,36 +CPA_J61,CPA_N77,122 +CPA_J61,CPA_N78,231 +CPA_J61,CPA_N79,226 +CPA_J61,CPA_N80,39 +CPA_J61,CPA_N81,130 +CPA_J61,CPA_N82,512 +CPA_J61,CPA_O84,2987 +CPA_J61,CPA_P85,363 +CPA_J61,CPA_Q86,1783 +CPA_J61,CPA_Q87 & Q88,605 +CPA_J61,CPA_R90,145 +CPA_J61,CPA_R91,27 +CPA_J61,CPA_R92,215 +CPA_J61,CPA_R93,149 +CPA_J61,CPA_S94,127 +CPA_J61,CPA_S95,299 +CPA_J61,CPA_S96,176 +CPA_J62,CPA_A01,132 +CPA_J62,CPA_A02,23 +CPA_J62,CPA_A03,10 +CPA_J62,CPA_B05 & B06,379 +CPA_J62,CPA_B07 & B08,29 +CPA_J62,CPA_B09,101 +CPA_J62,CPA_C101,99 +CPA_J62,CPA_C102_3,56 +CPA_J62,CPA_C104,6 +CPA_J62,CPA_C105,31 +CPA_J62,CPA_C106,23 +CPA_J62,CPA_C107,63 +CPA_J62,CPA_C108,110 +CPA_J62,CPA_C109,52 +CPA_J62,CPA_C11.01-6 & C12,184 +CPA_J62,CPA_C1107,56 +CPA_J62,CPA_C13,36 +CPA_J62,CPA_C14,25 +CPA_J62,CPA_C15,11 +CPA_J62,CPA_C16,57 +CPA_J62,CPA_C17,83 +CPA_J62,CPA_C18,79 +CPA_J62,CPA_C19,19 +CPA_J62,CPA_C203,32 +CPA_J62,CPA_C204,29 +CPA_J62,CPA_C205,57 +CPA_J62,CPA_C20A,28 +CPA_J62,CPA_C20B,74 +CPA_J62,CPA_C20C,8 +CPA_J62,CPA_C21,649 +CPA_J62,CPA_C22,129 +CPA_J62,CPA_C235_6,37 +CPA_J62,CPA_C23OTHER,59 +CPA_J62,CPA_C241_3,66 +CPA_J62,CPA_C244_5,52 +CPA_J62,CPA_C25,389 +CPA_J62,CPA_C26,255 +CPA_J62,CPA_C27,118 +CPA_J62,CPA_C28,248 +CPA_J62,CPA_C29,923 +CPA_J62,CPA_C301,236 +CPA_J62,CPA_C303,999 +CPA_J62,CPA_C30OTHER,48 +CPA_J62,CPA_C31,36 +CPA_J62,CPA_C32,124 +CPA_J62,CPA_C3315,4 +CPA_J62,CPA_C3316,26 +CPA_J62,CPA_C33OTHER,171 +CPA_J62,CPA_D351,942 +CPA_J62,CPA_D352_3,530 +CPA_J62,CPA_E36,140 +CPA_J62,CPA_E37,106 +CPA_J62,CPA_E38,198 +CPA_J62,CPA_E39,8 +CPA_J62,"CPA_F41, F42 & F43",2818 +CPA_J62,CPA_G45,1137 +CPA_J62,CPA_G46,3754 +CPA_J62,CPA_G47,4365 +CPA_J62,CPA_H491_2,256 +CPA_J62,CPA_H493_5,459 +CPA_J62,CPA_H50,158 +CPA_J62,CPA_H51,144 +CPA_J62,CPA_H52,1009 +CPA_J62,CPA_H53,358 +CPA_J62,CPA_I55,413 +CPA_J62,CPA_I56,629 +CPA_J62,CPA_J58,484 +CPA_J62,CPA_J59 & J60,668 +CPA_J62,CPA_J61,1762 +CPA_J62,CPA_J62,33225 +CPA_J62,CPA_J63,933 +CPA_J62,CPA_K64,5892 +CPA_J62,CPA_K65.1-2 & K65.3,1268 +CPA_J62,CPA_K66,5756 +CPA_J62,CPA_L68BXL683,1120 +CPA_J62,CPA_L683,392 +CPA_J62,CPA_M691,1758 +CPA_J62,CPA_M692,996 +CPA_J62,CPA_M70,2856 +CPA_J62,CPA_M71,1495 +CPA_J62,CPA_M72,353 +CPA_J62,CPA_M73,312 +CPA_J62,CPA_M74,863 +CPA_J62,CPA_M75,99 +CPA_J62,CPA_N77,350 +CPA_J62,CPA_N78,676 +CPA_J62,CPA_N79,232 +CPA_J62,CPA_N80,71 +CPA_J62,CPA_N81,266 +CPA_J62,CPA_N82,2061 +CPA_J62,CPA_O84,3529 +CPA_J62,CPA_P85,1569 +CPA_J62,CPA_Q86,2481 +CPA_J62,CPA_Q87 & Q88,1030 +CPA_J62,CPA_R90,159 +CPA_J62,CPA_R91,74 +CPA_J62,CPA_R92,316 +CPA_J62,CPA_R93,433 +CPA_J62,CPA_S94,494 +CPA_J62,CPA_S95,95 +CPA_J62,CPA_S96,179 +CPA_J63,CPA_A01,70 +CPA_J63,CPA_B05 & B06,1 +CPA_J63,CPA_C102_3,1 +CPA_J63,CPA_C106,12 +CPA_J63,CPA_C107,67 +CPA_J63,CPA_C108,149 +CPA_J63,CPA_C11.01-6 & C12,271 +CPA_J63,CPA_C13,6 +CPA_J63,CPA_C14,1 +CPA_J63,CPA_C17,1 +CPA_J63,CPA_C18,18 +CPA_J63,CPA_C204,98 +CPA_J63,CPA_C21,317 +CPA_J63,CPA_C22,37 +CPA_J63,CPA_C235_6,3 +CPA_J63,CPA_C26,1 +CPA_J63,CPA_C28,40 +CPA_J63,CPA_C29,347 +CPA_J63,CPA_C301,1 +CPA_J63,CPA_C303,8 +CPA_J63,CPA_C32,2 +CPA_J63,CPA_C33OTHER,6 +CPA_J63,CPA_D351,78 +CPA_J63,CPA_D352_3,310 +CPA_J63,CPA_E36,6 +CPA_J63,"CPA_F41, F42 & F43",441 +CPA_J63,CPA_G45,1297 +CPA_J63,CPA_G46,3716 +CPA_J63,CPA_G47,4881 +CPA_J63,CPA_H491_2,9 +CPA_J63,CPA_H493_5,18 +CPA_J63,CPA_H51,209 +CPA_J63,CPA_H52,251 +CPA_J63,CPA_H53,116 +CPA_J63,CPA_I55,350 +CPA_J63,CPA_I56,450 +CPA_J63,CPA_J58,474 +CPA_J63,CPA_J59 & J60,1177 +CPA_J63,CPA_J61,2765 +CPA_J63,CPA_J62,2732 +CPA_J63,CPA_J63,1059 +CPA_J63,CPA_K64,2464 +CPA_J63,CPA_K65.1-2 & K65.3,346 +CPA_J63,CPA_K66,1197 +CPA_J63,CPA_L68BXL683,102 +CPA_J63,CPA_L683,399 +CPA_J63,CPA_M691,221 +CPA_J63,CPA_M692,335 +CPA_J63,CPA_M70,1182 +CPA_J63,CPA_M71,180 +CPA_J63,CPA_M72,235 +CPA_J63,CPA_M73,2922 +CPA_J63,CPA_M74,370 +CPA_J63,CPA_N77,355 +CPA_J63,CPA_N78,400 +CPA_J63,CPA_N79,575 +CPA_J63,CPA_N80,27 +CPA_J63,CPA_N82,992 +CPA_J63,CPA_P85,90 +CPA_J63,CPA_Q86,10 +CPA_J63,CPA_R90,130 +CPA_J63,CPA_R92,400 +CPA_J63,CPA_R93,196 +CPA_J63,CPA_S94,135 +CPA_J63,CPA_S95,10 +CPA_J63,CPA_S96,250 +CPA_K64,CPA_A01,1308 +CPA_K64,CPA_A02,35 +CPA_K64,CPA_A03,55 +CPA_K64,CPA_B05 & B06,1483 +CPA_K64,CPA_B07 & B08,516 +CPA_K64,CPA_B09,410 +CPA_K64,CPA_C101,174 +CPA_K64,CPA_C102_3,295 +CPA_K64,CPA_C104,11 +CPA_K64,CPA_C105,191 +CPA_K64,CPA_C106,174 +CPA_K64,CPA_C107,400 +CPA_K64,CPA_C108,943 +CPA_K64,CPA_C109,104 +CPA_K64,CPA_C11.01-6 & C12,706 +CPA_K64,CPA_C1107,116 +CPA_K64,CPA_C13,152 +CPA_K64,CPA_C14,314 +CPA_K64,CPA_C15,60 +CPA_K64,CPA_C16,292 +CPA_K64,CPA_C17,327 +CPA_K64,CPA_C18,182 +CPA_K64,CPA_C19,556 +CPA_K64,CPA_C203,70 +CPA_K64,CPA_C204,126 +CPA_K64,CPA_C205,379 +CPA_K64,CPA_C20A,132 +CPA_K64,CPA_C20B,479 +CPA_K64,CPA_C20C,85 +CPA_K64,CPA_C21,686 +CPA_K64,CPA_C22,701 +CPA_K64,CPA_C235_6,204 +CPA_K64,CPA_C23OTHER,339 +CPA_K64,CPA_C241_3,251 +CPA_K64,CPA_C244_5,363 +CPA_K64,CPA_C25,1108 +CPA_K64,CPA_C26,276 +CPA_K64,CPA_C27,368 +CPA_K64,CPA_C28,771 +CPA_K64,CPA_C29,1710 +CPA_K64,CPA_C301,62 +CPA_K64,CPA_C303,1824 +CPA_K64,CPA_C30OTHER,236 +CPA_K64,CPA_C31,151 +CPA_K64,CPA_C32,267 +CPA_K64,CPA_C3315,20 +CPA_K64,CPA_C3316,114 +CPA_K64,CPA_C33OTHER,226 +CPA_K64,CPA_D351,1365 +CPA_K64,CPA_D352_3,419 +CPA_K64,CPA_E36,334 +CPA_K64,CPA_E37,93 +CPA_K64,CPA_E38,727 +CPA_K64,CPA_E39,12 +CPA_K64,"CPA_F41, F42 & F43",4007 +CPA_K64,CPA_G45,1047 +CPA_K64,CPA_G46,2291 +CPA_K64,CPA_G47,3150 +CPA_K64,CPA_H491_2,170 +CPA_K64,CPA_H493_5,948 +CPA_K64,CPA_H50,286 +CPA_K64,CPA_H51,433 +CPA_K64,CPA_H52,1587 +CPA_K64,CPA_H53,613 +CPA_K64,CPA_I55,630 +CPA_K64,CPA_I56,1410 +CPA_K64,CPA_J58,149 +CPA_K64,CPA_J59 & J60,349 +CPA_K64,CPA_J61,824 +CPA_K64,CPA_J62,914 +CPA_K64,CPA_J63,194 +CPA_K64,CPA_K64,17251 +CPA_K64,CPA_K65.1-2 & K65.3,2250 +CPA_K64,CPA_K66,184 +CPA_K64,CPA_L68BXL683,9440 +CPA_K64,CPA_L68A,-16544 +CPA_K64,CPA_L683,1625 +CPA_K64,CPA_M691,706 +CPA_K64,CPA_M692,686 +CPA_K64,CPA_M70,1218 +CPA_K64,CPA_M71,1195 +CPA_K64,CPA_M72,436 +CPA_K64,CPA_M73,446 +CPA_K64,CPA_M74,461 +CPA_K64,CPA_M75,104 +CPA_K64,CPA_N77,642 +CPA_K64,CPA_N78,982 +CPA_K64,CPA_N79,582 +CPA_K64,CPA_N80,90 +CPA_K64,CPA_N81,448 +CPA_K64,CPA_N82,841 +CPA_K64,CPA_O84,5695 +CPA_K64,CPA_P85,2630 +CPA_K64,CPA_Q86,904 +CPA_K64,CPA_Q87 & Q88,918 +CPA_K64,CPA_R90,392 +CPA_K64,CPA_R91,12 +CPA_K64,CPA_R92,204 +CPA_K64,CPA_R93,221 +CPA_K64,CPA_S94,387 +CPA_K64,CPA_S95,102 +CPA_K64,CPA_S96,649 +CPA_K65.1-2 & K65.3,CPA_A01,265 +CPA_K65.1-2 & K65.3,CPA_A02,10 +CPA_K65.1-2 & K65.3,CPA_A03,17 +CPA_K65.1-2 & K65.3,CPA_B05 & B06,141 +CPA_K65.1-2 & K65.3,CPA_B07 & B08,41 +CPA_K65.1-2 & K65.3,CPA_B09,25 +CPA_K65.1-2 & K65.3,CPA_C101,221 +CPA_K65.1-2 & K65.3,CPA_C102_3,62 +CPA_K65.1-2 & K65.3,CPA_C104,8 +CPA_K65.1-2 & K65.3,CPA_C105,81 +CPA_K65.1-2 & K65.3,CPA_C106,36 +CPA_K65.1-2 & K65.3,CPA_C107,78 +CPA_K65.1-2 & K65.3,CPA_C108,181 +CPA_K65.1-2 & K65.3,CPA_C109,69 +CPA_K65.1-2 & K65.3,CPA_C11.01-6 & C12,87 +CPA_K65.1-2 & K65.3,CPA_C1107,36 +CPA_K65.1-2 & K65.3,CPA_C13,38 +CPA_K65.1-2 & K65.3,CPA_C14,10 +CPA_K65.1-2 & K65.3,CPA_C15,3 +CPA_K65.1-2 & K65.3,CPA_C16,53 +CPA_K65.1-2 & K65.3,CPA_C17,68 +CPA_K65.1-2 & K65.3,CPA_C18,37 +CPA_K65.1-2 & K65.3,CPA_C19,373 +CPA_K65.1-2 & K65.3,CPA_C203,17 +CPA_K65.1-2 & K65.3,CPA_C204,35 +CPA_K65.1-2 & K65.3,CPA_C205,36 +CPA_K65.1-2 & K65.3,CPA_C20A,25 +CPA_K65.1-2 & K65.3,CPA_C20B,45 +CPA_K65.1-2 & K65.3,CPA_C20C,14 +CPA_K65.1-2 & K65.3,CPA_C21,222 +CPA_K65.1-2 & K65.3,CPA_C22,187 +CPA_K65.1-2 & K65.3,CPA_C235_6,40 +CPA_K65.1-2 & K65.3,CPA_C23OTHER,38 +CPA_K65.1-2 & K65.3,CPA_C241_3,120 +CPA_K65.1-2 & K65.3,CPA_C244_5,28 +CPA_K65.1-2 & K65.3,CPA_C25,266 +CPA_K65.1-2 & K65.3,CPA_C26,122 +CPA_K65.1-2 & K65.3,CPA_C27,75 +CPA_K65.1-2 & K65.3,CPA_C28,288 +CPA_K65.1-2 & K65.3,CPA_C29,567 +CPA_K65.1-2 & K65.3,CPA_C301,43 +CPA_K65.1-2 & K65.3,CPA_C303,240 +CPA_K65.1-2 & K65.3,CPA_C30OTHER,15 +CPA_K65.1-2 & K65.3,CPA_C31,41 +CPA_K65.1-2 & K65.3,CPA_C32,62 +CPA_K65.1-2 & K65.3,CPA_C3315,3 +CPA_K65.1-2 & K65.3,CPA_C3316,28 +CPA_K65.1-2 & K65.3,CPA_C33OTHER,69 +CPA_K65.1-2 & K65.3,CPA_D351,450 +CPA_K65.1-2 & K65.3,CPA_D352_3,69 +CPA_K65.1-2 & K65.3,CPA_E36,49 +CPA_K65.1-2 & K65.3,CPA_E37,14 +CPA_K65.1-2 & K65.3,CPA_E38,172 +CPA_K65.1-2 & K65.3,CPA_E39,4 +CPA_K65.1-2 & K65.3,"CPA_F41, F42 & F43",1927 +CPA_K65.1-2 & K65.3,CPA_G45,352 +CPA_K65.1-2 & K65.3,CPA_G46,948 +CPA_K65.1-2 & K65.3,CPA_G47,781 +CPA_K65.1-2 & K65.3,CPA_H491_2,108 +CPA_K65.1-2 & K65.3,CPA_H493_5,470 +CPA_K65.1-2 & K65.3,CPA_H50,107 +CPA_K65.1-2 & K65.3,CPA_H51,376 +CPA_K65.1-2 & K65.3,CPA_H52,359 +CPA_K65.1-2 & K65.3,CPA_H53,94 +CPA_K65.1-2 & K65.3,CPA_I55,132 +CPA_K65.1-2 & K65.3,CPA_I56,407 +CPA_K65.1-2 & K65.3,CPA_J58,71 +CPA_K65.1-2 & K65.3,CPA_J59 & J60,366 +CPA_K65.1-2 & K65.3,CPA_J61,211 +CPA_K65.1-2 & K65.3,CPA_J62,644 +CPA_K65.1-2 & K65.3,CPA_J63,94 +CPA_K65.1-2 & K65.3,CPA_K64,210 +CPA_K65.1-2 & K65.3,CPA_K65.1-2 & K65.3,14489 +CPA_K65.1-2 & K65.3,CPA_K66,14 +CPA_K65.1-2 & K65.3,CPA_L68BXL683,162 +CPA_K65.1-2 & K65.3,CPA_L68A,2254 +CPA_K65.1-2 & K65.3,CPA_L683,82 +CPA_K65.1-2 & K65.3,CPA_M691,93 +CPA_K65.1-2 & K65.3,CPA_M692,73 +CPA_K65.1-2 & K65.3,CPA_M70,401 +CPA_K65.1-2 & K65.3,CPA_M71,365 +CPA_K65.1-2 & K65.3,CPA_M72,131 +CPA_K65.1-2 & K65.3,CPA_M73,122 +CPA_K65.1-2 & K65.3,CPA_M74,110 +CPA_K65.1-2 & K65.3,CPA_M75,17 +CPA_K65.1-2 & K65.3,CPA_N77,136 +CPA_K65.1-2 & K65.3,CPA_N78,335 +CPA_K65.1-2 & K65.3,CPA_N79,232 +CPA_K65.1-2 & K65.3,CPA_N80,27 +CPA_K65.1-2 & K65.3,CPA_N81,142 +CPA_K65.1-2 & K65.3,CPA_N82,328 +CPA_K65.1-2 & K65.3,CPA_O84,80 +CPA_K65.1-2 & K65.3,CPA_P85,350 +CPA_K65.1-2 & K65.3,CPA_Q86,112 +CPA_K65.1-2 & K65.3,CPA_Q87 & Q88,149 +CPA_K65.1-2 & K65.3,CPA_R90,71 +CPA_K65.1-2 & K65.3,CPA_R91,10 +CPA_K65.1-2 & K65.3,CPA_R92,24 +CPA_K65.1-2 & K65.3,CPA_R93,107 +CPA_K65.1-2 & K65.3,CPA_S94,63 +CPA_K65.1-2 & K65.3,CPA_S95,21 +CPA_K65.1-2 & K65.3,CPA_S96,63 +CPA_K66,CPA_B05 & B06,1 +CPA_K66,CPA_B07 & B08,4 +CPA_K66,CPA_B09,1 +CPA_K66,CPA_C101,20 +CPA_K66,CPA_C105,8 +CPA_K66,CPA_C106,4 +CPA_K66,CPA_C108,6 +CPA_K66,CPA_C11.01-6 & C12,26 +CPA_K66,CPA_C13,1 +CPA_K66,CPA_C14,2 +CPA_K66,CPA_C17,3 +CPA_K66,CPA_C18,5 +CPA_K66,CPA_C19,60 +CPA_K66,CPA_C203,1 +CPA_K66,CPA_C204,39 +CPA_K66,CPA_C205,30 +CPA_K66,CPA_C20A,21 +CPA_K66,CPA_C20B,88 +CPA_K66,CPA_C21,3 +CPA_K66,CPA_C22,6 +CPA_K66,CPA_C235_6,4 +CPA_K66,CPA_C23OTHER,15 +CPA_K66,CPA_C241_3,35 +CPA_K66,CPA_C244_5,5 +CPA_K66,CPA_C25,48 +CPA_K66,CPA_C26,26 +CPA_K66,CPA_C27,40 +CPA_K66,CPA_C28,25 +CPA_K66,CPA_C29,102 +CPA_K66,CPA_C303,35 +CPA_K66,CPA_C30OTHER,10 +CPA_K66,CPA_C31,1 +CPA_K66,CPA_C32,11 +CPA_K66,CPA_C3316,1 +CPA_K66,CPA_C33OTHER,3 +CPA_K66,CPA_D351,1 +CPA_K66,CPA_D352_3,9 +CPA_K66,CPA_E36,5 +CPA_K66,CPA_E37,8 +CPA_K66,CPA_E38,174 +CPA_K66,"CPA_F41, F42 & F43",735 +CPA_K66,CPA_G45,90 +CPA_K66,CPA_G46,3434 +CPA_K66,CPA_G47,634 +CPA_K66,CPA_H491_2,5 +CPA_K66,CPA_H493_5,16 +CPA_K66,CPA_H50,255 +CPA_K66,CPA_H51,463 +CPA_K66,CPA_H52,140 +CPA_K66,CPA_H53,67 +CPA_K66,CPA_I55,25 +CPA_K66,CPA_I56,120 +CPA_K66,CPA_J58,55 +CPA_K66,CPA_J59 & J60,21 +CPA_K66,CPA_J61,305 +CPA_K66,CPA_J62,1474 +CPA_K66,CPA_J63,42 +CPA_K66,CPA_K64,14097 +CPA_K66,CPA_K65.1-2 & K65.3,10408 +CPA_K66,CPA_K66,19611 +CPA_K66,CPA_L68BXL683,118 +CPA_K66,CPA_L683,333 +CPA_K66,CPA_M691,218 +CPA_K66,CPA_M692,90 +CPA_K66,CPA_M70,7747 +CPA_K66,CPA_M71,819 +CPA_K66,CPA_M72,130 +CPA_K66,CPA_M73,58 +CPA_K66,CPA_M74,160 +CPA_K66,CPA_N77,390 +CPA_K66,CPA_N78,280 +CPA_K66,CPA_N79,8 +CPA_K66,CPA_N80,27 +CPA_K66,CPA_N81,150 +CPA_K66,CPA_N82,200 +CPA_K66,CPA_O84,43 +CPA_K66,CPA_P85,32 +CPA_K66,CPA_Q86,3 +CPA_K66,CPA_R90,12 +CPA_K66,CPA_R92,20 +CPA_K66,CPA_R93,9 +CPA_K66,CPA_S95,20 +CPA_K66,CPA_S96,37 +CPA_L68BXL683,CPA_C101,2 +CPA_L68BXL683,CPA_C102_3,1 +CPA_L68BXL683,CPA_C13,14 +CPA_L68BXL683,CPA_C15,3 +CPA_L68BXL683,CPA_C16,4 +CPA_L68BXL683,CPA_C17,299 +CPA_L68BXL683,CPA_C18,53 +CPA_L68BXL683,CPA_C203,1 +CPA_L68BXL683,CPA_C204,1 +CPA_L68BXL683,CPA_C205,7 +CPA_L68BXL683,CPA_C20B,25 +CPA_L68BXL683,CPA_C21,12 +CPA_L68BXL683,CPA_C22,254 +CPA_L68BXL683,CPA_C241_3,9 +CPA_L68BXL683,CPA_C244_5,5 +CPA_L68BXL683,CPA_C25,150 +CPA_L68BXL683,CPA_C27,30 +CPA_L68BXL683,CPA_C30OTHER,3 +CPA_L68BXL683,CPA_C31,122 +CPA_L68BXL683,CPA_C33OTHER,9 +CPA_L68BXL683,CPA_D351,137 +CPA_L68BXL683,CPA_D352_3,200 +CPA_L68BXL683,CPA_E36,11 +CPA_L68BXL683,CPA_E37,4 +CPA_L68BXL683,CPA_E38,192 +CPA_L68BXL683,CPA_E39,14 +CPA_L68BXL683,"CPA_F41, F42 & F43",526 +CPA_L68BXL683,CPA_G45,1023 +CPA_L68BXL683,CPA_G46,3022 +CPA_L68BXL683,CPA_G47,8243 +CPA_L68BXL683,CPA_H493_5,573 +CPA_L68BXL683,CPA_H50,58 +CPA_L68BXL683,CPA_H51,679 +CPA_L68BXL683,CPA_H52,2073 +CPA_L68BXL683,CPA_H53,53 +CPA_L68BXL683,CPA_I55,1264 +CPA_L68BXL683,CPA_I56,2026 +CPA_L68BXL683,CPA_J58,305 +CPA_L68BXL683,CPA_J59 & J60,1517 +CPA_L68BXL683,CPA_J61,1410 +CPA_L68BXL683,CPA_J62,2473 +CPA_L68BXL683,CPA_K64,2352 +CPA_L68BXL683,CPA_K65.1-2 & K65.3,556 +CPA_L68BXL683,CPA_K66,124 +CPA_L68BXL683,CPA_L68BXL683,8728 +CPA_L68BXL683,CPA_L68A,125 +CPA_L68BXL683,CPA_L683,1052 +CPA_L68BXL683,CPA_M691,2279 +CPA_L68BXL683,CPA_M692,274 +CPA_L68BXL683,CPA_M70,434 +CPA_L68BXL683,CPA_M71,1129 +CPA_L68BXL683,CPA_M72,336 +CPA_L68BXL683,CPA_M73,2161 +CPA_L68BXL683,CPA_M74,203 +CPA_L68BXL683,CPA_M75,111 +CPA_L68BXL683,CPA_N77,298 +CPA_L68BXL683,CPA_N78,914 +CPA_L68BXL683,CPA_N79,311 +CPA_L68BXL683,CPA_N81,232 +CPA_L68BXL683,CPA_N82,722 +CPA_L68BXL683,CPA_O84,4478 +CPA_L68BXL683,CPA_P85,2326 +CPA_L68BXL683,CPA_Q86,3081 +CPA_L68BXL683,CPA_Q87 & Q88,1139 +CPA_L68BXL683,CPA_R90,12 +CPA_L68BXL683,CPA_R91,28 +CPA_L68BXL683,CPA_R92,382 +CPA_L68BXL683,CPA_R93,449 +CPA_L68BXL683,CPA_S95,73 +CPA_L68BXL683,CPA_S96,568 +CPA_L683,CPA_E38,2 +CPA_L683,"CPA_F41, F42 & F43",137 +CPA_L683,CPA_J59 & J60,8 +CPA_L683,CPA_J61,623 +CPA_L683,CPA_K64,75 +CPA_L683,CPA_K65.1-2 & K65.3,31 +CPA_L683,CPA_K66,4 +CPA_L683,CPA_L68BXL683,6330 +CPA_L683,CPA_L68A,40 +CPA_L683,CPA_L683,2270 +CPA_L683,CPA_M691,6 +CPA_L683,CPA_M70,4 +CPA_L683,CPA_M71,68 +CPA_L683,CPA_N81,11 +CPA_L683,CPA_O84,8 +CPA_L683,CPA_P85,16 +CPA_M691,CPA_A01,78 +CPA_M691,CPA_A02,3 +CPA_M691,CPA_A03,6 +CPA_M691,CPA_B05 & B06,64 +CPA_M691,CPA_B07 & B08,43 +CPA_M691,CPA_B09,103 +CPA_M691,CPA_C101,92 +CPA_M691,CPA_C102_3,67 +CPA_M691,CPA_C104,2 +CPA_M691,CPA_C105,82 +CPA_M691,CPA_C106,117 +CPA_M691,CPA_C107,151 +CPA_M691,CPA_C108,76 +CPA_M691,CPA_C109,81 +CPA_M691,CPA_C11.01-6 & C12,45 +CPA_M691,CPA_C1107,36 +CPA_M691,CPA_C13,27 +CPA_M691,CPA_C14,2 +CPA_M691,CPA_C15,15 +CPA_M691,CPA_C16,6 +CPA_M691,CPA_C17,94 +CPA_M691,CPA_C18,7 +CPA_M691,CPA_C19,15 +CPA_M691,CPA_C203,12 +CPA_M691,CPA_C204,58 +CPA_M691,CPA_C205,94 +CPA_M691,CPA_C20A,35 +CPA_M691,CPA_C20B,60 +CPA_M691,CPA_C20C,28 +CPA_M691,CPA_C21,1109 +CPA_M691,CPA_C22,50 +CPA_M691,CPA_C235_6,28 +CPA_M691,CPA_C23OTHER,41 +CPA_M691,CPA_C241_3,103 +CPA_M691,CPA_C244_5,20 +CPA_M691,CPA_C25,22 +CPA_M691,CPA_C26,463 +CPA_M691,CPA_C27,124 +CPA_M691,CPA_C28,256 +CPA_M691,CPA_C29,270 +CPA_M691,CPA_C301,76 +CPA_M691,CPA_C303,55 +CPA_M691,CPA_C30OTHER,10 +CPA_M691,CPA_C31,41 +CPA_M691,CPA_C32,59 +CPA_M691,CPA_C3315,7 +CPA_M691,CPA_C3316,2 +CPA_M691,CPA_C33OTHER,92 +CPA_M691,CPA_D351,355 +CPA_M691,CPA_D352_3,288 +CPA_M691,CPA_E36,41 +CPA_M691,CPA_E37,14 +CPA_M691,CPA_E38,174 +CPA_M691,CPA_E39,9 +CPA_M691,"CPA_F41, F42 & F43",1126 +CPA_M691,CPA_G45,275 +CPA_M691,CPA_G46,805 +CPA_M691,CPA_G47,718 +CPA_M691,CPA_H491_2,18 +CPA_M691,CPA_H493_5,77 +CPA_M691,CPA_H50,37 +CPA_M691,CPA_H51,87 +CPA_M691,CPA_H52,251 +CPA_M691,CPA_H53,41 +CPA_M691,CPA_I55,68 +CPA_M691,CPA_I56,103 +CPA_M691,CPA_J58,175 +CPA_M691,CPA_J59 & J60,673 +CPA_M691,CPA_J61,470 +CPA_M691,CPA_J62,1978 +CPA_M691,CPA_J63,307 +CPA_M691,CPA_K64,3613 +CPA_M691,CPA_K65.1-2 & K65.3,883 +CPA_M691,CPA_K66,1347 +CPA_M691,CPA_L68BXL683,612 +CPA_M691,CPA_L68A,591 +CPA_M691,CPA_L683,143 +CPA_M691,CPA_M691,2074 +CPA_M691,CPA_M692,621 +CPA_M691,CPA_M70,2503 +CPA_M691,CPA_M71,242 +CPA_M691,CPA_M72,417 +CPA_M691,CPA_M73,254 +CPA_M691,CPA_M74,287 +CPA_M691,CPA_M75,14 +CPA_M691,CPA_N77,283 +CPA_M691,CPA_N78,507 +CPA_M691,CPA_N79,198 +CPA_M691,CPA_N80,11 +CPA_M691,CPA_N81,109 +CPA_M691,CPA_N82,778 +CPA_M691,CPA_O84,4508 +CPA_M691,CPA_P85,494 +CPA_M691,CPA_Q86,3013 +CPA_M691,CPA_Q87 & Q88,400 +CPA_M691,CPA_R90,67 +CPA_M691,CPA_R91,33 +CPA_M691,CPA_R92,113 +CPA_M691,CPA_R93,571 +CPA_M691,CPA_S94,453 +CPA_M691,CPA_S95,27 +CPA_M691,CPA_S96,45 +CPA_M692,CPA_A01,211 +CPA_M692,CPA_A02,38 +CPA_M692,CPA_A03,13 +CPA_M692,CPA_B05 & B06,37 +CPA_M692,CPA_B07 & B08,14 +CPA_M692,CPA_B09,112 +CPA_M692,CPA_C101,110 +CPA_M692,CPA_C102_3,71 +CPA_M692,CPA_C104,17 +CPA_M692,CPA_C105,158 +CPA_M692,CPA_C106,129 +CPA_M692,CPA_C107,100 +CPA_M692,CPA_C108,142 +CPA_M692,CPA_C109,31 +CPA_M692,CPA_C11.01-6 & C12,257 +CPA_M692,CPA_C1107,54 +CPA_M692,CPA_C13,60 +CPA_M692,CPA_C14,22 +CPA_M692,CPA_C15,9 +CPA_M692,CPA_C16,76 +CPA_M692,CPA_C17,106 +CPA_M692,CPA_C18,40 +CPA_M692,CPA_C19,23 +CPA_M692,CPA_C203,14 +CPA_M692,CPA_C204,63 +CPA_M692,CPA_C205,124 +CPA_M692,CPA_C20A,17 +CPA_M692,CPA_C20B,87 +CPA_M692,CPA_C20C,34 +CPA_M692,CPA_C21,400 +CPA_M692,CPA_C22,78 +CPA_M692,CPA_C235_6,169 +CPA_M692,CPA_C23OTHER,72 +CPA_M692,CPA_C241_3,68 +CPA_M692,CPA_C244_5,44 +CPA_M692,CPA_C25,109 +CPA_M692,CPA_C26,281 +CPA_M692,CPA_C27,98 +CPA_M692,CPA_C28,252 +CPA_M692,CPA_C29,113 +CPA_M692,CPA_C301,93 +CPA_M692,CPA_C303,66 +CPA_M692,CPA_C30OTHER,18 +CPA_M692,CPA_C31,124 +CPA_M692,CPA_C32,127 +CPA_M692,CPA_C3315,29 +CPA_M692,CPA_C3316,3 +CPA_M692,CPA_C33OTHER,62 +CPA_M692,CPA_D351,457 +CPA_M692,CPA_D352_3,241 +CPA_M692,CPA_E36,40 +CPA_M692,CPA_E37,4 +CPA_M692,CPA_E38,79 +CPA_M692,CPA_E39,33 +CPA_M692,"CPA_F41, F42 & F43",368 +CPA_M692,CPA_G45,327 +CPA_M692,CPA_G46,1811 +CPA_M692,CPA_G47,1059 +CPA_M692,CPA_H491_2,183 +CPA_M692,CPA_H493_5,196 +CPA_M692,CPA_H50,31 +CPA_M692,CPA_H51,32 +CPA_M692,CPA_H52,1011 +CPA_M692,CPA_H53,79 +CPA_M692,CPA_I55,140 +CPA_M692,CPA_I56,476 +CPA_M692,CPA_J58,135 +CPA_M692,CPA_J59 & J60,770 +CPA_M692,CPA_J61,434 +CPA_M692,CPA_J62,4154 +CPA_M692,CPA_J63,203 +CPA_M692,CPA_K64,2819 +CPA_M692,CPA_K65.1-2 & K65.3,282 +CPA_M692,CPA_K66,207 +CPA_M692,CPA_L68BXL683,383 +CPA_M692,CPA_L683,441 +CPA_M692,CPA_M691,420 +CPA_M692,CPA_M692,4154 +CPA_M692,CPA_M70,2558 +CPA_M692,CPA_M71,638 +CPA_M692,CPA_M72,303 +CPA_M692,CPA_M73,560 +CPA_M692,CPA_M74,635 +CPA_M692,CPA_M75,22 +CPA_M692,CPA_N77,197 +CPA_M692,CPA_N78,1245 +CPA_M692,CPA_N79,276 +CPA_M692,CPA_N80,126 +CPA_M692,CPA_N81,87 +CPA_M692,CPA_N82,1354 +CPA_M692,CPA_O84,701 +CPA_M692,CPA_P85,1354 +CPA_M692,CPA_Q86,1217 +CPA_M692,CPA_Q87 & Q88,1025 +CPA_M692,CPA_R90,353 +CPA_M692,CPA_R91,41 +CPA_M692,CPA_R92,38 +CPA_M692,CPA_R93,400 +CPA_M692,CPA_S94,454 +CPA_M692,CPA_S95,49 +CPA_M692,CPA_S96,420 +CPA_M70,CPA_A01,104 +CPA_M70,CPA_A03,1 +CPA_M70,CPA_B05 & B06,154 +CPA_M70,CPA_B07 & B08,4 +CPA_M70,CPA_B09,264 +CPA_M70,CPA_C101,45 +CPA_M70,CPA_C102_3,3 +CPA_M70,CPA_C106,8 +CPA_M70,CPA_C107,20 +CPA_M70,CPA_C108,13 +CPA_M70,CPA_C109,4 +CPA_M70,CPA_C11.01-6 & C12,426 +CPA_M70,CPA_C1107,170 +CPA_M70,CPA_C13,62 +CPA_M70,CPA_C14,8 +CPA_M70,CPA_C15,16 +CPA_M70,CPA_C16,2 +CPA_M70,CPA_C17,100 +CPA_M70,CPA_C18,39 +CPA_M70,CPA_C203,31 +CPA_M70,CPA_C204,506 +CPA_M70,CPA_C205,1 +CPA_M70,CPA_C20A,10 +CPA_M70,CPA_C20B,45 +CPA_M70,CPA_C20C,11 +CPA_M70,CPA_C21,484 +CPA_M70,CPA_C22,143 +CPA_M70,CPA_C235_6,2 +CPA_M70,CPA_C23OTHER,2 +CPA_M70,CPA_C241_3,8 +CPA_M70,CPA_C244_5,3 +CPA_M70,CPA_C25,36 +CPA_M70,CPA_C26,125 +CPA_M70,CPA_C27,5 +CPA_M70,CPA_C28,135 +CPA_M70,CPA_C29,685 +CPA_M70,CPA_C303,100 +CPA_M70,CPA_C30OTHER,9 +CPA_M70,CPA_C31,4 +CPA_M70,CPA_C32,378 +CPA_M70,CPA_C3316,1 +CPA_M70,CPA_C33OTHER,141 +CPA_M70,CPA_D351,4152 +CPA_M70,CPA_D352_3,1643 +CPA_M70,CPA_E36,5 +CPA_M70,CPA_E37,12 +CPA_M70,CPA_E38,100 +CPA_M70,"CPA_F41, F42 & F43",290 +CPA_M70,CPA_G45,184 +CPA_M70,CPA_G46,2048 +CPA_M70,CPA_G47,3593 +CPA_M70,CPA_H491_2,401 +CPA_M70,CPA_H493_5,480 +CPA_M70,CPA_H50,53 +CPA_M70,CPA_H51,232 +CPA_M70,CPA_H52,551 +CPA_M70,CPA_H53,238 +CPA_M70,CPA_I55,140 +CPA_M70,CPA_I56,284 +CPA_M70,CPA_J58,307 +CPA_M70,CPA_J59 & J60,1134 +CPA_M70,CPA_J61,1933 +CPA_M70,CPA_J62,8296 +CPA_M70,CPA_J63,4725 +CPA_M70,CPA_K64,14902 +CPA_M70,CPA_K65.1-2 & K65.3,655 +CPA_M70,CPA_K66,592 +CPA_M70,CPA_L68BXL683,828 +CPA_M70,CPA_L683,625 +CPA_M70,CPA_M691,462 +CPA_M70,CPA_M692,378 +CPA_M70,CPA_M70,13521 +CPA_M70,CPA_M71,531 +CPA_M70,CPA_M72,1079 +CPA_M70,CPA_M73,838 +CPA_M70,CPA_M74,602 +CPA_M70,CPA_N77,377 +CPA_M70,CPA_N78,666 +CPA_M70,CPA_N79,487 +CPA_M70,CPA_N80,15 +CPA_M70,CPA_N81,28 +CPA_M70,CPA_N82,995 +CPA_M70,CPA_O84,2316 +CPA_M70,CPA_P85,1928 +CPA_M70,CPA_Q86,57 +CPA_M70,CPA_Q87 & Q88,147 +CPA_M70,CPA_R90,230 +CPA_M70,CPA_R91,86 +CPA_M70,CPA_R92,664 +CPA_M70,CPA_R93,813 +CPA_M70,CPA_S94,15 +CPA_M70,CPA_S95,17 +CPA_M70,CPA_S96,53 +CPA_M71,CPA_A01,148 +CPA_M71,CPA_A03,4 +CPA_M71,CPA_B05 & B06,610 +CPA_M71,CPA_B07 & B08,18 +CPA_M71,CPA_B09,144 +CPA_M71,CPA_C101,64 +CPA_M71,CPA_C102_3,25 +CPA_M71,CPA_C104,15 +CPA_M71,CPA_C105,25 +CPA_M71,CPA_C106,35 +CPA_M71,CPA_C107,18 +CPA_M71,CPA_C108,95 +CPA_M71,CPA_C109,5 +CPA_M71,CPA_C11.01-6 & C12,19 +CPA_M71,CPA_C1107,36 +CPA_M71,CPA_C13,80 +CPA_M71,CPA_C14,1 +CPA_M71,CPA_C15,2 +CPA_M71,CPA_C16,10 +CPA_M71,CPA_C17,16 +CPA_M71,CPA_C19,264 +CPA_M71,CPA_C203,10 +CPA_M71,CPA_C204,30 +CPA_M71,CPA_C205,18 +CPA_M71,CPA_C20A,29 +CPA_M71,CPA_C20B,140 +CPA_M71,CPA_C20C,5 +CPA_M71,CPA_C21,603 +CPA_M71,CPA_C22,21 +CPA_M71,CPA_C235_6,146 +CPA_M71,CPA_C23OTHER,18 +CPA_M71,CPA_C241_3,36 +CPA_M71,CPA_C244_5,42 +CPA_M71,CPA_C25,329 +CPA_M71,CPA_C26,159 +CPA_M71,CPA_C27,254 +CPA_M71,CPA_C28,370 +CPA_M71,CPA_C29,254 +CPA_M71,CPA_C301,8 +CPA_M71,CPA_C303,703 +CPA_M71,CPA_C30OTHER,81 +CPA_M71,CPA_C31,6 +CPA_M71,CPA_C32,19 +CPA_M71,CPA_C3315,2 +CPA_M71,CPA_C3316,6 +CPA_M71,CPA_C33OTHER,142 +CPA_M71,CPA_D351,770 +CPA_M71,CPA_D352_3,40 +CPA_M71,CPA_E36,275 +CPA_M71,CPA_E37,4 +CPA_M71,CPA_E38,335 +CPA_M71,CPA_E39,13 +CPA_M71,"CPA_F41, F42 & F43",7158 +CPA_M71,CPA_G45,93 +CPA_M71,CPA_G46,284 +CPA_M71,CPA_G47,439 +CPA_M71,CPA_H491_2,10 +CPA_M71,CPA_H493_5,37 +CPA_M71,CPA_H50,93 +CPA_M71,CPA_H51,23 +CPA_M71,CPA_H52,182 +CPA_M71,CPA_I55,54 +CPA_M71,CPA_I56,15 +CPA_M71,CPA_J58,7 +CPA_M71,CPA_J59 & J60,207 +CPA_M71,CPA_J61,177 +CPA_M71,CPA_J62,27 +CPA_M71,CPA_J63,29 +CPA_M71,CPA_K64,1834 +CPA_M71,CPA_K65.1-2 & K65.3,351 +CPA_M71,CPA_K66,204 +CPA_M71,CPA_L68BXL683,158 +CPA_M71,CPA_L68A,2660 +CPA_M71,CPA_L683,107 +CPA_M71,CPA_M691,106 +CPA_M71,CPA_M70,297 +CPA_M71,CPA_M71,17647 +CPA_M71,CPA_M72,35 +CPA_M71,CPA_M74,137 +CPA_M71,CPA_M75,1 +CPA_M71,CPA_N77,33 +CPA_M71,CPA_N78,151 +CPA_M71,CPA_N79,68 +CPA_M71,CPA_N80,1 +CPA_M71,CPA_N81,32 +CPA_M71,CPA_N82,78 +CPA_M71,CPA_O84,1661 +CPA_M71,CPA_P85,357 +CPA_M71,CPA_Q86,3155 +CPA_M71,CPA_Q87 & Q88,224 +CPA_M71,CPA_R90,62 +CPA_M71,CPA_R91,5 +CPA_M71,CPA_R93,222 +CPA_M71,CPA_S94,142 +CPA_M71,CPA_S96,11 +CPA_M72,CPA_K65.1-2 & K65.3,62 +CPA_M72,CPA_M72,8605 +CPA_M73,CPA_A01,71 +CPA_M73,CPA_A02,10 +CPA_M73,CPA_A03,5 +CPA_M73,CPA_B05 & B06,30 +CPA_M73,CPA_B07 & B08,9 +CPA_M73,CPA_B09,5 +CPA_M73,CPA_C101,41 +CPA_M73,CPA_C102_3,117 +CPA_M73,CPA_C104,18 +CPA_M73,CPA_C105,85 +CPA_M73,CPA_C106,9 +CPA_M73,CPA_C107,40 +CPA_M73,CPA_C108,38 +CPA_M73,CPA_C109,78 +CPA_M73,CPA_C11.01-6 & C12,258 +CPA_M73,CPA_C1107,190 +CPA_M73,CPA_C13,90 +CPA_M73,CPA_C14,55 +CPA_M73,CPA_C15,43 +CPA_M73,CPA_C16,27 +CPA_M73,CPA_C17,67 +CPA_M73,CPA_C18,66 +CPA_M73,CPA_C19,12 +CPA_M73,CPA_C203,74 +CPA_M73,CPA_C204,195 +CPA_M73,CPA_C205,12 +CPA_M73,CPA_C20A,9 +CPA_M73,CPA_C20B,11 +CPA_M73,CPA_C20C,6 +CPA_M73,CPA_C21,259 +CPA_M73,CPA_C22,28 +CPA_M73,CPA_C235_6,29 +CPA_M73,CPA_C23OTHER,37 +CPA_M73,CPA_C241_3,10 +CPA_M73,CPA_C244_5,5 +CPA_M73,CPA_C25,135 +CPA_M73,CPA_C26,100 +CPA_M73,CPA_C27,73 +CPA_M73,CPA_C28,123 +CPA_M73,CPA_C29,490 +CPA_M73,CPA_C301,12 +CPA_M73,CPA_C303,17 +CPA_M73,CPA_C30OTHER,21 +CPA_M73,CPA_C31,74 +CPA_M73,CPA_C32,131 +CPA_M73,CPA_C3315,3 +CPA_M73,CPA_C3316,8 +CPA_M73,CPA_C33OTHER,64 +CPA_M73,CPA_D351,147 +CPA_M73,CPA_D352_3,15 +CPA_M73,CPA_E36,14 +CPA_M73,CPA_E37,46 +CPA_M73,CPA_E38,92 +CPA_M73,CPA_E39,10 +CPA_M73,"CPA_F41, F42 & F43",718 +CPA_M73,CPA_G45,1529 +CPA_M73,CPA_G46,3066 +CPA_M73,CPA_G47,6526 +CPA_M73,CPA_H491_2,235 +CPA_M73,CPA_H493_5,189 +CPA_M73,CPA_H50,131 +CPA_M73,CPA_H51,268 +CPA_M73,CPA_H52,206 +CPA_M73,CPA_H53,45 +CPA_M73,CPA_I55,484 +CPA_M73,CPA_I56,685 +CPA_M73,CPA_J58,578 +CPA_M73,CPA_J59 & J60,2114 +CPA_M73,CPA_J61,773 +CPA_M73,CPA_J62,1211 +CPA_M73,CPA_J63,931 +CPA_M73,CPA_K64,2752 +CPA_M73,CPA_K65.1-2 & K65.3,1179 +CPA_M73,CPA_K66,345 +CPA_M73,CPA_L68BXL683,355 +CPA_M73,CPA_L68A,369 +CPA_M73,CPA_L683,311 +CPA_M73,CPA_M691,523 +CPA_M73,CPA_M692,153 +CPA_M73,CPA_M70,640 +CPA_M73,CPA_M71,263 +CPA_M73,CPA_M72,245 +CPA_M73,CPA_M73,4690 +CPA_M73,CPA_M74,255 +CPA_M73,CPA_M75,68 +CPA_M73,CPA_N77,191 +CPA_M73,CPA_N78,467 +CPA_M73,CPA_N79,463 +CPA_M73,CPA_N80,46 +CPA_M73,CPA_N81,134 +CPA_M73,CPA_N82,712 +CPA_M73,CPA_O84,2004 +CPA_M73,CPA_P85,934 +CPA_M73,CPA_Q86,378 +CPA_M73,CPA_Q87 & Q88,487 +CPA_M73,CPA_R90,377 +CPA_M73,CPA_R91,83 +CPA_M73,CPA_R92,360 +CPA_M73,CPA_R93,302 +CPA_M73,CPA_S94,333 +CPA_M73,CPA_S95,36 +CPA_M73,CPA_S96,119 +CPA_M74,CPA_A01,108 +CPA_M74,CPA_B05 & B06,4 +CPA_M74,CPA_B07 & B08,3 +CPA_M74,CPA_B09,2 +CPA_M74,CPA_C101,51 +CPA_M74,CPA_C102_3,288 +CPA_M74,CPA_C104,17 +CPA_M74,CPA_C105,10 +CPA_M74,CPA_C106,18 +CPA_M74,CPA_C107,48 +CPA_M74,CPA_C108,144 +CPA_M74,CPA_C109,441 +CPA_M74,CPA_C11.01-6 & C12,42 +CPA_M74,CPA_C1107,25 +CPA_M74,CPA_C13,16 +CPA_M74,CPA_C14,18 +CPA_M74,CPA_C15,6 +CPA_M74,CPA_C16,1 +CPA_M74,CPA_C17,4 +CPA_M74,CPA_C18,17 +CPA_M74,CPA_C19,6 +CPA_M74,CPA_C203,4 +CPA_M74,CPA_C204,19 +CPA_M74,CPA_C205,2 +CPA_M74,CPA_C20A,4 +CPA_M74,CPA_C20B,8 +CPA_M74,CPA_C20C,6 +CPA_M74,CPA_C21,95 +CPA_M74,CPA_C22,12 +CPA_M74,CPA_C235_6,14 +CPA_M74,CPA_C23OTHER,35 +CPA_M74,CPA_C241_3,1 +CPA_M74,CPA_C244_5,3 +CPA_M74,CPA_C25,86 +CPA_M74,CPA_C26,79 +CPA_M74,CPA_C27,74 +CPA_M74,CPA_C28,36 +CPA_M74,CPA_C29,22 +CPA_M74,CPA_C301,210 +CPA_M74,CPA_C303,38 +CPA_M74,CPA_C30OTHER,24 +CPA_M74,CPA_C31,81 +CPA_M74,CPA_C32,56 +CPA_M74,CPA_C3316,2 +CPA_M74,CPA_C33OTHER,4 +CPA_M74,CPA_D351,75 +CPA_M74,CPA_E36,20 +CPA_M74,CPA_E37,2 +CPA_M74,CPA_E38,169 +CPA_M74,"CPA_F41, F42 & F43",77 +CPA_M74,CPA_G45,420 +CPA_M74,CPA_G46,1122 +CPA_M74,CPA_G47,548 +CPA_M74,CPA_H491_2,5 +CPA_M74,CPA_H493_5,231 +CPA_M74,CPA_H50,49 +CPA_M74,CPA_H51,4 +CPA_M74,CPA_H52,76 +CPA_M74,CPA_I55,47 +CPA_M74,CPA_I56,36 +CPA_M74,CPA_J58,309 +CPA_M74,CPA_J59 & J60,1568 +CPA_M74,CPA_J61,11 +CPA_M74,CPA_J62,328 +CPA_M74,CPA_J63,236 +CPA_M74,CPA_K64,833 +CPA_M74,CPA_K65.1-2 & K65.3,1671 +CPA_M74,CPA_K66,171 +CPA_M74,CPA_L68BXL683,41 +CPA_M74,CPA_L683,65 +CPA_M74,CPA_M691,13 +CPA_M74,CPA_M692,100 +CPA_M74,CPA_M70,283 +CPA_M74,CPA_M71,36 +CPA_M74,CPA_M72,968 +CPA_M74,CPA_M73,749 +CPA_M74,CPA_M74,8450 +CPA_M74,CPA_M75,2 +CPA_M74,CPA_N77,276 +CPA_M74,CPA_N78,14 +CPA_M74,CPA_N79,49 +CPA_M74,CPA_N80,3 +CPA_M74,CPA_N81,29 +CPA_M74,CPA_N82,604 +CPA_M74,CPA_O84,921 +CPA_M74,CPA_P85,770 +CPA_M74,CPA_Q86,803 +CPA_M74,CPA_Q87 & Q88,242 +CPA_M74,CPA_R90,481 +CPA_M74,CPA_R91,23 +CPA_M74,CPA_R93,145 +CPA_M74,CPA_S94,302 +CPA_M74,CPA_S95,9 +CPA_M74,CPA_S96,32 +CPA_M75,CPA_A01,304 +CPA_M75,CPA_A03,10 +CPA_M75,CPA_J59 & J60,6 +CPA_M75,CPA_L68BXL683,4 +CPA_M75,CPA_M75,164 +CPA_M75,CPA_O84,8 +CPA_N77,CPA_A01,450 +CPA_N77,CPA_A02,25 +CPA_N77,CPA_A03,46 +CPA_N77,CPA_B05 & B06,181 +CPA_N77,CPA_B07 & B08,165 +CPA_N77,CPA_B09,140 +CPA_N77,CPA_C101,86 +CPA_N77,CPA_C102_3,53 +CPA_N77,CPA_C104,11 +CPA_N77,CPA_C105,39 +CPA_N77,CPA_C106,18 +CPA_N77,CPA_C107,64 +CPA_N77,CPA_C108,74 +CPA_N77,CPA_C109,31 +CPA_N77,CPA_C11.01-6 & C12,324 +CPA_N77,CPA_C1107,38 +CPA_N77,CPA_C13,11 +CPA_N77,CPA_C14,6 +CPA_N77,CPA_C15,3 +CPA_N77,CPA_C16,60 +CPA_N77,CPA_C17,78 +CPA_N77,CPA_C18,47 +CPA_N77,CPA_C19,21 +CPA_N77,CPA_C203,35 +CPA_N77,CPA_C204,23 +CPA_N77,CPA_C205,21 +CPA_N77,CPA_C20A,29 +CPA_N77,CPA_C20B,31 +CPA_N77,CPA_C20C,11 +CPA_N77,CPA_C21,9940 +CPA_N77,CPA_C22,119 +CPA_N77,CPA_C235_6,42 +CPA_N77,CPA_C23OTHER,52 +CPA_N77,CPA_C241_3,85 +CPA_N77,CPA_C244_5,21 +CPA_N77,CPA_C25,315 +CPA_N77,CPA_C26,56 +CPA_N77,CPA_C27,61 +CPA_N77,CPA_C28,146 +CPA_N77,CPA_C29,118 +CPA_N77,CPA_C301,55 +CPA_N77,CPA_C303,36 +CPA_N77,CPA_C30OTHER,15 +CPA_N77,CPA_C31,36 +CPA_N77,CPA_C32,40 +CPA_N77,CPA_C3315,4 +CPA_N77,CPA_C3316,63 +CPA_N77,CPA_C33OTHER,308 +CPA_N77,CPA_D351,266 +CPA_N77,CPA_D352_3,243 +CPA_N77,CPA_E36,123 +CPA_N77,CPA_E37,72 +CPA_N77,CPA_E38,864 +CPA_N77,CPA_E39,69 +CPA_N77,"CPA_F41, F42 & F43",8196 +CPA_N77,CPA_G45,511 +CPA_N77,CPA_G46,2364 +CPA_N77,CPA_G47,978 +CPA_N77,CPA_H491_2,2025 +CPA_N77,CPA_H493_5,1587 +CPA_N77,CPA_H50,324 +CPA_N77,CPA_H51,2453 +CPA_N77,CPA_H52,1512 +CPA_N77,CPA_H53,519 +CPA_N77,CPA_I55,104 +CPA_N77,CPA_I56,497 +CPA_N77,CPA_J58,104 +CPA_N77,CPA_J59 & J60,547 +CPA_N77,CPA_J61,821 +CPA_N77,CPA_J62,476 +CPA_N77,CPA_J63,91 +CPA_N77,CPA_K64,153 +CPA_N77,CPA_K65.1-2 & K65.3,69 +CPA_N77,CPA_K66,183 +CPA_N77,CPA_L68BXL683,331 +CPA_N77,CPA_L68A,1529 +CPA_N77,CPA_L683,185 +CPA_N77,CPA_M691,216 +CPA_N77,CPA_M692,69 +CPA_N77,CPA_M70,612 +CPA_N77,CPA_M71,1019 +CPA_N77,CPA_M72,55 +CPA_N77,CPA_M73,83 +CPA_N77,CPA_M74,84 +CPA_N77,CPA_M75,45 +CPA_N77,CPA_N77,2044 +CPA_N77,CPA_N78,193 +CPA_N77,CPA_N79,810 +CPA_N77,CPA_N80,50 +CPA_N77,CPA_N81,574 +CPA_N77,CPA_N82,374 +CPA_N77,CPA_O84,278 +CPA_N77,CPA_P85,1855 +CPA_N77,CPA_Q86,1688 +CPA_N77,CPA_Q87 & Q88,490 +CPA_N77,CPA_R90,204 +CPA_N77,CPA_R91,26 +CPA_N77,CPA_R92,122 +CPA_N77,CPA_R93,303 +CPA_N77,CPA_S94,75 +CPA_N77,CPA_S95,61 +CPA_N77,CPA_S96,179 +CPA_N78,CPA_A01,191 +CPA_N78,CPA_A02,7 +CPA_N78,CPA_A03,6 +CPA_N78,CPA_B05 & B06,344 +CPA_N78,CPA_B07 & B08,27 +CPA_N78,CPA_B09,58 +CPA_N78,CPA_C101,387 +CPA_N78,CPA_C102_3,251 +CPA_N78,CPA_C104,17 +CPA_N78,CPA_C105,53 +CPA_N78,CPA_C106,41 +CPA_N78,CPA_C107,270 +CPA_N78,CPA_C108,341 +CPA_N78,CPA_C109,38 +CPA_N78,CPA_C11.01-6 & C12,108 +CPA_N78,CPA_C1107,34 +CPA_N78,CPA_C13,29 +CPA_N78,CPA_C14,14 +CPA_N78,CPA_C15,4 +CPA_N78,CPA_C16,65 +CPA_N78,CPA_C17,53 +CPA_N78,CPA_C18,111 +CPA_N78,CPA_C19,38 +CPA_N78,CPA_C203,35 +CPA_N78,CPA_C204,88 +CPA_N78,CPA_C205,29 +CPA_N78,CPA_C20A,41 +CPA_N78,CPA_C20B,47 +CPA_N78,CPA_C20C,19 +CPA_N78,CPA_C21,242 +CPA_N78,CPA_C22,204 +CPA_N78,CPA_C235_6,155 +CPA_N78,CPA_C23OTHER,23 +CPA_N78,CPA_C241_3,28 +CPA_N78,CPA_C244_5,49 +CPA_N78,CPA_C25,325 +CPA_N78,CPA_C26,119 +CPA_N78,CPA_C27,102 +CPA_N78,CPA_C28,406 +CPA_N78,CPA_C29,466 +CPA_N78,CPA_C301,184 +CPA_N78,CPA_C303,124 +CPA_N78,CPA_C30OTHER,39 +CPA_N78,CPA_C31,68 +CPA_N78,CPA_C32,97 +CPA_N78,CPA_C3315,49 +CPA_N78,CPA_C3316,15 +CPA_N78,CPA_C33OTHER,108 +CPA_N78,CPA_D351,282 +CPA_N78,CPA_D352_3,79 +CPA_N78,CPA_E36,127 +CPA_N78,CPA_E37,93 +CPA_N78,CPA_E38,311 +CPA_N78,CPA_E39,12 +CPA_N78,"CPA_F41, F42 & F43",3479 +CPA_N78,CPA_G45,255 +CPA_N78,CPA_G46,1852 +CPA_N78,CPA_G47,2331 +CPA_N78,CPA_H491_2,136 +CPA_N78,CPA_H493_5,1729 +CPA_N78,CPA_H50,1030 +CPA_N78,CPA_H51,24 +CPA_N78,CPA_H52,1899 +CPA_N78,CPA_H53,536 +CPA_N78,CPA_I55,312 +CPA_N78,CPA_I56,529 +CPA_N78,CPA_J58,175 +CPA_N78,CPA_J59 & J60,187 +CPA_N78,CPA_J61,297 +CPA_N78,CPA_J62,1111 +CPA_N78,CPA_J63,131 +CPA_N78,CPA_K64,2556 +CPA_N78,CPA_K65.1-2 & K65.3,510 +CPA_N78,CPA_K66,525 +CPA_N78,CPA_L68BXL683,409 +CPA_N78,CPA_L683,176 +CPA_N78,CPA_M691,467 +CPA_N78,CPA_M692,405 +CPA_N78,CPA_M70,513 +CPA_N78,CPA_M71,568 +CPA_N78,CPA_M72,299 +CPA_N78,CPA_M73,293 +CPA_N78,CPA_M74,207 +CPA_N78,CPA_M75,17 +CPA_N78,CPA_N77,138 +CPA_N78,CPA_N78,17274 +CPA_N78,CPA_N79,217 +CPA_N78,CPA_N80,89 +CPA_N78,CPA_N81,368 +CPA_N78,CPA_N82,469 +CPA_N78,CPA_O84,1354 +CPA_N78,CPA_P85,1856 +CPA_N78,CPA_Q86,5307 +CPA_N78,CPA_Q87 & Q88,2573 +CPA_N78,CPA_R90,47 +CPA_N78,CPA_R91,52 +CPA_N78,CPA_R92,27 +CPA_N78,CPA_R93,178 +CPA_N78,CPA_S94,132 +CPA_N78,CPA_S95,96 +CPA_N78,CPA_S96,219 +CPA_N79,CPA_C29,76 +CPA_N79,CPA_C303,53 +CPA_N79,CPA_C33OTHER,6 +CPA_N79,CPA_D351,2 +CPA_N79,CPA_G45,9 +CPA_N79,CPA_G47,40 +CPA_N79,CPA_H491_2,6 +CPA_N79,CPA_H493_5,8 +CPA_N79,CPA_H50,1306 +CPA_N79,CPA_H51,148 +CPA_N79,CPA_H52,282 +CPA_N79,CPA_I55,1020 +CPA_N79,CPA_I56,61 +CPA_N79,CPA_J59 & J60,76 +CPA_N79,CPA_J61,41 +CPA_N79,CPA_K64,820 +CPA_N79,CPA_K66,492 +CPA_N79,CPA_L68BXL683,4 +CPA_N79,CPA_L683,26 +CPA_N79,CPA_M692,47 +CPA_N79,CPA_M70,262 +CPA_N79,CPA_N78,31 +CPA_N79,CPA_N79,3418 +CPA_N79,CPA_O84,321 +CPA_N79,CPA_P85,1006 +CPA_N79,CPA_Q86,88 +CPA_N80,CPA_E37,3 +CPA_N80,CPA_E38,165 +CPA_N80,"CPA_F41, F42 & F43",1345 +CPA_N80,CPA_H491_2,1 +CPA_N80,CPA_H51,31 +CPA_N80,CPA_H52,9 +CPA_N80,CPA_H53,18 +CPA_N80,CPA_J59 & J60,72 +CPA_N80,CPA_J62,12 +CPA_N80,CPA_J63,102 +CPA_N80,CPA_K64,1736 +CPA_N80,CPA_K65.1-2 & K65.3,7 +CPA_N80,CPA_K66,33 +CPA_N80,CPA_L68BXL683,125 +CPA_N80,CPA_L68A,15 +CPA_N80,CPA_M72,13 +CPA_N80,CPA_M74,29 +CPA_N80,CPA_N80,2660 +CPA_N80,CPA_N82,16 +CPA_N80,CPA_O84,780 +CPA_N80,CPA_P85,534 +CPA_N80,CPA_Q86,577 +CPA_N80,CPA_Q87 & Q88,283 +CPA_N80,CPA_R90,106 +CPA_N80,CPA_R91,29 +CPA_N80,CPA_R93,70 +CPA_N80,CPA_S95,2 +CPA_N81,CPA_C33OTHER,21 +CPA_N81,CPA_D351,189 +CPA_N81,CPA_D352_3,106 +CPA_N81,CPA_E38,240 +CPA_N81,CPA_E39,6 +CPA_N81,"CPA_F41, F42 & F43",915 +CPA_N81,CPA_G46,985 +CPA_N81,CPA_H493_5,79 +CPA_N81,CPA_H51,219 +CPA_N81,CPA_H52,395 +CPA_N81,CPA_H53,19 +CPA_N81,CPA_I55,674 +CPA_N81,CPA_I56,586 +CPA_N81,CPA_J59 & J60,575 +CPA_N81,CPA_J62,820 +CPA_N81,CPA_J63,192 +CPA_N81,CPA_K64,952 +CPA_N81,CPA_K65.1-2 & K65.3,256 +CPA_N81,CPA_K66,357 +CPA_N81,CPA_L68BXL683,1175 +CPA_N81,CPA_L68A,3846 +CPA_N81,CPA_L683,823 +CPA_N81,CPA_M691,354 +CPA_N81,CPA_M70,1125 +CPA_N81,CPA_M71,208 +CPA_N81,CPA_M72,104 +CPA_N81,CPA_M74,111 +CPA_N81,CPA_M75,22 +CPA_N81,CPA_N77,149 +CPA_N81,CPA_N80,44 +CPA_N81,CPA_N81,9853 +CPA_N81,CPA_N82,35 +CPA_N81,CPA_O84,891 +CPA_N81,CPA_P85,1656 +CPA_N81,CPA_Q86,1592 +CPA_N81,CPA_Q87 & Q88,826 +CPA_N81,CPA_R90,69 +CPA_N81,CPA_R91,247 +CPA_N81,CPA_R92,339 +CPA_N81,CPA_R93,868 +CPA_N81,CPA_S94,399 +CPA_N81,CPA_S95,50 +CPA_N81,CPA_S96,29 +CPA_N82,CPA_B05 & B06,6 +CPA_N82,CPA_B09,159 +CPA_N82,CPA_C105,3 +CPA_N82,CPA_C106,1 +CPA_N82,CPA_C108,2 +CPA_N82,CPA_C109,1 +CPA_N82,CPA_C14,1 +CPA_N82,CPA_C19,12 +CPA_N82,CPA_C203,1 +CPA_N82,CPA_C204,2 +CPA_N82,CPA_C20B,36 +CPA_N82,CPA_C21,504 +CPA_N82,CPA_C22,232 +CPA_N82,CPA_C235_6,2 +CPA_N82,CPA_C23OTHER,70 +CPA_N82,CPA_C244_5,3 +CPA_N82,CPA_C26,20 +CPA_N82,CPA_C27,78 +CPA_N82,CPA_C28,365 +CPA_N82,CPA_C29,389 +CPA_N82,CPA_C30OTHER,13 +CPA_N82,CPA_C31,3 +CPA_N82,CPA_C33OTHER,62 +CPA_N82,CPA_D351,263 +CPA_N82,CPA_D352_3,165 +CPA_N82,CPA_E38,338 +CPA_N82,CPA_E39,1 +CPA_N82,"CPA_F41, F42 & F43",122 +CPA_N82,CPA_G45,325 +CPA_N82,CPA_G46,1620 +CPA_N82,CPA_G47,817 +CPA_N82,CPA_H491_2,31 +CPA_N82,CPA_H493_5,309 +CPA_N82,CPA_H51,47 +CPA_N82,CPA_H52,519 +CPA_N82,CPA_H53,26 +CPA_N82,CPA_I55,54 +CPA_N82,CPA_I56,106 +CPA_N82,CPA_J58,6 +CPA_N82,CPA_J59 & J60,521 +CPA_N82,CPA_J61,2228 +CPA_N82,CPA_J62,5988 +CPA_N82,CPA_J63,241 +CPA_N82,CPA_K64,7230 +CPA_N82,CPA_K65.1-2 & K65.3,361 +CPA_N82,CPA_K66,494 +CPA_N82,CPA_L68BXL683,100 +CPA_N82,CPA_L683,118 +CPA_N82,CPA_M691,369 +CPA_N82,CPA_M692,119 +CPA_N82,CPA_M70,2031 +CPA_N82,CPA_M71,127 +CPA_N82,CPA_M72,121 +CPA_N82,CPA_M73,538 +CPA_N82,CPA_M74,73 +CPA_N82,CPA_M75,69 +CPA_N82,CPA_N77,160 +CPA_N82,CPA_N78,104 +CPA_N82,CPA_N79,180 +CPA_N82,CPA_N80,21 +CPA_N82,CPA_N81,97 +CPA_N82,CPA_N82,9653 +CPA_N82,CPA_O84,1801 +CPA_N82,CPA_P85,1479 +CPA_N82,CPA_Q86,1117 +CPA_N82,CPA_Q87 & Q88,449 +CPA_N82,CPA_R90,67 +CPA_N82,CPA_R91,43 +CPA_N82,CPA_R92,27 +CPA_N82,CPA_R93,219 +CPA_N82,CPA_S94,266 +CPA_N82,CPA_S95,18 +CPA_N82,CPA_S96,153 +CPA_O84,CPA_A01,10 +CPA_O84,CPA_A02,2 +CPA_O84,CPA_B05 & B06,2 +CPA_O84,CPA_B07 & B08,1 +CPA_O84,CPA_C101,5 +CPA_O84,CPA_C102_3,15 +CPA_O84,CPA_C104,2 +CPA_O84,CPA_C105,3 +CPA_O84,CPA_C106,11 +CPA_O84,CPA_C107,11 +CPA_O84,CPA_C108,18 +CPA_O84,CPA_C109,6 +CPA_O84,CPA_C11.01-6 & C12,47 +CPA_O84,CPA_C1107,7 +CPA_O84,CPA_C13,15 +CPA_O84,CPA_C14,5 +CPA_O84,CPA_C15,6 +CPA_O84,CPA_C16,1 +CPA_O84,CPA_C17,13 +CPA_O84,CPA_C19,10 +CPA_O84,CPA_C203,16 +CPA_O84,CPA_C204,15 +CPA_O84,CPA_C205,27 +CPA_O84,CPA_C20A,4 +CPA_O84,CPA_C20C,10 +CPA_O84,CPA_C21,18 +CPA_O84,CPA_C22,23 +CPA_O84,CPA_C235_6,2 +CPA_O84,CPA_C23OTHER,6 +CPA_O84,CPA_C241_3,8 +CPA_O84,CPA_C244_5,18 +CPA_O84,CPA_C25,73 +CPA_O84,CPA_C26,11 +CPA_O84,CPA_C27,12 +CPA_O84,CPA_C28,55 +CPA_O84,CPA_C29,71 +CPA_O84,CPA_C301,5 +CPA_O84,CPA_C303,25 +CPA_O84,CPA_C30OTHER,5 +CPA_O84,CPA_C31,15 +CPA_O84,CPA_C32,22 +CPA_O84,CPA_C3315,1 +CPA_O84,CPA_C3316,2 +CPA_O84,CPA_C33OTHER,7 +CPA_O84,CPA_D351,25 +CPA_O84,CPA_D352_3,3 +CPA_O84,CPA_E36,33 +CPA_O84,CPA_E38,102 +CPA_O84,"CPA_F41, F42 & F43",2001 +CPA_O84,CPA_G45,41 +CPA_O84,CPA_G46,100 +CPA_O84,CPA_G47,647 +CPA_O84,CPA_H491_2,360 +CPA_O84,CPA_H493_5,2901 +CPA_O84,CPA_H50,24 +CPA_O84,CPA_H51,140 +CPA_O84,CPA_H52,41 +CPA_O84,CPA_H53,120 +CPA_O84,CPA_I55,24 +CPA_O84,CPA_I56,90 +CPA_O84,CPA_J58,14 +CPA_O84,CPA_J59 & J60,25 +CPA_O84,CPA_J61,23 +CPA_O84,CPA_J62,17 +CPA_O84,CPA_J63,4 +CPA_O84,CPA_K64,133 +CPA_O84,CPA_K65.1-2 & K65.3,15 +CPA_O84,CPA_K66,29 +CPA_O84,CPA_L68BXL683,6726 +CPA_O84,CPA_L68A,10 +CPA_O84,CPA_M691,4 +CPA_O84,CPA_M692,4 +CPA_O84,CPA_M70,181 +CPA_O84,CPA_M71,6520 +CPA_O84,CPA_M72,12 +CPA_O84,CPA_M73,1 +CPA_O84,CPA_M74,12 +CPA_O84,CPA_N77,5 +CPA_O84,CPA_N78,65 +CPA_O84,CPA_N79,1 +CPA_O84,CPA_N80,3 +CPA_O84,CPA_N81,29 +CPA_O84,CPA_N82,157 +CPA_O84,CPA_O84,400 +CPA_O84,CPA_Q86,315 +CPA_O84,CPA_R90,10 +CPA_O84,CPA_R91,2 +CPA_O84,CPA_R92,10 +CPA_O84,CPA_R93,9 +CPA_O84,CPA_S94,7 +CPA_O84,CPA_S95,2 +CPA_O84,CPA_S96,2 +CPA_P85,CPA_C104,1 +CPA_P85,CPA_C105,3 +CPA_P85,CPA_C11.01-6 & C12,12 +CPA_P85,CPA_C13,11 +CPA_P85,CPA_C14,3 +CPA_P85,CPA_C203,5 +CPA_P85,CPA_C204,2 +CPA_P85,CPA_C20B,23 +CPA_P85,CPA_C21,96 +CPA_P85,CPA_C22,11 +CPA_P85,CPA_C23OTHER,7 +CPA_P85,CPA_C244_5,7 +CPA_P85,CPA_C25,11 +CPA_P85,CPA_C26,30 +CPA_P85,CPA_C27,6 +CPA_P85,CPA_C303,15 +CPA_P85,CPA_C32,1 +CPA_P85,CPA_E36,3 +CPA_P85,CPA_E37,4 +CPA_P85,CPA_E38,30 +CPA_P85,CPA_H491_2,2 +CPA_P85,CPA_H493_5,10 +CPA_P85,CPA_H50,5 +CPA_P85,CPA_H51,20 +CPA_P85,CPA_H52,84 +CPA_P85,CPA_H53,29 +CPA_P85,CPA_I56,74 +CPA_P85,CPA_J59 & J60,28 +CPA_P85,CPA_J61,229 +CPA_P85,CPA_J62,1264 +CPA_P85,CPA_K64,1352 +CPA_P85,CPA_K65.1-2 & K65.3,219 +CPA_P85,CPA_K66,210 +CPA_P85,CPA_L68BXL683,136 +CPA_P85,CPA_M691,217 +CPA_P85,CPA_M692,369 +CPA_P85,CPA_M70,432 +CPA_P85,CPA_M71,186 +CPA_P85,CPA_M72,85 +CPA_P85,CPA_M73,92 +CPA_P85,CPA_M74,81 +CPA_P85,CPA_M75,41 +CPA_P85,CPA_N78,207 +CPA_P85,CPA_N79,99 +CPA_P85,CPA_N80,14 +CPA_P85,CPA_N82,150 +CPA_P85,CPA_O84,7432 +CPA_P85,CPA_P85,17183 +CPA_P85,CPA_Q86,229 +CPA_P85,CPA_Q87 & Q88,949 +CPA_P85,CPA_R93,7 +CPA_P85,CPA_S94,9 +CPA_P85,CPA_S95,14 +CPA_P85,CPA_S96,47 +CPA_Q86,CPA_B05 & B06,9 +CPA_Q86,CPA_C11.01-6 & C12,13 +CPA_Q86,CPA_C21,19 +CPA_Q86,CPA_C22,3 +CPA_Q86,CPA_C23OTHER,5 +CPA_Q86,CPA_C244_5,2 +CPA_Q86,CPA_C25,13 +CPA_Q86,CPA_C26,59 +CPA_Q86,CPA_C27,5 +CPA_Q86,CPA_E36,6 +CPA_Q86,CPA_E38,16 +CPA_Q86,CPA_J59 & J60,6 +CPA_Q86,CPA_K64,57 +CPA_Q86,CPA_K65.1-2 & K65.3,126 +CPA_Q86,CPA_K66,8 +CPA_Q86,CPA_N78,58 +CPA_Q86,CPA_O84,287 +CPA_Q86,CPA_Q86,3929 +CPA_Q86,CPA_R93,39 +CPA_Q87 & Q88,CPA_C22,1 +CPA_Q87 & Q88,CPA_E36,2 +CPA_Q87 & Q88,CPA_H52,1 +CPA_Q87 & Q88,CPA_K64,8 +CPA_Q87 & Q88,CPA_K65.1-2 & K65.3,3 +CPA_Q87 & Q88,CPA_O84,20 +CPA_Q87 & Q88,CPA_Q86,2055 +CPA_Q87 & Q88,CPA_Q87 & Q88,15554 +CPA_R90,CPA_E38,28 +CPA_R90,CPA_J58,90 +CPA_R90,CPA_J59 & J60,944 +CPA_R90,CPA_K64,39 +CPA_R90,CPA_K66,9 +CPA_R90,CPA_N82,60 +CPA_R90,CPA_O84,395 +CPA_R90,CPA_P85,101 +CPA_R90,CPA_Q86,36 +CPA_R90,CPA_Q87 & Q88,103 +CPA_R90,CPA_R90,4952 +CPA_R90,CPA_R91,68 +CPA_R90,CPA_R93,602 +CPA_R91,CPA_E38,16 +CPA_R91,CPA_J59 & J60,5 +CPA_R91,CPA_K65.1-2 & K65.3,4 +CPA_R91,CPA_L68BXL683,9 +CPA_R91,CPA_O84,373 +CPA_R91,CPA_P85,74 +CPA_R91,CPA_Q86,103 +CPA_R91,CPA_Q87 & Q88,38 +CPA_R91,CPA_R90,28 +CPA_R91,CPA_R91,286 +CPA_R91,CPA_R93,202 +CPA_R92,CPA_I55,10 +CPA_R92,CPA_K64,568 +CPA_R92,CPA_L68BXL683,8 +CPA_R92,CPA_R92,1134 +CPA_R92,CPA_R93,21 +CPA_R93,CPA_A01,21 +CPA_R93,CPA_C106,3 +CPA_R93,CPA_C107,16 +CPA_R93,CPA_C108,34 +CPA_R93,CPA_C11.01-6 & C12,97 +CPA_R93,CPA_C204,24 +CPA_R93,CPA_C205,2 +CPA_R93,CPA_C20B,2 +CPA_R93,CPA_C21,60 +CPA_R93,CPA_C22,9 +CPA_R93,CPA_C28,9 +CPA_R93,CPA_C29,74 +CPA_R93,CPA_D351,19 +CPA_R93,CPA_E36,1 +CPA_R93,CPA_E38,24 +CPA_R93,"CPA_F41, F42 & F43",93 +CPA_R93,CPA_G45,201 +CPA_R93,CPA_G46,650 +CPA_R93,CPA_G47,855 +CPA_R93,CPA_H51,53 +CPA_R93,CPA_H52,32 +CPA_R93,CPA_I55,75 +CPA_R93,CPA_I56,120 +CPA_R93,CPA_J58,77 +CPA_R93,CPA_J59 & J60,469 +CPA_R93,CPA_J61,103 +CPA_R93,CPA_J62,304 +CPA_R93,CPA_J63,66 +CPA_R93,CPA_K64,68 +CPA_R93,CPA_K65.1-2 & K65.3,32 +CPA_R93,CPA_K66,9 +CPA_R93,CPA_L68BXL683,24 +CPA_R93,CPA_L683,53 +CPA_R93,CPA_M691,49 +CPA_R93,CPA_M692,14 +CPA_R93,CPA_M70,193 +CPA_R93,CPA_M71,31 +CPA_R93,CPA_M72,40 +CPA_R93,CPA_M73,616 +CPA_R93,CPA_M74,35 +CPA_R93,CPA_N77,40 +CPA_R93,CPA_N78,120 +CPA_R93,CPA_N79,170 +CPA_R93,CPA_N82,107 +CPA_R93,CPA_O84,230 +CPA_R93,CPA_P85,175 +CPA_R93,CPA_Q86,32 +CPA_R93,CPA_Q87 & Q88,46 +CPA_R93,CPA_R90,34 +CPA_R93,CPA_R91,31 +CPA_R93,CPA_R92,100 +CPA_R93,CPA_R93,2209 +CPA_R93,CPA_S94,70 +CPA_R93,CPA_S96,40 +CPA_S94,CPA_A02,4 +CPA_S94,CPA_C101,2 +CPA_S94,CPA_C108,1 +CPA_S94,CPA_C203,1 +CPA_S94,CPA_C205,2 +CPA_S94,CPA_C21,3 +CPA_S94,CPA_C22,2 +CPA_S94,CPA_C244_5,1 +CPA_S94,CPA_C25,8 +CPA_S94,CPA_C26,7 +CPA_S94,CPA_C27,1 +CPA_S94,CPA_C33OTHER,2 +CPA_S94,CPA_E36,1 +CPA_S94,CPA_E38,2 +CPA_S94,CPA_G46,2 +CPA_S94,CPA_G47,5 +CPA_S94,CPA_H51,2 +CPA_S94,CPA_H52,16 +CPA_S94,CPA_J58,13 +CPA_S94,CPA_J59 & J60,243 +CPA_S94,CPA_J63,1 +CPA_S94,CPA_K64,384 +CPA_S94,CPA_K65.1-2 & K65.3,25 +CPA_S94,CPA_K66,38 +CPA_S94,CPA_M691,1 +CPA_S94,CPA_M70,1 +CPA_S94,CPA_M73,106 +CPA_S94,CPA_M74,107 +CPA_S94,CPA_N78,269 +CPA_S94,CPA_N80,15 +CPA_S94,CPA_N81,19 +CPA_S94,CPA_N82,167 +CPA_S94,CPA_O84,262 +CPA_S94,CPA_P85,455 +CPA_S94,CPA_Q87 & Q88,156 +CPA_S94,CPA_R90,5 +CPA_S94,CPA_R91,12 +CPA_S94,CPA_R92,26 +CPA_S94,CPA_R93,108 +CPA_S94,CPA_S94,1319 +CPA_S95,CPA_E38,24 +CPA_S95,CPA_H52,4 +CPA_S95,CPA_I56,2 +CPA_S95,CPA_J59 & J60,4 +CPA_S95,CPA_K64,112 +CPA_S95,CPA_K66,21 +CPA_S95,CPA_L68A,6 +CPA_S95,CPA_M73,2 +CPA_S95,CPA_N77,4 +CPA_S95,CPA_N78,2 +CPA_S95,CPA_O84,1541 +CPA_S95,CPA_P85,81 +CPA_S95,CPA_Q86,685 +CPA_S95,CPA_Q87 & Q88,157 +CPA_S95,CPA_R91,8 +CPA_S95,CPA_R93,28 +CPA_S95,CPA_S95,266 +CPA_S96,CPA_A03,22 +CPA_S96,CPA_C21,1 +CPA_S96,CPA_C23OTHER,1 +CPA_S96,CPA_C244_5,1 +CPA_S96,CPA_C25,2 +CPA_S96,CPA_C26,10 +CPA_S96,CPA_C33OTHER,1 +CPA_S96,CPA_E38,1 +CPA_S96,CPA_H52,3 +CPA_S96,CPA_I56,148 +CPA_S96,CPA_J58,10 +CPA_S96,CPA_J59 & J60,708 +CPA_S96,CPA_K64,361 +CPA_S96,CPA_K65.1-2 & K65.3,10 +CPA_S96,CPA_K66,23 +CPA_S96,CPA_M73,24 +CPA_S96,CPA_M75,4 +CPA_S96,CPA_N77,4 +CPA_S96,CPA_N78,23 +CPA_S96,CPA_O84,596 +CPA_S96,CPA_P85,4 +CPA_S96,CPA_Q86,681 +CPA_S96,CPA_Q87 & Q88,97 +CPA_S96,CPA_S96,751 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_vat_composition_2024/vat_product_treatment.csv b/packages/microcosm-build/tests/fixtures/uk/firm_vat_composition_2024/vat_product_treatment.csv new file mode 100644 index 0000000000..4f8ccd16a3 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_vat_composition_2024/vat_product_treatment.csv @@ -0,0 +1,121 @@ +product_code,user,standard,reduced,zero,exempt,basis,status +CPA_A01,all,0.15,0,0.85,0,"VATA 1994 Sch 8 Group 1 (food, animal feeding stuffs, seeds, live food animals); flowers, plants, non-food crops standard",assumed +CPA_A02,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_A03,all,0,0,1,0,Sch 8 Group 1 item 1 (food of a kind used for human consumption),statute +CPA_B05 & B06,all,1,0,0,0,Not in Sch 7A/8/9 (sales of crude oil and gas are business supplies); exports zero by s.30(6),statute +CPA_B07 & B08,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_B09,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C101,all,0,0,1,0,Sch 8 Group 1 item 1,statute +CPA_C102_3,all,0.05,0,0.95,0,Sch 8 Group 1 item 1; crisps and similar (excepted item 5) standard,assumed +CPA_C104,all,0,0,1,0,Sch 8 Group 1 item 1,statute +CPA_C105,all,0.05,0,0.95,0,Sch 8 Group 1 item 1; ice cream (excepted item 1) standard,assumed +CPA_C106,all,0,0,1,0,Sch 8 Group 1 item 1,statute +CPA_C107,all,0.1,0,0.9,0,Sch 8 Group 1 item 1; chocolate-covered biscuits (excepted item 2) standard,assumed +CPA_C108,all,0.4,0,0.6,0,"Sch 8 Group 1; confectionery, chocolate (excepted item 2) and hot-drink preparations partly standard",assumed +CPA_C109,all,0.3,0,0.7,0,Sch 8 Group 1 item 2 animal feeding stuffs; pet food (excepted item 6) standard,assumed +CPA_C11.01-6 & C12,all,1,0,0,0,Sch 8 Group 1 excepted item 4 (alcoholic beverages); tobacco not relieved,statute +CPA_C1107,all,1,0,0,0,Sch 8 Group 1 excepted item 4 (beverages),statute +CPA_C13,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C14,all,0.85,0,0.15,0,Sch 8 Group 16 (young children's clothing) on the share of children's wear,assumed +CPA_C15,all,0.95,0,0.05,0,Sch 8 Group 16 (young children's footwear),assumed +CPA_C16,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C17,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C18,all,1,0,0,0,Printing services standard; zero-rating of books falls on the publisher (J58),assumed +CPA_C19,all,1,0,0,0,Road fuel standard; domestic heating oil (Sch 7A Group 1) not split out,assumed +CPA_C203,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C204,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C205,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C20A,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C20B,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C20C,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C21,all,1,0,0,0,"Manufacturers' and wholesalers' sales standard; Sch 8 Group 12 zero-rating at dispensing is not modelled (NHS dispensing is bought by government, not households)",assumed +CPA_C22,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C235_6,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C23OTHER,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C241_3,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C244_5,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C25,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C26,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C27,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C28,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C29,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C301,all,0.5,0,0.5,0,Sch 8 Group 8 item 1 (qualifying ships) on part of ship output,assumed +CPA_C303,all,0.5,0,0.5,0,Sch 8 Group 8 item 2 (qualifying aircraft) on part of aircraft output,assumed +CPA_C30OTHER,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C31,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_C32,all,0.95,0,0.05,0,Sch 8 Group 12 (aids for disabled people) on a small share of medical devices,assumed +CPA_C3315,all,0,0,1,0,Sch 8 Group 8 item 1 (repair of qualifying ships),assumed +CPA_C3316,all,0,0,1,0,Sch 8 Group 8 item 2 (repair of qualifying aircraft),assumed +CPA_C33OTHER,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_D351,households,0,1,0,0,Sch 7A Group 1 (fuel and power for qualifying use: domestic),statute +CPA_D351,other,1,0,0,0,Business use standard (de minimis and charity use not split),assumed +CPA_D352_3,households,0,1,0,0,Sch 7A Group 1,statute +CPA_D352_3,other,1,0,0,0,Business use standard,assumed +CPA_E36,households,0,0,1,0,Sch 8 Group 2 item 2 (water other than to a relevant industrial activity),statute +CPA_E36,other,0.5,0,0.5,0,"Sch 8 Group 2: zero for non-industrial users, standard to relevant industrial activities (SIC divisions B-E); half assumed",assumed +CPA_E37,households,0,0,1,0,"Sch 8 Group 2 item 1 (sewerage services, not to industrial users)",statute +CPA_E37,other,0.5,0,0.5,0,Sch 8 Group 2 item 1; half assumed industrial,assumed +CPA_E38,all,1,0,0,0,"Not in Sch 7A/8/9 (local authority collection is non-business, treated as such under O84)",assumed +CPA_E39,all,1,0,0,0,Not in Sch 7A/8/9,statute +"CPA_F41, F42 & F43",all,DWELLINGS,0,DWELLINGS,0,Sch 8 Group 5 (construction of new dwellings): zero share = SUT Table 4 dwellings GFCF of construction x 0.6 new-build fraction / construction total demand,assumed +CPA_G45,all,1,0,0,0,"Vehicles, parts and fuel standard",assumed +CPA_G46,all,GOODS,0,GOODS,0,"Wholesale turnover carries the treatment of the goods resold (SUT goods mix, non-household uses)",assumed +CPA_G47,all,GOODS,0,GOODS,0,Retail turnover carries the treatment of the goods resold (SUT household goods mix),assumed +CPA_H491_2,households,0,0,1,0,"Sch 8 Group 8 item 4 (passenger transport, vehicles of 10 or more seats)",statute +CPA_H491_2,other,0.3,0,0.7,0,Passenger zero (Group 8 item 4); freight standard,assumed +CPA_H493_5,households,0.4,0,0.6,0,Bus and coach zero (Group 8 item 4); taxis and private hire standard,assumed +CPA_H493_5,other,0.9,0,0.1,0,"Mostly road freight and pipelines, standard",assumed +CPA_H50,all,0.4,0,0.6,0,"Sch 8 Group 8 items 4-6 (passengers, international freight)",assumed +CPA_H51,all,0.1,0,0.9,0,"Sch 8 Group 8 items 4-6 (passengers, international freight)",assumed +CPA_H52,all,0.8,0,0.2,0,"Sch 8 Group 8 items 6-7 (port and airport services, handling of international freight)",assumed +CPA_H53,all,0.7,0,0,0.3,Sch 9 Group 3 (universal postal service) exempt; courier and parcels standard,assumed +CPA_I55,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_I56,all,1,0,0,0,Sch 8 Group 1 note 3: catering is not zero-rated; cold takeaway food (zero) not split out,assumed +CPA_J58,households,0.3,0,0.7,0,"Sch 8 Group 3 (books, newspapers, periodicals, e-publications); software publishing standard",assumed +CPA_J58,other,0.6,0,0.4,0,Sch 8 Group 3; business purchases weighted to software and databases,assumed +CPA_J59 & J60,all,1,0,0,0,Not in Sch 7A/8/9 (licence fee and public broadcasting not split),assumed +CPA_J61,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_J62,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_J63,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_K64,all,0.1,0,0,0.9,Sch 9 Group 5 (finance); fee-based advisory and management services standard,assumed +CPA_K65.1-2 & K65.3,all,0,0,0,1,Sch 9 Group 2 (insurance),statute +CPA_K66,all,0.5,0,0,0.5,Sch 9 Groups 2 and 5 cover broking and intermediation; fund and other auxiliary services partly standard,assumed +CPA_L68BXL683,households,0,0,0,1,Sch 9 Group 1 (residential letting),statute +CPA_L68BXL683,other,0.4,0,0,0.6,Sch 9 Group 1; Sch 10 option to tax on part of commercial property,assumed +CPA_L68A,all,0,0,0,1,Imputed rent: not a supply (excluded from firms),statute +CPA_L683,all,1,0,0,0,Estate agency and property management standard,statute +CPA_M691,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_M692,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_M70,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_M71,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_M72,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_M73,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_M74,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_M75,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_N77,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_N78,all,0.9,0,0,0.1,Sch 9 Group 7 (supply of medical and nursing staff) on a small share,assumed +CPA_N79,all,1,0,0,0,Tour operators' margin scheme not modelled; treated as standard,assumed +CPA_N80,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_N81,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_N82,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_O84,all,0,0,0,1,Non-business activity outside the scope of VAT; s.33 and s.41 refunds not modelled (treated as exempt),assumed +CPA_P85,all,0.15,0,0,0.85,"Sch 9 Group 6 (education by eligible bodies); private school fees standard from 1 Jan 2025 (a quarter of 2024-25, part-year basis); commercial training standard",assumed +CPA_Q86,all,0.1,0,0,0.9,Sch 9 Group 7 (health and welfare),assumed +CPA_Q87 & Q88,all,0.1,0,0,0.9,Sch 9 Group 7 items 4 and 9 (welfare services),assumed +CPA_R90,all,0.7,0,0,0.3,Sch 9 Group 13 (cultural services by eligible bodies),assumed +CPA_R91,all,0.5,0,0,0.5,"Sch 9 Group 13 (museums, galleries by eligible bodies)",assumed +CPA_R92,all,0,0,0,1,"Sch 9 Group 4 (betting, gaming and lotteries)",statute +CPA_R93,all,0.7,0,0,0.3,Sch 9 Group 10 (sport by eligible bodies),assumed +CPA_S94,all,0.4,0,0,0.6,"Sch 9 Group 9 (trade unions, professional and public-interest bodies)",assumed +CPA_S95,all,1,0,0,0,Not in Sch 7A/8/9,statute +CPA_S96,all,0.9,0,0,0.1,Sch 9 Group 8 (burial and cremation),assumed +CPA_T97,all,0,0,0,1,Households as employers: no supply by a taxable person,statute +CPA_I55,exports,1,0,0,0,"SUT exports of this product are mostly non-residents' spending in the UK, a UK supply taxed as at home; same treatment as UK buyers",assumed +CPA_I56,exports,1,0,0,0,"SUT exports of this product are mostly non-residents' spending in the UK, a UK supply taxed as at home; same treatment as UK buyers",assumed +CPA_P85,exports,0.15,0,0,0.85,"SUT exports of this product are mostly non-residents' spending in the UK, a UK supply taxed as at home; same treatment as UK buyers",assumed +CPA_Q86,exports,0.1,0,0,0.9,"SUT exports of this product are mostly non-residents' spending in the UK, a UK supply taxed as at home; same treatment as UK buyers",assumed +CPA_R90,exports,0.7,0,0,0.3,"SUT exports of this product are mostly non-residents' spending in the UK, a UK supply taxed as at home; same treatment as UK buyers",assumed +CPA_R91,exports,0.5,0,0,0.5,"SUT exports of this product are mostly non-residents' spending in the UK, a UK supply taxed as at home; same treatment as UK buyers",assumed +CPA_R92,exports,0,0,0,1,"SUT exports of this product are mostly non-residents' spending in the UK, a UK supply taxed as at home; same treatment as UK buyers",assumed +CPA_R93,exports,0.7,0,0,0.3,"SUT exports of this product are mostly non-residents' spending in the UK, a UK supply taxed as at home; same treatment as UK buyers",assumed +CPA_S96,exports,0.9,0,0,0.1,"SUT exports of this product are mostly non-residents' spending in the UK, a UK supply taxed as at home; same treatment as UK buyers",assumed 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..b24c3cbaa3 --- /dev/null +++ b/tools/build_uk_firms.py @@ -0,0 +1,252 @@ +"""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, with ``--paybill-dir``, the ONS ASHE section +pay table that sets ``firm_paybill``), 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( + "--paybill-dir", + type=Path, + help=( + "directory holding the ONS ASHE section pay CSV; sets firm_paybill " + "(tax year 2024-25 only, so --vintage 2024-25; omit to leave it unset)" + ), + ) + parser.add_argument( + "--employment-allowance-flags", + action="store_true", + help=( + "set the assumed Employment Allowance flags " + "(firm_claims_employment_allowance, firm_is_single_director_company) " + "from ONS legal status and employment" + ), + ) + parser.add_argument( + "--public-sector-dir", + type=Path, + help=( + "directory holding the ONS public sector employment CSV; scales " + "central government and local authority headcounts to it" + ), + ) + parser.add_argument( + "--profit-dir", + type=Path, + help=( + "directory holding the HMRC Corporation Tax liability bands; sets " + "the assumed firm_taxable_trading_profit" + ), + ) + parser.add_argument( + "--rateable-value-dir", + type=Path, + help=( + "directory holding the VOA rateable value bands; sets the assumed " + "firm_rateable_value" + ), + ) + parser.add_argument( + "--pay-distribution-dir", + type=Path, + help=( + "directory holding the ONS ASHE section pay percentiles; sets the " + "assumed count and pay of employees at or below the secondary " + "threshold (needs --paybill-dir)" + ), + ) + parser.add_argument( + "--bpe-dir", + type=Path, + help=( + "directory holding the DBT Business Population Estimates 2025 " + "tables; redraws headcount inside the ONS 0-4 band by legal status " + "and sets firm_employees to employment less assumed working " + "proprietors, with the labour link columns (needs --paybill-dir)" + ), + ) + parser.add_argument( + "--vat-composition-dir", + type=Path, + help=( + "directory holding the VAT composition fixture; adds Microcosm-only " + "SIC section shares of standard-, reduced-, zero-rated and exempt " + "supplies (columns only; needs --consumption-dir)" + ), + ) + parser.add_argument( + "--paybill-anchor-dir", + type=Path, + help=( + "directory holding the ONS D.11 and PAYE RTI paybill anchors; " + "reports paybill over each in the receipt (needs --paybill-dir)" + ), + ) + parser.add_argument( + "--consumption-dir", + type=Path, + help=( + "directory holding the ONS Supply and Use Tables 2024 extract; " + "splits turnover into household, intermediate and other final " + "sales by SIC division" + ), + ) + parser.add_argument( + "--bpe-mid-headcount", + action="store_true", + help=( + "remap headcount inside the ONS 5-9 to 100-249 bands to BPE 2025 " + "Table 1 shapes (needs --bpe-dir)" + ), + ) + parser.add_argument( + "--bpe-turnover", + action="store_true", + help=( + "draw the open ONS turnover band on a tail pinned to BPE 2025 total " + "turnover and re-pair employment with turnover (needs --bpe-dir)" + ), + ) + parser.add_argument( + "--bpe-large-headcount", + action="store_true", + help="remap 250+ headcount to BPE 2025 Table 1 large rows (needs --bpe-dir)", + ) + parser.add_argument( + "--rd-tax-credits-dir", + type=Path, + help=( + "directory holding HMRC R&D tax credit statistics 2024-25; sets the " + "assumed firm_qualifying_rd_expenditure and firm_is_sme" + ), + ) + parser.add_argument( + "--out-of-frame-no-employees", + action="store_true", + help=( + "give rows outside the ONS frame no headcount, an assumption " + "(needs --bpe-dir)" + ), + ) + parser.add_argument( + "--employment-allowance-takeup-dir", + type=Path, + help=( + "directory holding HMRC Employment Allowance take-up 2024-25; " + "draws claims at HMRC's take-up by employee size band (needs " + "--bpe-dir and --employment-allowance-flags)" + ), + ) + 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), + paybill_dir=args.paybill_dir, + employment_allowance=args.employment_allowance_flags, + public_sector_dir=args.public_sector_dir, + profit_dir=args.profit_dir, + rateable_value_dir=args.rateable_value_dir, + pay_distribution_dir=args.pay_distribution_dir, + bpe_dir=args.bpe_dir, + employment_allowance_takeup_dir=args.employment_allowance_takeup_dir, + consumption_dir=args.consumption_dir, + vat_composition_dir=args.vat_composition_dir, + paybill_anchor_dir=args.paybill_anchor_dir, + bpe_mid_headcount=args.bpe_mid_headcount, + out_of_frame_no_employees=args.out_of_frame_no_employees, + bpe_turnover=args.bpe_turnover, + bpe_large_headcount=args.bpe_large_headcount, + rd_tax_credits_dir=args.rd_tax_credits_dir, + ) + 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..f89b20168f --- /dev/null +++ b/tools/compare_uk_firm_taxes_to_receipts.py @@ -0,0 +1,285 @@ +#!/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. It is the " + "generator's headcount times the ONS ASHE 2025 section mean annual gross " + "pay (all employee jobs), with working proprietors counted as employees " + "and out-of-frame zero-turnover traders included, so agreement or " + "disagreement here 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: unless the build sets the assumed flags " + "(--employment-allowance-flags), firm_is_single_director_company and " + "firm_claims_employment_allowance are left at their defaults, so no firm " + "is excluded as a single-director company or as having no employees, 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": ( + "In-sample when firm_taxable_trading_profit comes from the opt-in " + "firm_profit.py imputation (--profit-dir): it allots HMRC Corporation " + "Tax statistics liability bands for 2024-25 to companies, so the model " + "total reproduces HMRC's CT liabilities by construction and agreement " + "here does not validate the model. Public corporations (ONS legal " + "status 4) are companies but get no imputed profit, so they pay no CT. " + "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. Assumed " + "input: with --rateable-value-dir, firm_rateable_value allots the VOA " + "2023-list stock of hereditaments in England to firms by headcount rank, " + "one property per firm, so small business rate relief is overstated " + "for multi-site firms and properties of non-firm ratepayers are handed " + "to firms. Every ONS non-profit body (legal status 7) is assumed a " + "charity (firm_is_charity), so it takes mandatory charitable rate relief " + "and the total is lower than if only registered charities did. 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_bpe_tables.py b/tools/extract_uk_firm_bpe_tables.py new file mode 100644 index 0000000000..8801860efa --- /dev/null +++ b/tools/extract_uk_firm_bpe_tables.py @@ -0,0 +1,506 @@ +#!/usr/bin/env python3 +"""Extract DBT Business Population Estimates 2025 size tables for UK firms. + +Reads the Department for Business and Trade *Business population estimates +for the UK and regions 2025* detailed tables workbook +(``BPE_2025_detailed_tables.xlsx``, published 2 October 2025, start-2025 +estimates) and writes two CSVs: + +- ``bpe_legal_status_bands.csv`` from sheet ``Table 3`` (UK private sector by + legal status and employee size band): the private sector, companies, + ordinary partnerships and sole proprietorships sections, with business + number and employment (thousands). A cell published as ``[c]`` (disclosive) + is left empty and flagged ``[c]`` in the row's flag column; +- ``bpe_size_bands.csv`` from sheet ``Table 1`` (UK private sector: businesses, + employment, employees, working proprietors, turnover) and sheet ``Table 2`` + (whole economy, private sector, central and local government, non-profit + organisations: businesses, employment, employees, turnover) by employee + size band. A column a table does not publish is left empty. + +Values are the cells as published; the percentage columns are not kept. +Band labels lose their ``[Note n]`` markers and nothing else. + +openpyxl is imported only when a workbook is read, so engine-free CI, which +reads the committed CSVs, never needs it. + +Usage:: + + uv run --no-sync python tools/extract_uk_firm_bpe_tables.py \\ + --xlsx /BPE_2025_detailed_tables.xlsx + + # Exit 1 if re-extraction would change the committed CSVs' bytes. + uv run --no-sync python tools/extract_uk_firm_bpe_tables.py \\ + --xlsx /BPE_2025_detailed_tables.xlsx --check +""" + +from __future__ import annotations + +import argparse +import csv +import datetime as dt +import hashlib +import io +import json +import re +import sys +from collections.abc import Sequence +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_bpe_2025" +) +LEGAL_STATUS_CSV = "bpe_legal_status_bands.csv" +SIZE_BANDS_CSV = "bpe_size_bands.csv" +PROVENANCE_NAME = "firm_bpe_2025.provenance.json" + +LANDING_PAGE = ( + "https://www.gov.uk/government/statistics/business-population-estimates-2025" +) +XLSX_URL = ( + "https://assets.publishing.service.gov.uk/media/68dbccc9c487360cc70c9f4e/" + "BPE_2025_detailed_tables.xlsx" +) +#: The committed fixture's recorded access date: the default for +#: ``--access-date``, which the person who downloads the workbook sets. +ACCESS_DATE = "2026-11-22" + +CONTENTS_SHEET = "Contents" +EDITION_TITLE = "BUSINESS POPULATION ESTIMATES FOR THE UK AND REGIONS 2025" +PUBLISHED = "Published 2nd October 2025" + +#: Employee size bands every section lists, in published order. +SIZE_BANDS_TABLE_1 = ( + "All businesses", + "All employers", + "With no employees (unregistered)", + "With no employees (registered)", + "1", + "2 to 4", + "5 to 9", + "10 to 19", + "20 to 49", + "50 to 99", + "100 to 199", + "200 to 249", + "250 to 499", + "500 to 999", + "1000 or more", +) +SIZE_BANDS_TABLE_2 = ( + "All", + "Zero or 1 employee", + *SIZE_BANDS_TABLE_1[5:], +) + +TABLE_1 = "Table 1" +TABLE_1_TITLE = "Table 1 (UK private sector)" +TABLE_2 = "Table 2" +TABLE_2_TITLE = "Table 2 (UK whole economy)" +TABLE_3 = "Table 3" +TABLE_3_TITLE = "Tables 3 (UK legal status)" + +#: Table 2 section heading -> sector key. +TABLE_2_SECTIONS = ( + ("Whole economy", "whole_economy"), + ("Private sector", "private_sector"), + ("Central and Local Government", "central_and_local_government"), + ("Non-profit Organisations", "non_profit"), +) +#: Table 3 section heading prefix -> legal status key. +TABLE_3_SECTIONS = ( + ("Private sector", "private_sector"), + ("Companies", "companies"), + ("Ordinary Partnerships", "ordinary_partnerships"), + ("Sole proprietorships", "sole_proprietorships"), +) + +SUPPRESSED = "[c]" + +LEGAL_STATUS_HEADER = ( + "legal_status", + "size_band", + "business_number", + "business_number_flag", + "employment_thousand", + "employment_flag", +) +SIZE_BANDS_HEADER = ( + "table", + "sector", + "size_band", + "business_number", + "employment_thousand", + "employees_thousand", + "working_proprietors_thousand", + "turnover_million", +) + + +def _text(value: Any) -> str: + return "" if value is None else " ".join(str(value).split()) + + +def _band(value: Any) -> str: + """A size band label without ``[Note n]`` markers.""" + + if isinstance(value, (int, float)) and not isinstance(value, bool): + return str(int(value)) + return re.sub(r"\s*\[Note \d+\]", "", _text(value)).strip() + + +def _cell(value: Any, where: str) -> tuple[str, str]: + """``(value, flag)``: a number as published, or empty and ``[c]``.""" + + if _text(value) == SUPPRESSED: + return "", SUPPRESSED + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError(f"{where}: expected a number or [c], got {value!r}") + if value < 0: + raise ValueError(f"{where}: negative value {value!r}") + return (str(int(value)) if value == int(value) else repr(float(value))), "" + + +def _number(value: Any, where: str) -> str: + text, flag = _cell(value, where) + if flag: + raise ValueError(f"{where}: unexpected suppressed cell") + return text + + +def _header_columns(row: tuple[Any, ...], wanted: dict[str, str]) -> dict[str, int]: + """Column index of each wanted header (matched on its first words).""" + + labels = [_text(cell).lower() for cell in row] + out = {} + for key, prefix in wanted.items(): + hits = [i for i, label in enumerate(labels) if label.startswith(prefix)] + if len(hits) != 1: + raise ValueError(f"header {prefix!r} found {len(hits)}x in {labels}") + out[key] = hits[0] + return out + + +def _sections( + rows: list[tuple[Any, ...]], + start: int, + headings: tuple[tuple[str, str], ...], + bands: tuple[str, ...], +) -> dict[str, list[tuple[Any, ...]]]: + """Each heading's band rows, checked against ``bands`` in order.""" + + out: dict[str, list[tuple[Any, ...]]] = {} + labels = [_text(row[0]) if row else "" for row in rows] + for heading, key in headings: + hits = [i for i in range(start, len(rows)) if labels[i].startswith(heading)] + if len(hits) != 1: + raise ValueError(f"section {heading!r} found {len(hits)}x") + block = rows[hits[0] + 1 : hits[0] + 1 + len(bands)] + got = tuple(_band(row[0]) for row in block) + if got != bands: + raise ValueError(f"section {heading!r} bands {got} are not {bands}") + out[key] = block + return out + + +def extract_legal_status(rows: list[tuple[Any, ...]]) -> list[tuple[str, ...]]: + """``bpe_legal_status_bands.csv`` rows from sheet ``Table 3``'s cells.""" + + if not _text(rows[0][0]).startswith(TABLE_3_TITLE): + raise ValueError(f"unexpected Table 3 title {_text(rows[0][0])!r}") + header = next( + i + for i, row in enumerate(rows) + if _text(row[0]).startswith("Employee size band") + ) + columns = _header_columns( + rows[header], + {"business": "business number", "employment": "employment number"}, + ) + out = [] + sections = _sections(rows, header + 1, TABLE_3_SECTIONS, SIZE_BANDS_TABLE_1) + for _, key in TABLE_3_SECTIONS: + for row in sections[key]: + band = _band(row[0]) + where = f"Table 3 {key} {band}" + business, business_flag = _cell(row[columns["business"]], where) + employment, employment_flag = _cell(row[columns["employment"]], where) + out.append( + (key, band, business, business_flag, employment, employment_flag) + ) + return out + + +def extract_size_bands( + table_1: list[tuple[Any, ...]], table_2: list[tuple[Any, ...]] +) -> list[tuple[str, ...]]: + """``bpe_size_bands.csv`` rows from sheets ``Table 1`` and ``Table 2``.""" + + if not _text(table_1[0][0]).startswith(TABLE_1_TITLE): + raise ValueError(f"unexpected Table 1 title {_text(table_1[0][0])!r}") + if not _text(table_2[0][0]).startswith(TABLE_2_TITLE): + raise ValueError(f"unexpected Table 2 title {_text(table_2[0][0])!r}") + out = [] + header = next( + i + for i, row in enumerate(table_1) + if _text(row[0]).startswith("Employee size band") + ) + columns = _header_columns( + table_1[header], + { + "business": "business number", + "employment": "employment number", + "employees": "employees number", + "proprietors": "working proprietors number", + "turnover": "turnover (£ millions)", + }, + ) + block = table_1[header + 1 : header + 1 + len(SIZE_BANDS_TABLE_1)] + if tuple(_band(row[0]) for row in block) != SIZE_BANDS_TABLE_1: + raise ValueError("Table 1 bands are not the expected bands") + for row in block: + band = _band(row[0]) + where = f"Table 1 {band}" + out.append( + ( + TABLE_1, + "private_sector", + band, + *(_number(row[columns[key]], where) for key in columns), + ) + ) + header = next( + i + for i, row in enumerate(table_2) + if _text(row[0]).startswith("Employee size band") + ) + columns = _header_columns( + table_2[header], + { + "business": "number of businesses", + "employment": "employment number", + "employees": "employees number", + "turnover": "turnover (£ millions)", + }, + ) + sections = _sections(table_2, header + 1, TABLE_2_SECTIONS, SIZE_BANDS_TABLE_2) + for _, key in TABLE_2_SECTIONS: + for row in sections[key]: + band = _band(row[0]) + where = f"Table 2 {key} {band}" + business, employment, employees, turnover = ( + _number(row[columns[name]], where) + for name in ("business", "employment", "employees", "turnover") + ) + out.append( + (TABLE_2, key, band, business, employment, employees, "", turnover) + ) + return out + + +def to_csv_bytes(header: tuple[str, ...], rows: list[tuple[Any, ...]]) -> bytes: + buffer = io.StringIO() + writer = csv.writer(buffer, lineterminator="\n") + writer.writerow(header) + writer.writerows(rows) + return buffer.getvalue().encode("utf-8") + + +def _read(xlsx: Path) -> tuple[dict[str, list[tuple[Any, ...]]], list[str]]: + import openpyxl # noqa: PLC0415 - local-only dependency, kept out of CI imports + + book = openpyxl.load_workbook(xlsx, read_only=True, data_only=True) + try: + sheets = { + name: list(book[name].iter_rows(values_only=True)) + for name in (TABLE_1, TABLE_2, TABLE_3) + } + contents = [ + _text(row[0]) + for row in book[CONTENTS_SHEET].iter_rows(max_row=2, values_only=True) + ] + finally: + book.close() + return sheets, contents + + +def extract( + xlsx: Path, +) -> tuple[list[tuple[str, ...]], list[tuple[str, ...]], list[str]]: + sheets, contents = _read(xlsx) + if contents[:2] != [EDITION_TITLE, PUBLISHED]: + raise ValueError( + f"workbook is {contents[:2]!r}, not {[EDITION_TITLE, PUBLISHED]!r}" + ) + legal = extract_legal_status(sheets[TABLE_3]) + size = extract_size_bands(sheets[TABLE_1], sheets[TABLE_2]) + return legal, size, contents + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _iso_date(value: str) -> str: + try: + return dt.date.fromisoformat(value).isoformat() + except ValueError: + raise argparse.ArgumentTypeError( + f"access date {value!r} is not YYYY-MM-DD" + ) from None + + +def provenance( + xlsx: Path, + payloads: dict[str, tuple[bytes, int, tuple[str, ...]]], + contents: list[str], + access_date: str = ACCESS_DATE, +) -> dict[str, Any]: + workbook = xlsx.read_bytes() + return { + "kind": "uk_firm_bpe_size_band_fixture", + "schema_version": 1, + "period": "start of 2025 (BPE reference date), not a tax year", + "accessed": access_date, + "method": ( + "Figures were read from the downloaded workbook on the access date " + "by tools/extract_uk_firm_bpe_tables.py; none was filled from " + "memory. Numbers are the cells as published: business counts in " + "businesses, employment, employees and working proprietors in " + "thousands of people, turnover in millions of pounds. A cell " + "published as [c] (disclosive) is left empty and flagged [c]. " + "Band labels lose their [Note n] markers; percentage columns are " + "not kept." + ), + "source": { + "publisher": "Department for Business and Trade", + "dataset_title": "Business population estimates 2025", + "landing_page": LANDING_PAGE, + "url": XLSX_URL, + "edition": f"{contents[0]}; {contents[1]}", + "file": xlsx.name, + "size_bytes": len(workbook), + "sha256": _sha256(workbook), + "sheets": { + LEGAL_STATUS_CSV: [TABLE_3], + SIZE_BANDS_CSV: [TABLE_1, TABLE_2], + }, + "tables": { + TABLE_1: ( + "Number and percentage of businesses in the private sector " + "and their associated employment and turnover, by number " + "of employees, UK, start 2025" + ), + TABLE_2: ( + "Number and percentage of businesses and other " + "organisations in the whole economy, private sector, " + "central and local government, and non-profit " + "organisations with associated employment and turnover, " + "start 2025" + ), + TABLE_3: ( + "Number and percentage of businesses in the private " + "sector and associated employment and turnover, by legal " + "status and number of employees, UK, start 2025" + ), + }, + "designation": "Official statistics in development", + "licence": "Open Government Licence v3.0", + }, + "notes": ( + "Employment is employees plus working proprietors (Table 1 note " + "3). Companies with one PAYE employee on the IDBR are counted " + "with no employees, the employee being treated as a working " + "proprietor (Table 3 notes 3 and 6). Businesses with no employees " + "are registered (VAT and/or PAYE) or unregistered (Table 3 note " + "2). Companies include public corporations and nationalised " + "bodies (Table 3 heading). Turnover excludes SIC 2007 Section K. " + "Business counts are rounded, so totals may not equal the sum of " + "their parts." + ), + "extraction_date": dt.date.today().isoformat(), + "tool": "tools/extract_uk_firm_bpe_tables.py", + "command": ( + "uv run --no-sync python tools/extract_uk_firm_bpe_tables.py " + "--xlsx /BPE_2025_detailed_tables.xlsx" + ), + "files": { + name: { + "sha256": _sha256(payload), + "bytes": len(payload), + "rows": rows, + "columns": list(header), + } + for name, (payload, rows, header) in payloads.items() + }, + } + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--xlsx", 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", + ) + parser.add_argument( + "--access-date", + type=_iso_date, + default=ACCESS_DATE, + help=( + "date (YYYY-MM-DD) the workbook was downloaded, written to the " + f"provenance (default {ACCESS_DATE}, the committed fixture's)" + ), + ) + args = parser.parse_args(argv) + xlsx = args.xlsx.resolve() + legal, size, contents = extract(xlsx) + payloads = { + LEGAL_STATUS_CSV: ( + to_csv_bytes(LEGAL_STATUS_HEADER, legal), + len(legal), + LEGAL_STATUS_HEADER, + ), + SIZE_BANDS_CSV: ( + to_csv_bytes(SIZE_BANDS_HEADER, size), + len(size), + SIZE_BANDS_HEADER, + ), + } + if args.check: + stale = [ + name + for name, (payload, _, _) in payloads.items() + if not (args.out / name).is_file() + or (args.out / name).read_bytes() != payload + ] + for name in stale: + print(f"stale or missing: {name}", file=sys.stderr) + if stale: + return 1 + print("CSVs match the workbook") + return 0 + args.out.mkdir(parents=True, exist_ok=True) + for name, (payload, rows, _) in payloads.items(): + (args.out / name).write_bytes(payload) + print(f"wrote {args.out / name} ({rows} rows)") + record = provenance(xlsx, payloads, contents, args.access_date) + (args.out / PROVENANCE_NAME).write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8" + ) + print(f"wrote {args.out / PROVENANCE_NAME}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/extract_uk_firm_capex_tables.py b/tools/extract_uk_firm_capex_tables.py new file mode 100644 index 0000000000..87406ec859 --- /dev/null +++ b/tools/extract_uk_firm_capex_tables.py @@ -0,0 +1,131 @@ +"""Extract UK business capital expenditure by asset and by section (fixture only). + +Design note: ``docs/uk-firm-capex-design.md``. Nothing reads this fixture in a +build: profit is drawn after capital allowances, so feeding capex to +policyengine-uk would deduct allowances twice. + +Writes ``packages/microcosm-build/tests/fixtures/uk/firm_capex_2024/``: + +- ``business_investment_by_asset.csv``: ONS Business investment by asset, + sheet "CP (Annual)", the 2024 row (pounds million, current prices) for + NPEK, EDRB, EDWH, EDYP and EDYS; +- ``abs_capex_by_section.csv``: ONS Annual Business Survey 2024 results, + sheet "Sections A to S", 2024 capital expenditure acquisitions and + disposals by SIC section. + + uv run --no-sync python tools/extract_uk_firm_capex_tables.py \ + --bi-xlsx /businessinvestmentbyasset.xlsx \ + --abs-xlsx /abssectionsas.xlsx [--check] +""" + +from __future__ import annotations + +import argparse +import hashlib +import io +import sys +from pathlib import Path + +import openpyxl +import pandas as pd + +FIXTURE = Path("packages/microcosm-build/tests/fixtures/uk/firm_capex_2024") +BI_SHA256 = "f206fa785e4b1f1f04fef31dbcafd4b8b480af4029a20b5f438383fa7c521c2c" +ABS_SHA256 = "9e548c5c410b73e5a7aec1f97db8f92843430cb6ef5457b1459a0e0e9b13e710" +YEAR = 2024 + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def extract_business_investment(path: Path) -> pd.DataFrame: + wb = openpyxl.load_workbook(path, read_only=True, data_only=True) + rows = list(wb["CP (Annual)"].iter_rows(values_only=True)) + titles, ids = rows[2], rows[3] + row = next(r for r in rows[4:] if r[0] == YEAR) + out = [ + { + "series_id": ids[i], + "asset": str(titles[i]).split(" [")[0], + "year": YEAR, + "value_gbp_million": float(row[i]), + } + for i in range(1, len(ids)) + if ids[i] + ] + frame = pd.DataFrame(out) + parts = frame[frame.series_id != "NPEK"].value_gbp_million.sum() + total = frame[frame.series_id == "NPEK"].value_gbp_million.iloc[0] + if abs(parts - total) > 0.5: + raise ValueError(f"asset classes sum to {parts}, not NPEK {total}") + return frame + + +def extract_abs_capex(path: Path) -> pd.DataFrame: + wb = openpyxl.load_workbook(path, read_only=True, data_only=True) + rows = list(wb["Sections A to S"].iter_rows(values_only=True)) + header = rows[6] + acq = next( + i + for i, h in enumerate(header) + if str(h).startswith("Total capital expenditure acquisitions") + ) + dis = next( + i + for i, h in enumerate(header) + if str(h).startswith("Total capital expenditure disposals") + ) + out = [ + { + "sic_section": r[0].strip(), + "year": YEAR, + "acquisitions_gbp_million": float(r[acq]), + "disposals_gbp_million": float(r[dis]), + } + for r in rows[8:] + if r[2] == YEAR and isinstance(r[0], str) + ] + return pd.DataFrame(out) + + +def _csv(frame: pd.DataFrame) -> bytes: + buffer = io.StringIO() + frame.to_csv(buffer, index=False, lineterminator="\n", float_format="%.10g") + return buffer.getvalue().encode() + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--bi-xlsx", type=Path, required=True) + parser.add_argument("--abs-xlsx", type=Path, required=True) + parser.add_argument("--out-dir", type=Path, default=FIXTURE) + parser.add_argument("--check", action="store_true") + args = parser.parse_args(argv) + if _sha256(args.bi_xlsx) != BI_SHA256 or _sha256(args.abs_xlsx) != ABS_SHA256: + print("a workbook's sha256 differs from the pinned download", file=sys.stderr) + return 1 + tables = { + "business_investment_by_asset.csv": extract_business_investment(args.bi_xlsx), + "abs_capex_by_section.csv": extract_abs_capex(args.abs_xlsx), + } + bad = [] + for name, frame in tables.items(): + target = args.out_dir / name + if args.check: + if target.read_bytes() != _csv(frame): + bad.append(name) + else: + args.out_dir.mkdir(parents=True, exist_ok=True) + target.write_bytes(_csv(frame)) + print(f"wrote {name} ({len(frame)} rows)") + if bad: + print(f"differ from a fresh extraction: {bad}", file=sys.stderr) + return 1 + if args.check: + print("ok: extraction matches the committed CSVs") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/extract_uk_firm_ct_tables.py b/tools/extract_uk_firm_ct_tables.py new file mode 100644 index 0000000000..308de73e6f --- /dev/null +++ b/tools/extract_uk_firm_ct_tables.py @@ -0,0 +1,407 @@ +#!/usr/bin/env python3 +"""Extract HMRC Corporation Tax liability tables for the UK firm profit draw. + +Reads HMRC *Corporation Tax Statistics 2026* (``corporation_tax_data_tables_ +2026.ods``, published 24 September 2026), financial year 2024-25 (1 April 2024 +to 31 March 2025, the last column of each table), and writes two CSVs: + +``ct_liability_bands.csv`` from sheet ``Tables_9A,B`` (*Tax liability by +band*; this was Table 10 in earlier editions, and ``Tables_10A,B`` is now +trading turnover by band):: + + band,lower_gbp,upper_gbp,companies,liability_gbp_million + +one row per liability band as published (``0``, ``>0-100`` ... ``>50m``), then +``POSITIVE`` (Table 9B's *Companies with > £0 tax payable* and Table 9A's +*Total*) and ``ALL_RETURNS`` (*All companies who submitted a tax return*). +``lower_gbp`` is exclusive and ``upper_gbp`` inclusive; the open band has a +blank ``upper_gbp``. Table 9A has no row for the ``0`` band and no liability +for all returns, so those cells are blank, never 0. + +``ct_sic_sections.csv`` from sheet ``Tables_6A,B`` (*Tax liability by SIC +section*):: + + hmrc_section,description,companies_with_liability,liability_gbp_million + +one row per HMRC section A-U and one ``ALL`` row (the tables' *Total*). HMRC's +``U`` is *Overseas; Unclassified, Dormant and Non-trading*, not SIC section U +alone. This table is held out: the profit draw never reads it. + +Counts are as published, rounded by HMRC to the nearest 5; amounts are GBP +million, rounded by HMRC to the nearest million. The "tax liability" of these +tables is *Corporation Tax payable* (its total equals that row of Table 5A). + +Usage:: + + uv run --no-sync python tools/extract_uk_firm_ct_tables.py \\ + --ods /corporation_tax_data_tables_2026.ods + + # Exit 1 if re-extraction would change a committed CSV's bytes. + uv run --no-sync python tools/extract_uk_firm_ct_tables.py \\ + --ods /corporation_tax_data_tables_2026.ods --check +""" + +from __future__ import annotations + +import argparse +import csv +import datetime as dt +import hashlib +import io +import json +import sys +from collections.abc import Sequence +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_ct_2024" +) + +LANDING_PAGE = ( + "https://www.gov.uk/government/statistics/corporation-tax-statistics-2026" +) +COLLECTION_PAGE = ( + "https://www.gov.uk/government/collections/" + "analyses-of-corporation-tax-receipts-and-liabilities" +) +ODS_URL = ( + "https://assets.publishing.service.gov.uk/media/6aabc7c52f29b38884818639/" + "corporation_tax_data_tables_2026.ods" +) +EDITION = ( + "Corporation Tax Statistics 2026, published 24 September 2026 (cover " + "sheet: all tables updated in September 2026; next release autumn 2027)" +) +FINANCIAL_YEAR = "2024-25" +#: The committed fixtures' recorded access date: the default for +#: ``--access-date``, which the person who downloads the file sets. +ACCESS_DATE = "2026-11-22" + +BANDS_SHEET = "Tables_9A,B" +BANDS_TITLE = "Tax liability by band, 2019-20 to 2024-25" +BANDS_AMOUNT_TABLE = "Table 9A: Total tax liability per band" +BANDS_COUNT_TABLE = "Table 9B: Number of companies per band" +BANDS_CSV = "ct_liability_bands.csv" +BANDS_HEADER = ( + "band", + "lower_gbp", + "upper_gbp", + "companies", + "liability_gbp_million", +) +ZERO_BAND = "0" +POSITIVE_LABEL = "Companies with > £0 tax payable" +ALL_RETURNS_LABEL = "All companies who submitted a tax return" +POSITIVE_KEY = "POSITIVE" +ALL_RETURNS_KEY = "ALL_RETURNS" +TOTAL_LABEL = "Total" + +SECTIONS_SHEET = "Tables_6A,B" +SECTIONS_TITLE = ( + "Tax liability by Standard Industrial Classification (SIC) section " + "2019-20 to 2024-25" +) +SECTIONS_AMOUNT_TABLE = "Table 6A: Tax liability by SIC section" +SECTIONS_COUNT_TABLE = ( + "Table 6B: Number of companies by SIC section with > £0 CT payable" +) +SECTIONS_CSV = "ct_sic_sections.csv" +SECTIONS_HEADER = ( + "hmrc_section", + "description", + "companies_with_liability", + "liability_gbp_million", +) +SECTIONS = tuple("ABCDEFGHIJKLMNOPQRSTU") +ALL_KEY = "ALL" + +END_OF_SHEET = "End of worksheet" +_MULTIPLIERS = {"m": 1_000_000, "b": 1_000_000_000} + + +def _text(value: Any) -> str: + return "" if value is None else " ".join(str(value).split()) + + +def _label(value: Any) -> str: + """A row label; the ``0`` band arrives as a number in Table 9B.""" + + if isinstance(value, float) and value == int(value): + return str(int(value)) + return _text(value) + + +def _whole(value: Any, where: str) -> int: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError(f"{where}: expected a number, got {value!r}") + if value != int(value) or value < 0: + raise ValueError(f"{where}: expected a non-negative whole number, got {value}") + return int(value) + + +def _edge(text: str) -> int: + text = text.replace(",", "").strip() + multiplier = _MULTIPLIERS.get(text[-1:], 1) + digits = text[:-1] if multiplier != 1 else text + if not digits.isdigit(): + raise ValueError(f"band edge {text!r} is not a number") + return int(digits) * multiplier + + +def band_edges(label: str) -> tuple[int, int | None]: + """``(lower, upper)`` pounds of a band label: lower exclusive, upper + inclusive, ``None`` for the open band. ``0`` is ``(0, 0)``.""" + + if label == ZERO_BAND: + return 0, 0 + if not label.startswith(">"): + raise ValueError(f"band label {label!r} does not start with '>'") + lower, _, upper = label[1:].partition("-") + return _edge(lower), (_edge(upper) if upper else None) + + +def _table( + rows: Sequence[Sequence[Any]], heading: str, sheet: str +) -> list[tuple[str, int]]: + """``(label, value)`` of the ``FINANCIAL_YEAR`` column of one table.""" + + starts = [i for i, row in enumerate(rows) if row and _text(row[0]) == heading] + if len(starts) != 1: + raise ValueError(f"{sheet}: heading {heading!r} found {len(starts)}x") + header = [_text(value) for value in rows[starts[0]]] + if header[-1] != FINANCIAL_YEAR or header.count(FINANCIAL_YEAR) != 1: + raise ValueError( + f"{sheet}: {heading!r} does not end with column {FINANCIAL_YEAR}" + ) + column = len(header) - 1 + out: list[tuple[str, int]] = [] + for row in rows[starts[0] + 1 :]: + label = _label(row[0]) if row else "" + if not label or label == END_OF_SHEET or label.startswith("Table "): + break + if len(row) <= column: + raise ValueError(f"{sheet}: row {label!r} has no {FINANCIAL_YEAR} cell") + out.append((label, _whole(row[column], f"{sheet} {label!r}"))) + if not out: + raise ValueError(f"{sheet}: {heading!r} has no rows") + return out + + +def _title(rows: Sequence[Sequence[Any]], title: str, sheet: str) -> None: + found = _text(rows[0][0]) if rows and rows[0] else "" + if found != title: + raise ValueError(f"{sheet}: title {found!r} is not {title!r}") + + +def extract_bands(rows: Sequence[Sequence[Any]]) -> list[tuple[Any, ...]]: + _title(rows, BANDS_TITLE, BANDS_SHEET) + amounts = dict(_table(rows, BANDS_AMOUNT_TABLE, BANDS_SHEET)) + counts = _table(rows, BANDS_COUNT_TABLE, BANDS_SHEET) + count_by_label = dict(counts) + for label in (ZERO_BAND, POSITIVE_LABEL, ALL_RETURNS_LABEL): + if label not in count_by_label: + raise ValueError(f"{BANDS_SHEET}: Table 9B has no {label!r} row") + if TOTAL_LABEL not in amounts: + raise ValueError(f"{BANDS_SHEET}: Table 9A has no {TOTAL_LABEL!r} row") + bands = [label for label, _ in counts if label.startswith(">")] + if bands != [label for label in amounts if label != TOTAL_LABEL]: + raise ValueError(f"{BANDS_SHEET}: Tables 9A and 9B list different bands") + out: list[tuple[Any, ...]] = [ + (ZERO_BAND, 0, 0, count_by_label[ZERO_BAND], ""), + ] + previous_upper: int | None = 0 + for label in bands: + lower, upper = band_edges(label) + if lower != previous_upper: + raise ValueError(f"{BANDS_SHEET}: band {label!r} does not follow on") + previous_upper = upper + out.append( + ( + label, + lower, + "" if upper is None else upper, + count_by_label[label], + amounts[label], + ) + ) + if previous_upper is not None: + raise ValueError(f"{BANDS_SHEET}: the last band is not open") + out.append( + (POSITIVE_KEY, "", "", count_by_label[POSITIVE_LABEL], amounts[TOTAL_LABEL]) + ) + out.append((ALL_RETURNS_KEY, "", "", count_by_label[ALL_RETURNS_LABEL], "")) + return out + + +def extract_sections(rows: Sequence[Sequence[Any]]) -> list[tuple[Any, ...]]: + _title(rows, SECTIONS_TITLE, SECTIONS_SHEET) + amounts = _table(rows, SECTIONS_AMOUNT_TABLE, SECTIONS_SHEET) + counts = _table(rows, SECTIONS_COUNT_TABLE, SECTIONS_SHEET) + if [label for label, _ in amounts] != [label for label, _ in counts]: + raise ValueError(f"{SECTIONS_SHEET}: Tables 6A and 6B list different rows") + labels = [label for label, _ in amounts] + if labels[-1] != TOTAL_LABEL: + raise ValueError(f"{SECTIONS_SHEET}: the last row is not {TOTAL_LABEL!r}") + letters = tuple(label.partition(". ")[0] for label in labels[:-1]) + if letters != SECTIONS: + raise ValueError(f"{SECTIONS_SHEET}: sections {letters} != {SECTIONS}") + out: list[tuple[Any, ...]] = [] + for (label, amount), (_, count) in zip(amounts, counts, strict=True): + if label == TOTAL_LABEL: + out.append((ALL_KEY, TOTAL_LABEL, count, amount)) + else: + letter, _, description = label.partition(". ") + out.append((letter, description, count, amount)) + return out + + +def to_csv_bytes(header: Sequence[str], rows: Sequence[Sequence[Any]]) -> bytes: + buffer = io.StringIO() + writer = csv.writer(buffer, lineterminator="\n") + writer.writerow(header) + writer.writerows(rows) + return buffer.getvalue().encode("utf-8") + + +def extract(ods: Path) -> dict[str, bytes]: + """The two CSVs' bytes, keyed by file name.""" + + sys.path.insert(0, str(REPOSITORY_ROOT / "packages" / "microcosm-build" / "src")) + from microcosm.build.uk_runtime.ods_tables import ( # noqa: PLC0415 + read_ods_tables, + ) + + tables = read_ods_tables(ods, label="HMRC Corporation Tax statistics tables") + for sheet in (BANDS_SHEET, SECTIONS_SHEET): + if sheet not in tables: + raise ValueError(f"the workbook has no sheet {sheet!r}") + return { + BANDS_CSV: to_csv_bytes(BANDS_HEADER, extract_bands(tables[BANDS_SHEET].rows)), + SECTIONS_CSV: to_csv_bytes( + SECTIONS_HEADER, extract_sections(tables[SECTIONS_SHEET].rows) + ), + } + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def provenance(name: str, payload: bytes, ods: Path, access_date: str) -> dict: + source = ods.read_bytes() + bands = name == BANDS_CSV + return { + "kind": "uk_firm_ct_liability_fixture", + "schema_version": 1, + "period": f"financial year {FINANCIAL_YEAR} (1 April 2024 to 31 March 2025)", + "accessed": access_date, + "url": ODS_URL, + "landing_page": LANDING_PAGE, + "collection_page": COLLECTION_PAGE, + "edition": EDITION, + "publisher": "HM Revenue and Customs", + "licence": "Open Government Licence v3.0", + "sha256": _sha256(source), + "size_bytes": len(source), + "source_file": ods.name, + "sheet": BANDS_SHEET if bands else SECTIONS_SHEET, + "tables": ( + [BANDS_AMOUNT_TABLE, BANDS_COUNT_TABLE] + if bands + else [SECTIONS_AMOUNT_TABLE, SECTIONS_COUNT_TABLE] + ), + "column": FINANCIAL_YEAR, + "method": ( + "Every figure was read from the downloaded workbook on the access " + "date by tools/extract_uk_firm_ct_tables.py; none was filled from " + "memory. Counts are as published (rounded by HMRC to the nearest " + "5) and amounts are GBP million as published (rounded to the " + "nearest million). " + + ( + "Band edges are parsed from the band labels (lower exclusive, " + "upper inclusive, 'm' = million). Table 9A has no row for the " + "0 band and no liability for all returns, so those cells are " + "blank. Earlier editions numbered this table 10; in the 2026 " + "edition Tables 10A,B are trading turnover by band." + if bands + else "HMRC section U is 'Overseas; Unclassified, Dormant and " + "Non-trading', not SIC section U alone. This table is held " + "out of the profit draw and used only to check it." + ) + ), + "liability_concept": ( + "The tables' 'tax liability' total equals 'Corporation Tax " + "payable' in Table 5A of the same workbook: after double taxation " + "relief and other charges and reliefs, including ring fence " + "Corporation Tax and the supplementary charge." + ), + "tool": "tools/extract_uk_firm_ct_tables.py", + "command": ( + "uv run --no-sync python tools/extract_uk_firm_ct_tables.py " + "--ods /corporation_tax_data_tables_2026.ods" + ), + "extraction_date": dt.date.today().isoformat(), + "file": { + "name": name, + "sha256": _sha256(payload), + "bytes": len(payload), + "rows": payload.count(b"\n") - 1, + "columns": list(BANDS_HEADER if bands else SECTIONS_HEADER), + }, + } + + +def _iso_date(value: str) -> str: + try: + return dt.date.fromisoformat(value).isoformat() + except ValueError: + raise argparse.ArgumentTypeError( + f"access date {value!r} is not YYYY-MM-DD" + ) from None + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--ods", type=Path, required=True) + parser.add_argument("--out", type=Path, default=DEFAULT_OUT) + parser.add_argument("--access-date", type=_iso_date, default=ACCESS_DATE) + parser.add_argument( + "--check", + action="store_true", + help="exit 1 if a committed CSV differs from a fresh extraction", + ) + args = parser.parse_args(argv) + payloads = extract(args.ods) + if args.check: + stale = [ + name + for name, payload in payloads.items() + if not (args.out / name).is_file() + or (args.out / name).read_bytes() != payload + ] + for name in stale: + print(f"stale or missing: {name}", file=sys.stderr) + if not stale: + print(f"up to date: {', '.join(payloads)}") + return 1 if stale else 0 + args.out.mkdir(parents=True, exist_ok=True) + for name, payload in payloads.items(): + (args.out / name).write_bytes(payload) + record = provenance(name, payload, args.ods, args.access_date) + (args.out / f"{name}.provenance.json").write_text( + json.dumps(record, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" + ) + print(f"wrote {args.out / name}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/extract_uk_firm_employment_allowance_takeup.py b/tools/extract_uk_firm_employment_allowance_takeup.py new file mode 100644 index 0000000000..240fabda0f --- /dev/null +++ b/tools/extract_uk_firm_employment_allowance_takeup.py @@ -0,0 +1,403 @@ +#!/usr/bin/env python3 +"""Extract HMRC Employment Allowance take-up tables for the UK firm claim draw. + +Reads HMRC *Employment Allowance take-up statistics: 2024 to 2025 tax year +estimates* (``Employment_Allowance_2024-2025.ods``, published 9:30am 25 June +2025), column *2024 to 2025 tax year: Employers benefitting from EA* (and its +*% of EA beneficiaries* neighbour), and writes three CSVs: + +``hmrc_ea_takeup_by_size.csv`` from sheet ``5_Employer_size_breakdown``:: + + business_size,employers_benefitting,share_percent + +one row per published band (``1-9``, ``10-49``, ``50-249``, ``250+``) and a +``Total`` row. Size is the PAYE scheme's employee count at the end of the +tax year. A suppressed cell keeps HMRC's marker (``<500``, ``<1``) as text: +it is never turned into a number. + +``hmrc_ea_takeup_by_sector.csv`` from sheet ``2_Sector_breakdown``:: + + sic_section,sic_description,employers_benefitting,share_percent + +one row per HMRC sector (single SIC 2007 section letters, and ``B,D,E,O,U`` +for HMRC's pooled *Other*) and a ``Total`` row. + +``hmrc_ea_takeup_by_region.csv`` from sheet ``3_Regional_breakdown``:: + + region_code,region_description,employers_benefitting,share_percent + +one row per region as published (GSS codes for the English regions, HMRC's +``W99999999``, ``S99999999`` and ``N99999999`` pseudo codes for the nations) +and a ``Total`` row. + +Counts are as published (rounded by HMRC to the nearest 1,000, thousands +separators removed); shares are whole percent as published. Cases without +size, sector or region information were apportioned by HMRC over the known +distribution. + +The workbook is read with ``uk_runtime/ods_tables.py`` (standard library +only), loaded from its file when a workbook is read, so engine-free CI, which +reads the committed CSVs, never runs this reader. + +Usage:: + + uv run --no-sync python tools/extract_uk_firm_employment_allowance_takeup.py \\ + --ods /Employment_Allowance_2024-2025.ods + + # Exit 1 if re-extraction would change a committed CSV's bytes. + uv run --no-sync python tools/extract_uk_firm_employment_allowance_takeup.py \\ + --ods /Employment_Allowance_2024-2025.ods --check +""" + +from __future__ import annotations + +import argparse +import csv +import datetime as dt +import hashlib +import importlib.util +import io +import json +import re +import sys +from collections.abc import Sequence +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_employment_allowance_takeup_2024_25" +) +ODS_TABLES = ( + REPOSITORY_ROOT + / "packages" + / "microcosm-build" + / "src" + / "microcosm" + / "build" + / "uk_runtime" + / "ods_tables.py" +) + +ODS_URL = ( + "https://assets.publishing.service.gov.uk/media/684bf34372e2ed81c079700c/" + "Employment_Allowance_2024-2025.ods" +) +LANDING_PAGE = ( + "https://www.gov.uk/government/statistics/" + "employment-allowance-take-up-2024-to-2025-tax-year-estimate" +) +EDITION = "Employment Allowance take-up statistics: 2024 to 2025 tax year estimates" +PUBLISHED = "2025-06-25" +#: The committed fixture's recorded access date: the default for +#: ``--access-date``, which the person who downloads the workbook sets. +ACCESS_DATE = "2026-11-22" + +COVER_SHEET = "Cover_Sheet" +PUBLICATION_LINE = ( + "The data tables in this spreadsheet were originally published at 9:30am " + "25 June 2025." +) +TAX_YEAR = "2024 to 2025" +COUNT_HEADER = f"{TAX_YEAR} tax year: Employers benefitting from EA" +SHARE_HEADER = f"{TAX_YEAR} tax year: % of EA beneficiaries" + +SIZE_SHEET = "5_Employer_size_breakdown" +SECTOR_SHEET = "2_Sector_breakdown" +REGION_SHEET = "3_Regional_breakdown" + +SIZE_CSV = "hmrc_ea_takeup_by_size.csv" +SECTOR_CSV = "hmrc_ea_takeup_by_sector.csv" +REGION_CSV = "hmrc_ea_takeup_by_region.csv" + +SIZE_HEADER = ("business_size", "employers_benefitting", "share_percent") +SECTOR_HEADER = ( + "sic_section", + "sic_description", + "employers_benefitting", + "share_percent", +) +REGION_HEADER = ( + "region_code", + "region_description", + "employers_benefitting", + "share_percent", +) + +#: The band labels sheet 5 must carry, in order. +SIZE_BANDS = ("1-9", "10-49", "50-249", "250+") +#: A whole count with optional thousands separators, or a suppressed marker. +_COUNT = re.compile(r"^(?:\d{1,3}(?:,\d{3})*|\d+)$") +_SUPPRESSED = re.compile(r"^<\d+$") + + +def _text(value: Any) -> str: + if isinstance(value, float) and value == int(value): + value = int(value) + return "" if value is None else " ".join(str(value).split()) + + +def _cell(value: Any, what: str) -> str: + """A published count or share: digits without separators, or the marker.""" + + text = _text(value) + if _SUPPRESSED.match(text): + return text + if not _COUNT.match(text): + raise ValueError(f"{what}: expected a count or a ' tuple[int, int, int]: + """The header row's index and its 2024-25 count and share columns.""" + + headers = [i for i, row in enumerate(rows) if row and _text(row[0]) == first] + if len(headers) != 1: + raise ValueError(f"header row starting {first!r} found {len(headers)}x") + header = [_text(cell) for cell in rows[headers[0]]] + for label in (COUNT_HEADER, SHARE_HEADER): + if header.count(label) != 1: + raise ValueError(f"column {label!r} found {header.count(label)}x") + return headers[0], header.index(COUNT_HEADER), header.index(SHARE_HEADER) + + +def _body(rows: Sequence[Sequence[Any]], start: int) -> list[Sequence[Any]]: + """Rows after the header up to and including the ``Total`` row.""" + + out = [] + for row in rows[start + 1 :]: + if not row or not _text(row[0]): + continue + out.append(row) + if _text(row[0]) == "Total": + return out + raise ValueError("table has no Total row") + + +def extract_size(rows: Sequence[Sequence[Any]]) -> list[tuple[str, ...]]: + start, count, share = _columns(rows, "Business size") + out = [ + ( + _text(row[0]), + _cell(row[count], f"size {_text(row[0])}"), + _cell(row[share], f"size {_text(row[0])} share"), + ) + for row in _body(rows, start) + ] + labels = tuple(row[0] for row in out) + if labels != (*SIZE_BANDS, "Total"): + raise ValueError(f"size bands are {labels}, not {(*SIZE_BANDS, 'Total')}") + return out + + +def _coded( + rows: Sequence[Sequence[Any]], first: str, what: str +) -> list[tuple[str, ...]]: + start, count, share = _columns(rows, first) + out = [] + for row in _body(rows, start): + code = _text(row[0]) + out.append( + ( + code, + _text(row[1]), + _cell(row[count], f"{what} {code}"), + _cell(row[share], f"{what} {code} share"), + ) + ) + return out + + +def extract_sector(rows: Sequence[Sequence[Any]]) -> list[tuple[str, ...]]: + out = _coded(rows, "ONS SIC Code", "sector") + for code, *_ in out[:-1]: + if not re.fullmatch(r"[A-U](?:,[A-U])*", code): + raise ValueError(f"unexpected sector code {code!r}") + return out + + +def extract_region(rows: Sequence[Sequence[Any]]) -> list[tuple[str, ...]]: + out = _coded(rows, "ONS Region Code", "region") + for code, *_ in out[:-1]: + if not re.fullmatch(r"[ENSW]\d{8}", code): + raise ValueError(f"unexpected region code {code!r}") + return out + + +def to_csv_bytes(header: Sequence[str], rows: list[tuple[str, ...]]) -> bytes: + buffer = io.StringIO() + writer = csv.writer(buffer, lineterminator="\n") + writer.writerow(header) + writer.writerows(rows) + return buffer.getvalue().encode("utf-8") + + +def _read_ods_tables(ods: Path) -> dict[str, Any]: + # Loaded from its file, not through the uk_runtime package, so reading a + # workbook needs neither the package's other imports nor numpy. + spec = importlib.util.spec_from_file_location("_ods_tables", ODS_TABLES) + if spec is None or spec.loader is None: + raise RuntimeError(f"cannot load {ODS_TABLES}") + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module.read_ods_tables(ods, label="HMRC Employment Allowance take-up") + + +def extract(ods: Path) -> dict[str, bytes]: + """The three CSVs' bytes, keyed by file name.""" + + tables = _read_ods_tables(ods) + for sheet in (COVER_SHEET, SIZE_SHEET, SECTOR_SHEET, REGION_SHEET): + if sheet not in tables: + raise ValueError(f"the workbook has no sheet {sheet!r}") + cover = [_text(row[0]) for row in tables[COVER_SHEET].rows if row] + if not cover or cover[0] != EDITION: + raise ValueError(f"workbook is {cover[:1]!r}, not {EDITION!r}") + if PUBLICATION_LINE not in cover: + raise ValueError(f"cover sheet lacks {PUBLICATION_LINE!r}") + return { + SIZE_CSV: to_csv_bytes(SIZE_HEADER, extract_size(tables[SIZE_SHEET].rows)), + SECTOR_CSV: to_csv_bytes( + SECTOR_HEADER, extract_sector(tables[SECTOR_SHEET].rows) + ), + REGION_CSV: to_csv_bytes( + REGION_HEADER, extract_region(tables[REGION_SHEET].rows) + ), + } + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +_SHEETS = {SIZE_CSV: SIZE_SHEET, SECTOR_CSV: SECTOR_SHEET, REGION_CSV: REGION_SHEET} +_HEADERS = {SIZE_CSV: SIZE_HEADER, SECTOR_CSV: SECTOR_HEADER, REGION_CSV: REGION_HEADER} +_NOTES = { + SIZE_CSV: ( + "Size is the number of employees on the claiming PAYE scheme at the " + "end of the tax year (sheet note); employers may run several PAYE " + "schemes. The 250+ count and share are published suppressed ('<500', " + "'<1') and are kept as those markers, never as numbers. The bands " + "sum to 1,222,000 against a published total of 1,223,000 (HMRC: " + "'Sum of employer sizes may not sum to the total due to rounding')." + ), + SECTOR_CSV: ( + "Sections are SIC 2007 letters; HMRC pools B, D, E, O and U as " + "'Other', kept here under the code 'B,D,E,O,U' as published. T's " + "description is HMRC's shortened 'Activities of households as " + "employers...'. Sector came from the ONS Business Lookup Table with a " + "94% match rate; unmatched cases were apportioned by HMRC." + ), + REGION_CSV: ( + "Codes as published: GSS E12 codes for the English regions and " + "HMRC's W99999999, S99999999 and N99999999 for Wales, Scotland and " + "Northern Ireland. Region is the claiming enterprise's postcode in " + "the ONS Business Lookup Table (94% match rate); unmatched cases were " + "apportioned by HMRC." + ), +} + + +def provenance(name: str, payload: bytes, ods: Path, access_date: str) -> dict: + source = ods.read_bytes() + return { + "kind": "uk_firm_employment_allowance_takeup_fixture", + "schema_version": 1, + "period": "tax year 2024-25", + "accessed": access_date, + "url": ODS_URL, + "landing_page": LANDING_PAGE, + "edition": EDITION, + "published": PUBLISHED, + "published_note": ( + f"Cover_Sheet: '{PUBLICATION_LINE}' The next publication was due June 2026." + ), + "publisher": "HM Revenue and Customs", + "licence": "Open Government Licence v3.0", + "sha256": _sha256(source), + "size_bytes": len(source), + "source_file": ods.name, + "sheet": _SHEETS[name], + "sheets_read": [COVER_SHEET, _SHEETS[name]], + "columns": [COUNT_HEADER, SHARE_HEADER], + "method": ( + "Every figure was read from the downloaded workbook on the access " + "date by tools/extract_uk_firm_employment_allowance_takeup.py; " + "none was filled from memory. Counts are as published, rounded by " + "HMRC to the nearest 1,000, with thousands separators removed; " + "shares are whole percent as published. Labels are whitespace-" + "normalised (the region sheet's 'Total ' code loses its trailing " + "space). An employer counts as benefitting when some allowance " + "was offset against its employer NICs paid to HMRC (Cover_Sheet). " + + _NOTES[name] + ), + "tool": "tools/extract_uk_firm_employment_allowance_takeup.py", + "command": ( + "uv run --no-sync python " + "tools/extract_uk_firm_employment_allowance_takeup.py " + "--ods /Employment_Allowance_2024-2025.ods" + ), + "extraction_date": dt.date.today().isoformat(), + "file": { + "name": name, + "sha256": _sha256(payload), + "bytes": len(payload), + "rows": payload.count(b"\n") - 1, + "columns": list(_HEADERS[name]), + }, + } + + +def _iso_date(value: str) -> str: + try: + return dt.date.fromisoformat(value).isoformat() + except ValueError: + raise argparse.ArgumentTypeError( + f"access date {value!r} is not YYYY-MM-DD" + ) from None + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--ods", type=Path, required=True) + parser.add_argument("--out", type=Path, default=DEFAULT_OUT) + parser.add_argument("--access-date", type=_iso_date, default=ACCESS_DATE) + parser.add_argument( + "--check", + action="store_true", + help="exit 1 if a committed CSV differs from a fresh extraction", + ) + args = parser.parse_args(argv) + payloads = extract(args.ods) + if args.check: + stale = [ + name + for name, payload in payloads.items() + if not (args.out / name).is_file() + or (args.out / name).read_bytes() != payload + ] + for name in stale: + print(f"stale or missing: {name}", file=sys.stderr) + if not stale: + print(f"up to date: {', '.join(payloads)}") + return 1 if stale else 0 + args.out.mkdir(parents=True, exist_ok=True) + for name, payload in payloads.items(): + (args.out / name).write_bytes(payload) + record = provenance(name, payload, args.ods, args.access_date) + (args.out / f"{name}.provenance.json").write_text( + json.dumps(record, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" + ) + print(f"wrote {args.out / name}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/extract_uk_firm_empty_property_tables.py b/tools/extract_uk_firm_empty_property_tables.py new file mode 100644 index 0000000000..396eb68452 --- /dev/null +++ b/tools/extract_uk_firm_empty_property_tables.py @@ -0,0 +1,444 @@ +#!/usr/bin/env python3 +"""Extract MHCLG empty property relief tables for the UK firm empty property draw. + +Reads three MHCLG *National non-domestic rates collected by councils in +England* files and writes three CSVs with published values only: + +- ``mhclg_nndr1_empty_hereditaments.csv``: England hereditaments in receipt of + mandatory empty premises relief, total and by the six sub-categories, as at + 31 December 2023 (NNDR1 2024-25 supplementary table) and 31 December 2024 + (NNDR1 2025-26 supplementary table), sheet ``NNDR1S Hereditaments Data``; +- ``mhclg_nndr1_empty_relief_value.csv``: England estimated value (£) of + empty property relief, total and by sub-category, for 2024-25 and 2025-26 + (sheet ``NNDR1S Relief data``; the 2025-26 edition prints the values with a + minus sign, kept as published); +- ``mhclg_nndr3_2024_25.csv``: 2024-25 outturn items from the NNDR3 Tables + 1-3 workbook: gross rates payable and empty premises relief (£ million), + hereditaments on the list at 30 September (thousands), aggregate rateable + value (£ million) and the two multipliers (pence). + +Columns are found by MHCLG's variable names (``hdit_mr_empty*``, +``value_empty*``) and row labels, not by position. openpyxl and the ODS reader +are imported only when a file is read, so engine-free CI never needs them. + +Usage:: + + uv run --no-sync python tools/extract_uk_firm_empty_property_tables.py \\ + --nndr1-2024-25 /NNDR1_2024-25_Supplementary_table.xlsx \\ + --nndr1-2025-26 /NNDR1_2025-26_Supplementary_table__ecomms_.xlsx \\ + --nndr3-ods /NNDR3_2024-25_Tables_1-3_accessible_gov.uk__Values_only__-_3rd_Release.ods + + # Add --check to exit 1 if re-extraction would change a committed CSV. +""" + +from __future__ import annotations + +import argparse +import csv +import datetime as dt +import hashlib +import io +import json +import re +import sys +from collections.abc import Sequence +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_empty_property_2024_25" +) +PROVENANCE_NAME = "provenance.json" +HEREDITAMENTS_CSV = "mhclg_nndr1_empty_hereditaments.csv" +RELIEF_CSV = "mhclg_nndr1_empty_relief_value.csv" +NNDR3_CSV = "mhclg_nndr3_2024_25.csv" +ACCESS_DATE = "2026-11-23" + +_GOV = "https://www.gov.uk/government/statistics/" +_ASSETS = "https://assets.publishing.service.gov.uk/media/" +SOURCES = { + "nndr1_2024_25": { + "landing_page": _GOV + + "national-non-domestic-rates-collected-by-councils-in-england-" + "forecast-2024-to-2025", + "url": _ASSETS + + "663b98e474933dccbbb6c431/NNDR1_2024-25_Supplementary_table.xlsx", + "edition": ( + "National non-domestic rates collected by councils in England: " + "forecast 2024 to 2025; supplementary data tables (added 9 May 2024)" + ), + }, + "nndr1_2025_26": { + "landing_page": _GOV + + "national-non-domestic-rates-collected-by-councils-in-england-" + "forecast-2025-to-2026", + "url": _ASSETS + + "67d2c9c4814acba3755e97c1/NNDR1_2025-26_Supplementary_table__ecomms_.xlsx", + "edition": ( + "National non-domestic rates collected by councils in England: " + "forecast 2025 to 2026; supplementary data tables (added 13 March 2025)" + ), + }, + "nndr3_2024_25": { + "landing_page": _GOV + + "national-non-domestic-rates-collected-by-councils-in-england-2024-to-2025", + "url": _ASSETS + + "6977f8533fd50ac304b79790/NNDR3_2024-25_Tables_1-3_accessible_gov.uk__" + "Values_only__-_3rd_Release.ods", + "edition": ( + "National non-domestic rates collected by councils in England: 2024 " + "to 2025; Tables 1-3: England, 3rd release (updated 27 January 2026)" + ), + }, +} + +HEREDITAMENT_SHEET = "NNDR1S Hereditaments Data" +RELIEF_SHEET = "NNDR1S Relief data" +#: The six empty sub-categories partition the total (checked on extraction). +HEREDITAMENT_TOTAL = "hdit_mr_empty" +HEREDITAMENT_PARTS = ( + "hdit_mr_emptyind", + "hdit_mr_emptylisted", + "hdit_mr_emptycasc", + "hdit_mr_emptycharity", + "hdit_mr_emptyoth", + "hdit_mr_emptyabove", +) +RELIEF_TOTAL = "value_empty" +RELIEF_PARTS = ( + "value_emptyind", + "value_emptylisted", + "value_emptycasc", + "value_emptycharity", + "value_emptyoth", + "value_emptyabove", +) +HEREDITAMENT_HEADER = ("snapshot_date", "variable", "label", "england_hereditaments") +RELIEF_HEADER = ("forecast_year", "variable", "label", "england_value_gbp") +NNDR3_HEADER = ("item", "table", "row_label", "year", "value", "unit") +NNDR3_YEAR = "2024 to 2025" +#: item, sheet, row label prefix, unit. +NNDR3_ITEMS = ( + ("gross_rates_payable", "Table_1", "Gross rates payable in year", "GBP million"), + ("empty_premises_relief", "Table_2", "Of which empty premises", "GBP million"), + ( + "hereditaments_30_sept", + "Table_1a", + "Number of hereditaments on rating list as at 30 Sept", + "thousand", + ), + ( + "aggregate_rateable_value_30_sept", + "Table_1a", + "Total aggregate rateable value of all hereditaments", + "GBP million", + ), + ( + "small_business_multiplier", + "Table_1a", + "Small business rate multiplier", + "pence", + ), + ( + "standard_multiplier", + "Table_1a", + "National non-domestic rates multiplier", + "pence", + ), +) +_MONTHS = {"December": 12} + + +def _text(value: Any) -> str: + return "" if value is None else " ".join(str(value).split()) + + +def _number(value: Any, label: str) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError(f"{label}: expected a number, got {value!r}") + return float(value) + + +def _format(value: float) -> str: + return str(int(value)) if value == int(value) else repr(value) + + +def _variable_row(rows: list[tuple[Any, ...]], marker: str) -> int: + found = [i for i, row in enumerate(rows[:12]) if marker in map(_text, row)] + if len(found) != 1: + raise ValueError(f"variable-name row with {marker!r} found {len(found)}x") + return found[0] + + +def _label_row(rows: list[tuple[Any, ...]], at: int, column: int, prefix: str) -> int: + for candidate in (at - 1, at + 1): + row = rows[candidate] if 0 <= candidate < len(rows) else () + if column < len(row) and _text(row[column]).startswith(prefix): + return candidate + raise ValueError(f"no label row starting {prefix!r} next to row {at}") + + +def _england_row(rows: list[tuple[Any, ...]]) -> tuple[Any, ...]: + found = [row for row in rows if len(row) > 2 and _text(row[2]) == "England"] + if len(found) != 1: + raise ValueError(f"England row found {len(found)}x") + return found[0] + + +def _snapshot(title: str) -> str: + match = re.search(r"as at 31 (December) (\d{4})", title) + if not match: + raise ValueError(f"no 'as at 31 December YYYY' in {title!r}") + return dt.date(int(match.group(2)), _MONTHS[match.group(1)], 31).isoformat() + + +def _forecast_year(title: str) -> str: + match = re.search(r"in (\d{4}-\d{2})\b", title) + if not match: + raise ValueError(f"no forecast year in {title!r}") + return match.group(1) + + +def extract_supplementary( + hereditaments: list[tuple[Any, ...]], relief: list[tuple[Any, ...]] +) -> tuple[list[tuple[Any, ...]], list[tuple[Any, ...]]]: + """Hereditament and relief rows from one supplementary workbook's sheets.""" + + out_h, out_r = [], [] + for rows, total, parts, prefix, out, kind in ( + ( + hereditaments, + HEREDITAMENT_TOTAL, + HEREDITAMENT_PARTS, + "Mandatory Relief for empty", + out_h, + "hereditaments", + ), + ( + relief, + RELIEF_TOTAL, + RELIEF_PARTS, + "Estimated value of empty property relief", + out_r, + "relief", + ), + ): + at = _variable_row(rows, total) + names = [_text(cell) for cell in rows[at]] + labels = rows[_label_row(rows, at, names.index(total), prefix)] + england = _england_row(rows) + key = ( + _snapshot(_text(rows[0][0])) + if kind == "hereditaments" + else _forecast_year(_text(rows[0][0])) + ) + values = {} + for name in (total, *parts): + if names.count(name) != 1: + raise ValueError(f"{kind}: variable {name} found {names.count(name)}x") + column = names.index(name) + values[name] = _number(england[column], f"{kind} {name}") + out.append((key, name, _text(labels[column]), _format(values[name]))) + # The hereditament sub-categories partition the total; the relief + # values do not quite (2024-25: £1,023.9m of £1,040.9m), as published. + if kind == "hereditaments" and sum(values[p] for p in parts) != values[total]: + raise ValueError(f"{kind}: sub-categories do not sum to {total}") + return out_h, out_r + + +def extract_nndr3(tables: dict[str, Any]) -> list[tuple[Any, ...]]: + out = [] + for item, sheet, prefix, unit in NNDR3_ITEMS: + rows = tables[sheet].rows + headers = [i for i, row in enumerate(rows) if row and _text(row[0]) == "Year"] + if len(headers) != 1: + raise ValueError(f"{sheet}: 'Year' header row found {len(headers)}x") + header = [_text(c) for c in rows[headers[0]]] + columns = [i for i, h in enumerate(header) if h.startswith(NNDR3_YEAR)] + if len(columns) != 1: + raise ValueError(f"{sheet}: column {NNDR3_YEAR!r} found {len(columns)}x") + found = [row for row in rows if row and _text(row[0]).startswith(prefix)] + if len(found) != 1: + raise ValueError(f"{sheet}: row {prefix!r} found {len(found)}x") + value = _number(found[0][columns[0]], f"{sheet} {prefix}") + out.append( + (item, sheet, _text(found[0][0]), header[columns[0]], _format(value), unit) + ) + return out + + +def to_csv_bytes(header: Sequence[str], rows: list[tuple[Any, ...]]) -> bytes: + buffer = io.StringIO() + writer = csv.writer(buffer, lineterminator="\n") + writer.writerow(header) + writer.writerows(rows) + return buffer.getvalue().encode("utf-8") + + +def _read_xlsx(path: Path) -> tuple[list[tuple[Any, ...]], list[tuple[Any, ...]]]: + import openpyxl # noqa: PLC0415 - local-only dependency, kept out of CI imports + + book = openpyxl.load_workbook(path, read_only=True, data_only=True) + try: + return ( + list(book[HEREDITAMENT_SHEET].iter_rows(values_only=True)), + list(book[RELIEF_SHEET].iter_rows(values_only=True)), + ) + finally: + book.close() + + +def extract(nndr1_2425: Path, nndr1_2526: Path, nndr3: Path) -> dict[str, bytes]: + from microcosm.build.uk_runtime.ods_tables import ( # noqa: PLC0415 + read_ods_tables, + ) + + hereditaments: list[tuple[Any, ...]] = [] + relief: list[tuple[Any, ...]] = [] + for path in (nndr1_2425, nndr1_2526): + h, r = extract_supplementary(*_read_xlsx(path)) + hereditaments += h + relief += r + nndr3_rows = extract_nndr3(read_ods_tables(nndr3, label="MHCLG NNDR3 2024-25")) + return { + HEREDITAMENTS_CSV: to_csv_bytes(HEREDITAMENT_HEADER, hereditaments), + RELIEF_CSV: to_csv_bytes(RELIEF_HEADER, relief), + NNDR3_CSV: to_csv_bytes(NNDR3_HEADER, nndr3_rows), + } + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _iso_date(value: str) -> str: + try: + return dt.date.fromisoformat(value).isoformat() + except ValueError: + raise argparse.ArgumentTypeError( + f"access date {value!r} is not YYYY-MM-DD" + ) from None + + +def provenance( + inputs: dict[str, Path], payloads: dict[str, bytes], access_date: str +) -> dict[str, Any]: + sources = {} + for key, path in inputs.items(): + data = path.read_bytes() + sources[key] = { + **SOURCES[key], + "publisher": "Ministry of Housing, Communities and Local Government", + "file": path.name, + "size_bytes": len(data), + "sha256": _sha256(data), + "licence": "Open Government Licence v3.0", + } + sources["nndr1_2024_25"]["sheets"] = [HEREDITAMENT_SHEET, RELIEF_SHEET] + sources["nndr1_2025_26"]["sheets"] = [HEREDITAMENT_SHEET, RELIEF_SHEET] + sources["nndr3_2024_25"]["sheets"] = sorted({item[1] for item in NNDR3_ITEMS}) + return { + "kind": "uk_firm_empty_property_fixture", + "schema_version": 1, + "period": ( + "2024-25: relief counts as at 31 December 2023 and 2024, relief " + "value forecasts for 2024-25 and 2025-26, and the 2024-25 NNDR3 " + "outturn" + ), + "accessed": access_date, + "method": ( + "Values were read from the downloaded files on the access date by " + "tools/extract_uk_firm_empty_property_tables.py, from the England " + "row of each supplementary sheet (columns found by MHCLG variable " + "name) and the '2024 to 2025' column of NNDR3 Tables 1, 1a and 2; " + "none was filled from memory." + ), + "sources": sources, + "coverage": ( + "Counts are hereditaments in receipt of mandatory empty premises " + "relief at the snapshot date, not all empty hereditaments: an " + "empty property past its 3-month (6 for industrial) exemption " + "pays full rates and is not counted. The six sub-categories " + "(industrial above the exemption threshold, listed building, " + "community amateur sports club, charity, not in the previous " + "four, non-industrial above the exemption threshold) partition " + "the total; the relief value sub-categories do not quite sum to " + "the relief total as published. No source gives the rateable value of empty " + "property, empty shares by property type, or empty durations." + ), + "caveats": [ + "NNDR1 2024-25 supplementary Note 7: the split of empty property " + "relief by category was first published in 2024-25 and was " + "validated against earlier unvalidated data; use with caution.", + "NNDR1 2025-26 Table 4 Note 25: for 2024 the empty premises " + "hereditament count is under investigation for 2 local " + "authorities; data are as provided by the authorities.", + "The NNDR1 2025-26 relief labels read 'to be granted in 2024-25' " + "as published; the forecast year is taken from the sheet title, " + "and the total equals Table 2's 2025-26 empty premises forecast " + "(£1,084.979229 million).", + "NNDR1 2024-25 supplementary Note 3: Three Rivers and Watford " + "supplied no supplementary figures for 31 December 2023.", + ], + "extraction_date": dt.date.today().isoformat(), + "tool": "tools/extract_uk_firm_empty_property_tables.py", + "files": { + name: { + "sha256": _sha256(payload), + "bytes": len(payload), + "rows": payload.count(b"\n") - 1, + } + for name, payload in payloads.items() + }, + } + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--nndr1-2024-25", type=Path, required=True) + parser.add_argument("--nndr1-2025-26", type=Path, required=True) + parser.add_argument("--nndr3-ods", type=Path, required=True) + parser.add_argument("--out", type=Path, default=DEFAULT_OUT) + parser.add_argument("--check", action="store_true") + parser.add_argument("--access-date", type=_iso_date, default=ACCESS_DATE) + args = parser.parse_args(argv) + inputs = { + "nndr1_2024_25": args.nndr1_2024_25.resolve(), + "nndr1_2025_26": args.nndr1_2025_26.resolve(), + "nndr3_2024_25": args.nndr3_ods.resolve(), + } + payloads = extract(*inputs.values()) + if args.check: + stale = [ + name + for name, payload in payloads.items() + if not (args.out / name).is_file() + or (args.out / name).read_bytes() != payload + ] + for name in stale: + print(f"stale or missing: {name}", file=sys.stderr) + if stale: + return 1 + print("the empty property CSVs match the downloads") + return 0 + args.out.mkdir(parents=True, exist_ok=True) + for name, payload in payloads.items(): + (args.out / name).write_bytes(payload) + print(f"wrote {args.out / name}") + record = provenance(inputs, payloads, args.access_date) + (args.out / PROVENANCE_NAME).write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8" + ) + print(f"wrote {args.out / PROVENANCE_NAME}") + 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/extract_uk_firm_pay_distribution_table.py b/tools/extract_uk_firm_pay_distribution_table.py new file mode 100644 index 0000000000..5377e445a0 --- /dev/null +++ b/tools/extract_uk_firm_pay_distribution_table.py @@ -0,0 +1,265 @@ +#!/usr/bin/env python3 +"""Extract ONS ASHE section annual gross pay percentiles for UK firms. + +Reads the ONS *Earnings and hours worked, industry by two-digit SIC: ASHE +Table 4*, 2025 revised edition (``ashetable42025revised.zip``), member +``Table 4.7a Annual pay - Gross 2025``, sheet ``All`` (all employee jobs), and +writes ``ashe_section_annual_pay_percentiles.csv`` with one row per SIC 2007 +section A-U plus one ``ALL`` row (the sheet's ``ALL EMPLOYEES`` row): + +``sic_section,description,jobs_thousand,mean,p10,p20,p25,p30,p40,p50,p60,p70, +p75,p80,p90`` + +``p50`` is the sheet's ``Median`` column; the others are its ``Percentiles`` +columns and ``Mean``, pounds a year. A cell ONS does not publish keeps the ONS +marker (``x`` unreliable, ``:`` not available) as its value; it is never +written as 0 or blank. ASHE 2025 annual estimates are tax year 2024-25. + +Usage:: + + uv run --no-sync python tools/extract_uk_firm_pay_distribution_table.py \\ + --zip /ashetable42025revised.zip [--check] +""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import io +import json +import sys +import zipfile +from collections.abc import Sequence +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_pay_distribution_2024" +) +CSV_NAME = "ashe_section_annual_pay_percentiles.csv" +PROVENANCE_NAME = CSV_NAME + ".provenance.json" +LANDING_PAGE = ( + "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/" + "earningsandworkinghours/datasets/industry2digitsicashetable4" +) +ZIP_URL = ( + "https://www.ons.gov.uk/file?uri=/employmentandlabourmarket/peopleinwork/" + "earningsandworkinghours/datasets/industry2digitsicashetable4/2025revised/" + "ashetable42025revised.zip" +) +EDITION = "2025 revised" +ACCESS_DATE = "2026-11-22" +MEMBER_MARKER = "Table 4.7a" +MEMBER_SUFFIX = "Annual pay - Gross 2025.xlsx" +SHEET = "All" +TITLE_MARKERS = ( + "SIC2007 Table 4", + "Annual pay - Gross", + "For all employee jobs", + "United Kingdom 2025", +) +HEADER_ROW = 5 +ALL_LABEL = "ALL EMPLOYEES" +ALL_KEY = "ALL" +SECTIONS = tuple("ABCDEFGHIJKLMNOPQRSTU") +UNPUBLISHED_MARKERS = ("x", ":") +#: Percentile columns the sheet labels with a number, in sheet order. +PERCENTILES = (10, 20, 25, 30, 40, 60, 70, 75, 80, 90) +HEADER = ( + "sic_section", + "description", + "jobs_thousand", + "mean", + "p10", + "p20", + "p25", + "p30", + "p40", + "p50", + "p60", + "p70", + "p75", + "p80", + "p90", +) + + +def _cell(value: Any) -> str: + """A number as ``repr(float)``, or the ONS marker the cell holds.""" + + if isinstance(value, str) and value.strip() in UNPUBLISHED_MARKERS: + return value.strip() + if isinstance(value, bool) or not isinstance(value, (int, float)) or value < 0: + raise ValueError(f"expected a non-negative number or ONS marker: {value!r}") + return repr(float(value)) + + +def _column(header: Sequence[Any], label: Any) -> int: + matches = [ + index + for index, value in enumerate(header) + if value is not None and (value == label or str(value).strip() == str(label)) + ] + if len(matches) != 1: + raise ValueError(f"header row {HEADER_ROW}: {label!r} found {len(matches)}x") + return matches[0] + + +def extract_rows(rows: list[tuple[Any, ...]]) -> tuple[str, list[tuple[str, ...]]]: + title = " ".join(str(rows[0][0]).split()) + for marker in TITLE_MARKERS: + if marker not in title: + raise ValueError(f"title {title!r} lacks {marker!r}") + header = rows[HEADER_ROW - 1] + source = { + "description": _column(header, "Description"), + "code": _column(header, "Code"), + "jobs_thousand": _column(header, "(thousand)"), + "mean": _column(header, "Mean"), + "p50": _column(header, "Median"), + **{f"p{p}": _column(header, p) for p in PERCENTILES}, + } + picked: dict[str, tuple[Any, ...]] = {} + for row in rows[HEADER_ROW:]: + code = "" if row[source["code"]] is None else str(row[source["code"]]) + code = code.strip().lstrip("'").strip() + label = row[source["description"]] + if len(code) == 1 and code.isalpha(): + key = code + elif label is not None and str(label).strip() == ALL_LABEL: + key = ALL_KEY + else: + continue + if key in picked: + raise ValueError(f"row {key} appears twice") + picked[key] = row + if tuple(picked) != (ALL_KEY, *SECTIONS): + raise ValueError(f"rows {list(picked)} are not ALL then sections A-U") + out = [] + for key in (*SECTIONS, ALL_KEY): + row = picked[key] + description = " ".join(str(row[source["description"]]).split()) + out.append( + (key, description, *(_cell(row[source[name]]) for name in HEADER[2:])) + ) + return title, out + + +def to_csv_bytes(rows: list[tuple[str, ...]]) -> bytes: + buffer = io.StringIO() + writer = csv.writer(buffer, lineterminator="\n") + writer.writerow(HEADER) + writer.writerows(rows) + return buffer.getvalue().encode("utf-8") + + +def extract(zip_path: Path) -> tuple[str, list[tuple[str, ...]], str, bytes]: + import openpyxl # noqa: PLC0415 - local-only dependency, kept out of CI imports + + with zipfile.ZipFile(zip_path) as archive: + names = [ + name + for name in archive.namelist() + if MEMBER_MARKER in name and name.endswith(MEMBER_SUFFIX) + ] + if len(names) != 1: + raise ValueError(f"zip members matching {MEMBER_MARKER!r}: {names}") + data = archive.read(names[0]) + book = openpyxl.load_workbook(io.BytesIO(data), read_only=True, data_only=True) + try: + sheet_rows = list(book[SHEET].iter_rows(values_only=True)) + finally: + book.close() + title, rows = extract_rows(sheet_rows) + return title, rows, names[0], data + + +def provenance( + zip_path: Path, member: str, data: bytes, title: str, payload: bytes +) -> dict[str, Any]: + archive = zip_path.read_bytes() + return { + "kind": "uk_firm_pay_distribution_fixture", + "schema_version": 1, + "period": "2024-25", + "accessed": ACCESS_DATE, + "method": ( + "Cells were copied from the downloaded workbook by " + "tools/extract_uk_firm_pay_distribution_table.py; none was filled " + "from memory. p50 is the sheet's Median column. A cell ONS does " + "not publish keeps its marker ('x' unreliable, ':' not available)." + ), + "sources": { + "ons_ashe_table_4": { + "publisher": "Office for National Statistics", + "landing_page": LANDING_PAGE, + "url": ZIP_URL, + "edition": EDITION, + "sha256": hashlib.sha256(archive).hexdigest(), + "size_bytes": len(archive), + "member": member, + "member_sha256": hashlib.sha256(data).hexdigest(), + "sheet": SHEET, + "sheet_title": title, + "reference_period": ( + "ASHE annual estimates are for the tax year that ended on " + "5 April of the reference year: the 2025 edition is " + "2024-25." + ), + "coverage": ( + "Employees on adult rates in the same job for more than a " + "year; all employee jobs, full-time and part-time." + ), + "licence": "Open Government Licence v3.0", + } + }, + "files": { + CSV_NAME: { + "sha256": hashlib.sha256(payload).hexdigest(), + "bytes": len(payload), + "columns": list(HEADER), + } + }, + } + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--zip", 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 CSV; write nothing", + ) + args = parser.parse_args(argv) + zip_path = args.zip.resolve() + title, rows, member, data = extract(zip_path) + payload = to_csv_bytes(rows) + target = args.out / CSV_NAME + if args.check: + if not target.is_file() or target.read_bytes() != payload: + print(f"stale or missing: {CSV_NAME}", file=sys.stderr) + return 1 + print(f"{CSV_NAME} matches the workbook") + return 0 + args.out.mkdir(parents=True, exist_ok=True) + target.write_bytes(payload) + record = provenance(zip_path, member, data, title, payload) + (args.out / PROVENANCE_NAME).write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8" + ) + print(f"wrote {target} ({len(rows)} rows)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/extract_uk_firm_paybill_anchor.py b/tools/extract_uk_firm_paybill_anchor.py new file mode 100644 index 0000000000..fd42903945 --- /dev/null +++ b/tools/extract_uk_firm_paybill_anchor.py @@ -0,0 +1,115 @@ +"""Extract the UK paybill anchors (report-only, ``firm_paybill_anchor.py``). + +Writes ``packages/microcosm-build/tests/fixtures/uk/firm_paybill_anchor_2024/ +paybill_anchors.csv`` from two downloads: + +- the ONS time-series CSV for DTWL (UK wages and salaries, ESA D.11, uses, + current prices, pounds million, seasonally adjusted), Quarterly National + Accounts dataset: the calendar-year 2024 row; +- the ONS/HMRC PAYE Real Time Information reference table, not seasonally + adjusted (``rtinsanov2026.xlsx``): sheet "4. Aggregate pay (UK)", the + twelve months April 2024 to March 2025 summed (no annual figure is + published), and sheet "1. Payrolled employees (UK)", their mean. + +Values are read, never typed. ``--check`` compares a fresh extraction with +the committed CSV. + + uv run --no-sync python tools/extract_uk_firm_paybill_anchor.py \ + --dtwl-csv /dtwl_qna.csv --rti-xlsx /rtinsanov2026.xlsx [--check] +""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import io +import sys +from pathlib import Path + +import openpyxl + +FIXTURE = Path("packages/microcosm-build/tests/fixtures/uk/firm_paybill_anchor_2024") +DTWL_SHA256 = "5948ee2d3da0fe42fab8a27768a18eb6b8ee352e712e02e15c817bf5cb8df1a5" +RTI_SHA256 = "8aafec63ce93a6a8b299c438faf4ce54a535d9ed331c2e2dc30106b8c163748c" +TAX_YEAR = [ + "April 2024", "May 2024", "June 2024", "July 2024", "August 2024", "September 2024", + "October 2024", "November 2024", "December 2024", "January 2025", "February 2025", "March 2025", +] # fmt: skip +COLUMNS = ("anchor", "period", "value", "unit", "detail") + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _dtwl_2024(path: Path) -> float: + with path.open(newline="") as handle: + for row in csv.reader(handle): + if row and row[0].strip() == "2024": + return float(row[1]) + raise ValueError("DTWL CSV has no 2024 row") + + +def _monthly(wb: openpyxl.Workbook, sheet: str) -> dict[str, float]: + out = {} + for row in wb[sheet].iter_rows(values_only=True): + if isinstance(row[0], str) and isinstance(row[1], (int, float)): + out[row[0].strip()] = float(row[1]) + missing = [m for m in TAX_YEAR if m not in out] + if missing: + raise ValueError(f"{sheet} lacks {missing}") + return out + + +def extract(dtwl: Path, rti: Path) -> list[tuple]: + for path, expected in ((dtwl, DTWL_SHA256), (rti, RTI_SHA256)): + if _sha256(path) != expected: + raise ValueError(f"{path.name} sha256 is not the pinned {expected}") + wb = openpyxl.load_workbook(rti, read_only=True, data_only=True) + pay = _monthly(wb, "4. Aggregate pay (UK)") + employees = _monthly(wb, "1. Payrolled employees (UK)") + return [ + ("ons_d11_wages_and_salaries", "2024", _dtwl_2024(dtwl) * 1e6, "GBP", + "ONS DTWL, UK wages and salaries (D.11), uses, current prices, SA; QNA"), + ("paye_rti_aggregate_pay", "2024-25", sum(pay[m] for m in TAX_YEAR), "GBP", + "ONS/HMRC PAYE RTI aggregate pay, UK, NSA; sum of April 2024 to March 2025"), + ("paye_rti_payrolled_employees", "2024-25", sum(employees[m] for m in TAX_YEAR) / 12, "persons", + "ONS/HMRC PAYE RTI payrolled employees, UK, NSA; mean of April 2024 to March 2025"), + ] # fmt: skip + + +def _csv(rows: list[tuple]) -> bytes: + buffer = io.StringIO() + writer = csv.writer(buffer, lineterminator="\n") + writer.writerow(COLUMNS) + for anchor, period, value, unit, detail in rows: + writer.writerow((anchor, period, f"{value:.2f}", unit, detail)) + return buffer.getvalue().encode() + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--dtwl-csv", type=Path, required=True) + parser.add_argument("--rti-xlsx", type=Path, required=True) + parser.add_argument("--out-dir", type=Path, default=FIXTURE) + parser.add_argument("--check", action="store_true") + args = parser.parse_args(argv) + payload = _csv(extract(args.dtwl_csv, args.rti_xlsx)) + target = args.out_dir / "paybill_anchors.csv" + if args.check: + if target.read_bytes() != payload: + print( + "paybill_anchors.csv differs from a fresh extraction", file=sys.stderr + ) + return 1 + print("ok: extraction matches the committed CSV") + return 0 + args.out_dir.mkdir(parents=True, exist_ok=True) + target.write_bytes(payload) + print(f"wrote {target}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/extract_uk_firm_paybill_table.py b/tools/extract_uk_firm_paybill_table.py new file mode 100644 index 0000000000..35eaf9e2c9 --- /dev/null +++ b/tools/extract_uk_firm_paybill_table.py @@ -0,0 +1,364 @@ +#!/usr/bin/env python3 +"""Extract ONS ASHE section mean annual gross pay for the UK firm paybill. + +Reads the ONS *Earnings and hours worked, industry by two-digit SIC: ASHE +Table 4*, 2025 revised edition (``ashetable42025revised.zip``), member +``Table 4.7a Annual pay - Gross 2025``, sheet ``All`` (all employee jobs: +full-time and part-time, both sexes), and writes ``ashe_section_annual_pay.csv`` +with one row per SIC 2007 section A-U plus one ``ALL`` row (the sheet's +``ALL EMPLOYEES`` row): + +``sic_section,description,jobs_thousand,mean_annual_gross_pay_gbp,marker`` + +``mean_annual_gross_pay_gbp`` is the sheet's ``Mean`` column (pounds a year) +and ``jobs_thousand`` its indicative ``Number of jobs (thousand)``. A section +ONS does not publish (``x`` unreliable or disclosive, ``:`` not available) +keeps both numbers blank and the ONS marker in ``marker``; it is never +written as 0. The 2025 edition suppresses section U. + +ASHE annual estimates cover the tax year that ended on 5 April of the +reference year, so the 2025 edition is tax year 2024-25 (the firm build's +2024-25 vintage); the 2024 edition is 2023-24. + +openpyxl is imported only when a workbook is read, so engine-free CI, which +reads the committed CSV, never needs it. + +Usage:: + + uv run --no-sync python tools/extract_uk_firm_paybill_table.py \\ + --zip /ashetable42025revised.zip + + # Exit 1 if re-extraction would change the committed CSV's bytes. + uv run --no-sync python tools/extract_uk_firm_paybill_table.py \\ + --zip /ashetable42025revised.zip --check +""" + +from __future__ import annotations + +import argparse +import csv +import datetime as dt +import hashlib +import io +import json +import sys +import zipfile +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_paybill_2024" +) +PROVENANCE_NAME = ".provenance.json" +CSV_NAME = "ashe_section_annual_pay.csv" + +DATASET_URL = ( + "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/" + "earningsandworkinghours/datasets/industry2digitsicashetable4" +) +ZIP_URL = ( + "https://www.ons.gov.uk/file?uri=/employmentandlabourmarket/peopleinwork/" + "earningsandworkinghours/datasets/industry2digitsicashetable4/2025revised/" + "ashetable42025revised.zip" +) +DATASET_TITLE = "Earnings and hours worked, industry by two-digit SIC: ASHE Table 4" +EDITION = "2025 revised" +#: The committed fixture's recorded access date: the default for +#: ``--access-date``, which the person who downloads the zip sets. +ACCESS_DATE = "2026-11-22" + +MEMBER_MARKER = "Table 4.7a" +MEMBER_SUFFIX = "Annual pay - Gross 2025.xlsx" +SHEET = "All" +TITLE_PREFIX = "SIC2007 Table 4" +TITLE_MARKERS = ("Annual pay - Gross", "For all employee jobs", "United Kingdom 2025") +HEADER_ROW = 5 +ALL_LABEL = "ALL EMPLOYEES" +ALL_KEY = "ALL" +SECTIONS = tuple("ABCDEFGHIJKLMNOPQRSTU") +#: ONS markers for an unpublished cell. +UNPUBLISHED_MARKERS = ("x", ":") + +HEADER = ( + "sic_section", + "description", + "jobs_thousand", + "mean_annual_gross_pay_gbp", + "marker", +) + + +@dataclass +class Extracted: + title: str + rows: list[tuple[Any, ...]] = field(default_factory=list) + markers: dict[str, str] = field(default_factory=dict) + + def to_csv_bytes(self) -> bytes: + buffer = io.StringIO() + writer = csv.writer(buffer, lineterminator="\n") + writer.writerow(HEADER) + writer.writerows(self.rows) + return buffer.getvalue().encode("utf-8") + + +def _code(value: Any) -> str: + """A ``Code`` cell without the leading apostrophe and spaces ONS leaves.""" + + return "" if value is None else str(value).strip().lstrip("'").strip() + + +def _number(value: Any) -> str: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError(f"expected a number, got {value!r}") + if value < 0: + raise ValueError(f"expected a non-negative number, got {value!r}") + return repr(float(value)) + + +def _column(header: Sequence[Any], label: str) -> int: + matches = [ + index + for index, value in enumerate(header) + if value is not None and str(value).strip() == label + ] + if len(matches) != 1: + raise ValueError(f"header row {HEADER_ROW}: {label!r} found {len(matches)}x") + return matches[0] + + +def _row(row: Sequence[Any], key: str, columns: dict[str, int]) -> tuple: + description = " ".join(str(row[columns["Description"]]).split()) + jobs = row[columns["(thousand)"]] + mean = row[columns["Mean"]] + if isinstance(mean, str) and mean.strip() in UNPUBLISHED_MARKERS: + return (key, description, "", "", mean.strip()) + if mean is None: + raise ValueError(f"section {key}: blank mean") + return (key, description, _number(jobs), _number(mean), "") + + +def extract_rows(rows: list[tuple[Any, ...]]) -> Extracted: + title = " ".join(str(rows[0][0]).split()) + if not title.startswith(TITLE_PREFIX): + raise ValueError(f"unexpected title {title!r}") + for marker in TITLE_MARKERS: + if marker not in title: + raise ValueError(f"title {title!r} lacks {marker!r}") + header = rows[HEADER_ROW - 1] + columns = { + label: _column(header, label) for label in ("Description", "Code", "Mean") + } + # The jobs label is split over rows 3-5; its third line sits in row 5. + columns["(thousand)"] = _column(header, "(thousand)") + table = Extracted(title=title) + all_rows = [ + row + for row in rows[HEADER_ROW:] + if row[columns["Description"]] is not None + and str(row[columns["Description"]]).strip() == ALL_LABEL + ] + if len(all_rows) != 1: + raise ValueError(f"{ALL_LABEL!r} found {len(all_rows)}x") + by_section: dict[str, tuple[Any, ...]] = {} + order = [] + for row in rows[HEADER_ROW:]: + code = _code(row[columns["Code"]]) + if len(code) == 1 and code.isalpha(): + if code in by_section: + raise ValueError(f"section {code} appears twice") + by_section[code] = row + order.append(code) + if tuple(order) != SECTIONS: + raise ValueError(f"sections {order} != {list(SECTIONS)}") + for section in SECTIONS: + record = _row(by_section[section], section, columns) + table.rows.append(record) + if record[4]: + table.markers[section] = record[4] + record = _row(all_rows[0], ALL_KEY, columns) + if record[4]: + raise ValueError(f"{ALL_LABEL!r} mean is not published") + table.rows.append(record) + return table + + +def _member(archive: zipfile.ZipFile) -> str: + names = [ + name + for name in archive.namelist() + if MEMBER_MARKER in name and name.endswith(MEMBER_SUFFIX) + ] + if len(names) != 1: + raise ValueError(f"zip members matching {MEMBER_MARKER!r}: {names}") + return names[0] + + +def extract(zip_path: Path) -> tuple[Extracted, str, bytes]: + import openpyxl # noqa: PLC0415 - local-only dependency, kept out of CI imports + + with zipfile.ZipFile(zip_path) as archive: + member = _member(archive) + data = archive.read(member) + book = openpyxl.load_workbook(io.BytesIO(data), read_only=True, data_only=True) + try: + rows = list(book[SHEET].iter_rows(values_only=True)) + finally: + book.close() + return extract_rows(rows), member, data + + +def _iso_date(value: str) -> str: + try: + return dt.date.fromisoformat(value).isoformat() + except ValueError: + raise argparse.ArgumentTypeError( + f"access date {value!r} is not YYYY-MM-DD" + ) from None + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def provenance( + zip_path: Path, + member: str, + member_bytes: bytes, + table: Extracted, + payload: bytes, + access_date: str = ACCESS_DATE, +) -> dict[str, Any]: + archive = zip_path.read_bytes() + return { + "source": { + "publisher": "Office for National Statistics", + "dataset_title": DATASET_TITLE, + "dataset_id": "ASHE: Table 4", + "dataset_url": DATASET_URL, + "edition": EDITION, + "download_url": ZIP_URL, + "zip_file": zip_path.name, + "zip_sha256": _sha256(archive), + "zip_bytes": len(archive), + "member": member, + "member_sha256": _sha256(member_bytes), + "member_bytes": len(member_bytes), + "sheet": SHEET, + "sheet_title": table.title, + "column": "Mean (Annual pay - Gross, GBP)", + "jobs_column": "Number of jobs (thousand), indicative only", + "release_date_note": ( + "The dataset landing page read 'Release date: 22 October 2026' " + "on the access date; that is the page's latest release (the " + "2026 provisional edition), not necessarily this edition's. " + "The zip's members are dated 13 October 2026." + ), + "licence": "Open Government Licence v3.0", + "access_date": access_date, + }, + "reference_period": ( + "Workbook Notes: annual estimates are for the tax year that ended on " + "5 April in the reference year, so the 2025 edition is tax year " + "2024-25. The directory is named for the build's rule period, 2024 " + "(tax year 2024-25), not for the ASHE edition." + ), + "coverage": ( + "Workbook footnote a: employees on adult rates who have been in the " + "same job for more than a year. All employee jobs, full-time and " + "part-time; a person with two jobs counts twice." + ), + "extraction_date": dt.date.today().isoformat(), + "tool": "tools/extract_uk_firm_paybill_table.py", + "command": ( + "uv run --no-sync python tools/extract_uk_firm_paybill_table.py " + "--zip /ashetable42025revised.zip" + ), + "unpublished": { + "markers": dict(table.markers), + "rule": ( + "A section whose mean is 'x' or ':' keeps blank numbers and the " + "marker; it is never written as 0." + ), + }, + "all_row": ( + f"sic_section {ALL_KEY!r} is the sheet's {ALL_LABEL!r} row, the " + "fallback for sections without a published mean." + ), + "files": { + CSV_NAME: { + "sha256": _sha256(payload), + "bytes": len(payload), + "rows": len(table.rows), + "columns": list(HEADER), + } + }, + } + + +def _write( + out: Path, + zip_path: Path, + member: str, + data: bytes, + table: Extracted, + access_date: str = ACCESS_DATE, +): + out.mkdir(parents=True, exist_ok=True) + payload = table.to_csv_bytes() + (out / CSV_NAME).write_bytes(payload) + record = provenance(zip_path, member, data, table, payload, access_date) + (out / PROVENANCE_NAME).write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8" + ) + print(f"wrote {out / CSV_NAME} ({len(table.rows)} rows)") + print(f"wrote {out / PROVENANCE_NAME}") + + +def _check(out: Path, table: Extracted) -> int: + path = out / CSV_NAME + if not path.is_file() or path.read_bytes() != table.to_csv_bytes(): + print(f"stale or missing: {CSV_NAME}", file=sys.stderr) + return 1 + print(f"{CSV_NAME} matches the workbook") + return 0 + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--zip", 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 CSV; write nothing", + ) + parser.add_argument( + "--access-date", + type=_iso_date, + default=ACCESS_DATE, + help=( + "date (YYYY-MM-DD) the zip was downloaded, written to the " + f"provenance (default {ACCESS_DATE}, the committed fixture's)" + ), + ) + args = parser.parse_args(argv) + zip_path = args.zip.resolve() + table, member, data = extract(zip_path) + if args.check: + return _check(args.out, table) + _write(args.out, zip_path, member, data, table, args.access_date) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/extract_uk_firm_public_sector_table.py b/tools/extract_uk_firm_public_sector_table.py new file mode 100644 index 0000000000..8cf0d74c60 --- /dev/null +++ b/tools/extract_uk_firm_public_sector_table.py @@ -0,0 +1,309 @@ +#!/usr/bin/env python3 +"""Extract ONS public sector headcounts for the UK firm public sector rescale. + +Reads the ONS *Public sector employment* reference table workbook, March 2025 +edition (``datasets8.xlsx``, "Public sector employment, UK: March 2025"), +sheet ``Table 1`` (*Public sector employment by sector classification; +Headcount*, United Kingdom, thousands, seasonally adjusted), row ``Mar 2025``, +and writes ``ons_public_sector_employment.csv`` with one row for central +government (series G6NQ) and one for local government (series G6NT): + +``sector,ons_legal_status,series_id,period,headcount_thousand`` + +``ons_legal_status`` is the ONS business-count legal status the firm build +spreads each headcount over (5 central government, 6 local authority). + +openpyxl is imported only when a workbook is read, so engine-free CI, which +reads the committed CSV, never needs it. + +Usage:: + + uv run --no-sync python tools/extract_uk_firm_public_sector_table.py \\ + --xlsx /datasets8.xlsx + + # Also record what a later edition gives for the same quarter. + uv run --no-sync python tools/extract_uk_firm_public_sector_table.py \\ + --xlsx /datasets8.xlsx --later-xlsx /datasets3.xlsx + + # Exit 1 if re-extraction would change the committed CSV's bytes. + uv run --no-sync python tools/extract_uk_firm_public_sector_table.py \\ + --xlsx /datasets8.xlsx --check +""" + +from __future__ import annotations + +import argparse +import csv +import datetime as dt +import hashlib +import io +import json +import sys +from collections.abc import Sequence +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_public_sector_2025" +) +CSV_NAME = "ons_public_sector_employment.csv" +PROVENANCE_NAME = CSV_NAME + ".provenance.json" + +LANDING_PAGE = ( + "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/" + "publicsectorpersonnel/datasets/publicsectoremploymentreferencetable" +) +_FILE_BASE = ( + "https://www.ons.gov.uk/file?uri=/employmentandlabourmarket/peopleinwork/" + "publicsectorpersonnel/datasets/publicsectoremploymentreferencetable/" +) +XLSX_URL = _FILE_BASE + "march2025/datasets8.xlsx" +LATER_XLSX_URL = _FILE_BASE + "june2026/datasets3.xlsx" +#: The committed fixture's recorded access date: the default for +#: ``--access-date``, which the person who downloads the workbook sets. +ACCESS_DATE = "2026-11-22" + +INDEX_SHEET = "Index" +EDITION_TITLE = "Public sector employment, UK: March 2025" +SHEET = "Table 1" +TITLE_PREFIX = "Table 1: Public sector employment by sector classification; Headcount" +UNITS = "United Kingdom (thousands), seasonally adjusted" +PERIOD = "Mar 2025" +#: sector, ONS legal status, series identifier, header words. +SECTORS = ( + ("central_government", 5, "G6NQ", ("Central", "government")), + ("local_government", 6, "G6NT", ("Local", "government")), +) +HEADER = ("sector", "ons_legal_status", "series_id", "period", "headcount_thousand") + + +def _text(value: Any) -> str: + return "" if value is None else " ".join(str(value).split()) + + +def _period(value: Any) -> str: + """A period label without a revision marker such as ``[r]``.""" + + return _text(value).split("[")[0].strip() + + +def extract_rows(rows: list[tuple[Any, ...]]) -> list[tuple[Any, ...]]: + """The CSV rows from sheet ``Table 1``'s cell rows.""" + + if not _text(rows[0][0]).startswith(TITLE_PREFIX): + raise ValueError(f"unexpected title {_text(rows[0][0])!r}") + if not any(_text(cell) == UNITS for row in rows[:8] for cell in row): + raise ValueError(f"sheet lacks the units line {UNITS!r}") + series_rows = [ + row for row in rows[:12] if SECTORS[0][2] in [_text(cell) for cell in row] + ] + if len(series_rows) != 1: + raise ValueError(f"series row with {SECTORS[0][2]} found {len(series_rows)}x") + series = [_text(cell) for cell in series_rows[0]] + labels = rows[rows.index(series_rows[0]) - 2] + period_rows = [row for row in rows if _period(row[0]) == PERIOD] + if len(period_rows) != 1: + raise ValueError(f"period {PERIOD!r} found {len(period_rows)}x") + out = [] + for sector, status, series_id, words in SECTORS: + if series.count(series_id) != 1: + raise ValueError(f"series {series_id} found {series.count(series_id)}x") + column = series.index(series_id) + label = _text(labels[column]) + if not all(word in label for word in words) or "Total" in label: + raise ValueError(f"series {series_id} sits under {label!r}") + value = period_rows[0][column] + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError(f"{sector}: expected a number, got {value!r}") + if value <= 0 or value != int(value): + raise ValueError(f"{sector}: expected whole thousands, got {value!r}") + out.append((sector, status, series_id, PERIOD, int(value))) + return out + + +def to_csv_bytes(rows: list[tuple[Any, ...]]) -> bytes: + buffer = io.StringIO() + writer = csv.writer(buffer, lineterminator="\n") + writer.writerow(HEADER) + writer.writerows(rows) + return buffer.getvalue().encode("utf-8") + + +def _read(xlsx: Path) -> tuple[list[tuple[Any, ...]], list[str]]: + import openpyxl # noqa: PLC0415 - local-only dependency, kept out of CI imports + + book = openpyxl.load_workbook(xlsx, read_only=True, data_only=True) + try: + rows = list(book[SHEET].iter_rows(values_only=True)) + index = [ + _text(row[0]) + for row in book[INDEX_SHEET].iter_rows(max_row=2, values_only=True) + ] + finally: + book.close() + return rows, index + + +def extract(xlsx: Path) -> tuple[list[tuple[Any, ...]], list[str]]: + rows, index = _read(xlsx) + if index[0] != EDITION_TITLE: + raise ValueError(f"workbook is {index[0]!r}, not {EDITION_TITLE!r}") + return extract_rows(rows), index + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _iso_date(value: str) -> str: + try: + return dt.date.fromisoformat(value).isoformat() + except ValueError: + raise argparse.ArgumentTypeError( + f"access date {value!r} is not YYYY-MM-DD" + ) from None + + +def provenance( + xlsx: Path, + rows: list[tuple[Any, ...]], + index: list[str], + payload: bytes, + access_date: str = ACCESS_DATE, + later_xlsx: Path | None = None, +) -> dict[str, Any]: + workbook = xlsx.read_bytes() + record: dict[str, Any] = { + "kind": "uk_firm_public_sector_employment_fixture", + "schema_version": 1, + "period": "March 2025 quarter (the last quarter of tax year 2024-25)", + "accessed": access_date, + "method": ( + "Figures were read from the downloaded workbook on the access date " + "by tools/extract_uk_firm_public_sector_table.py; none was filled " + "from memory. headcount_thousand is the Table 1 cell as published " + "(thousands of people, seasonally adjusted). ons_legal_status is " + "the firm build's mapping of each sector to an ONS business-count " + "legal status (5 central government, 6 local authority), an " + "assumption beyond the source." + ), + "source": { + "publisher": "Office for National Statistics", + "dataset_title": "Public sector employment", + "landing_page": LANDING_PAGE, + "url": XLSX_URL, + "edition": f"March 2025 edition: {index[0]}; {index[1]}", + "file": xlsx.name, + "size_bytes": len(workbook), + "sha256": _sha256(workbook), + "sheet": SHEET, + "table": ( + "Table 1: Public sector employment by sector classification; " + "Headcount; United Kingdom (thousands), seasonally adjusted; " + f"row '{PERIOD}'" + ), + "series": {sector: series_id for sector, _, series_id, _ in SECTORS}, + "survey": "Quarterly Public Sector Employment Survey", + "licence": "Open Government Licence v3.0", + }, + "edition_note": ( + "The March 2025 edition is not the dataset's latest: the landing " + "page listed a June 2026 edition (release date 15 September 2026) " + "on the access date. The March 2025 edition is used so the " + "headcount is the first published estimate for the quarter that " + "closes the 2024-25 frame; later editions revise it." + ), + "coverage": ( + "Headcount, full-time and part-time. Table 1 does not list the " + "bodies in each sector; the workbook's Table 2 splits the public " + "sector total by industry (HM Forces, police, public " + "administration, education, National Health Service, other), and " + "its Reclassification notes place English further education " + "colleges and Network Rail in central government. Police " + "(England and Wales) are based on projections (footnote 4). " + "Public corporations (series G7AR) are not extracted." + ), + "extraction_date": dt.date.today().isoformat(), + "tool": "tools/extract_uk_firm_public_sector_table.py", + "command": ( + "uv run --no-sync python tools/extract_uk_firm_public_sector_table.py " + "--xlsx /datasets8.xlsx --later-xlsx /datasets3.xlsx" + ), + "files": { + CSV_NAME: { + "sha256": _sha256(payload), + "bytes": len(payload), + "rows": len(rows), + "columns": list(HEADER), + } + }, + } + if later_xlsx is not None: + later_rows, later_index = _read(later_xlsx) + later = later_xlsx.read_bytes() + record["later_edition"] = { + "note": ( + "The same row and series in a later edition, recorded for " + "comparison only; the CSV does not use it." + ), + "url": LATER_XLSX_URL, + "edition": f"{later_index[0]}; {later_index[1]}", + "file": later_xlsx.name, + "size_bytes": len(later), + "sha256": _sha256(later), + "headcount_thousand": {row[0]: row[4] for row in extract_rows(later_rows)}, + } + return record + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--xlsx", type=Path, required=True) + parser.add_argument("--later-xlsx", type=Path, default=None) + 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 CSV; write nothing", + ) + parser.add_argument( + "--access-date", + type=_iso_date, + default=ACCESS_DATE, + help=( + "date (YYYY-MM-DD) the workbook was downloaded, written to the " + f"provenance (default {ACCESS_DATE}, the committed fixture's)" + ), + ) + args = parser.parse_args(argv) + xlsx = args.xlsx.resolve() + rows, index = extract(xlsx) + payload = to_csv_bytes(rows) + if args.check: + path = args.out / CSV_NAME + if not path.is_file() or path.read_bytes() != payload: + print(f"stale or missing: {CSV_NAME}", file=sys.stderr) + return 1 + print(f"{CSV_NAME} matches the workbook") + return 0 + args.out.mkdir(parents=True, exist_ok=True) + (args.out / CSV_NAME).write_bytes(payload) + later = args.later_xlsx.resolve() if args.later_xlsx else None + record = provenance(xlsx, rows, index, payload, args.access_date, later) + (args.out / PROVENANCE_NAME).write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8" + ) + print(f"wrote {args.out / CSV_NAME} ({len(rows)} rows)") + print(f"wrote {args.out / PROVENANCE_NAME}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/extract_uk_firm_rateable_value_tables.py b/tools/extract_uk_firm_rateable_value_tables.py new file mode 100644 index 0000000000..6cb3aba9c6 --- /dev/null +++ b/tools/extract_uk_firm_rateable_value_tables.py @@ -0,0 +1,468 @@ +#!/usr/bin/env python3 +"""Extract VOA rateable-value stock tables for the UK firm rateable value. + +Reads the Valuation Office Agency's *Non-domestic rating: stock of +properties, March 2026* CSV bundle (``ndr_stock_of_properties_2026.zip``): +the stock of rateable properties (hereditaments) on the **2023 rating lists** +as at 31 March 2026, England and Wales. Writes three CSVs: + +``voa_rv_band_sector.csv`` (Tables SOP2.1, SOP2.2, SOP2.3) + ``geography,rv_band,band_lower_gbp,band_upper_gbp,sector,hereditaments, + total_rv_gbp_thousand``: hereditaments and total rateable value by + rateable-value band and RIO sector (``all``, ``retail``, ``offices``, + ``industry``, ``other``) for ``england_and_wales``, ``england`` and + ``wales``, with the tables' own ``Total`` rows (blank band bounds). The + open top band has a blank upper bound. + +``voa_property_type.csv`` (Table SOP1.2) + ``geography,prop_type_code,parent_code,level,description,hereditaments, + total_rv_gbp_thousand,mean_rv_gbp_thousand,median_rv_gbp_thousand,marker``: + the same by property type, at levels ``all``, ``sector``, ``sub_sector`` + and ``shop_type``. A cell the VOA suppresses (``[c]``) keeps blank numbers + and the marker; it is never written as 0. + +``voa_stock_by_year.csv`` (Tables SOP3.1 and SOP3.2) + ``geography,as_at,hereditaments,total_rv_gbp_thousand``: all-property + stock at 31 March of each year the 2023 rating lists were in force (2024, + 2025, 2026), for the same three geographies. + +Rateable values are in GBP thousand, as the bundle's variable-names metadata +says (``Total rateable value (GBP thousands)``); the tool copies the source +digits and does no arithmetic on them. + +Usage:: + + uv run --no-sync python tools/extract_uk_firm_rateable_value_tables.py \\ + --zip /ndr_stock_of_properties_2026.zip + + # Exit 1 if re-extraction would change a committed CSV's bytes. + uv run --no-sync python tools/extract_uk_firm_rateable_value_tables.py \\ + --zip /ndr_stock_of_properties_2026.zip --check +""" + +from __future__ import annotations + +import argparse +import csv +import datetime as dt +import hashlib +import io +import json +import re +import sys +import zipfile +from collections.abc import Sequence +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_rateable_value_2024" +) +PROVENANCE_NAME = ".provenance.json" + +LANDING_PAGE = ( + "https://www.gov.uk/government/statistics/" + "non-domestic-rating-stock-of-properties-march-2026" +) +COLLECTION_PAGE = ( + "https://www.gov.uk/government/collections/" + "non-domestic-rating-stock-of-properties-collection" +) +ZIP_URL = ( + "https://assets.publishing.service.gov.uk/media/69f9bdf9a96f4d06cda76fbf/" + "ndr_stock_of_properties_2026.zip" +) +EDITION = ( + "Non-domestic rating: stock of properties, March 2026 (published 14 May " + "2026): stock on the 2023 central and local rating lists as at 31 March 2026" +) +RATING_LIST = "2023 rating list (England and Wales), as at 31 March 2026" +#: The committed fixture's recorded access date. +ACCESS_DATE = "2026-11-22" + +BAND_FILE = "voa_rv_band_sector.csv" +PROPERTY_TYPE_FILE = "voa_property_type.csv" +YEAR_FILE = "voa_stock_by_year.csv" + +BAND_HEADER = ( + "geography", + "rv_band", + "band_lower_gbp", + "band_upper_gbp", + "sector", + "hereditaments", + "total_rv_gbp_thousand", +) +PROPERTY_TYPE_HEADER = ( + "geography", + "prop_type_code", + "parent_code", + "level", + "description", + "hereditaments", + "total_rv_gbp_thousand", + "mean_rv_gbp_thousand", + "median_rv_gbp_thousand", + "marker", +) +YEAR_HEADER = ("geography", "as_at", "hereditaments", "total_rv_gbp_thousand") + +#: Band-table member per geography. +BAND_MEMBERS = { + "england_and_wales": "table_SOP2_1.csv", + "england": "table_SOP2_2.csv", + "wales": "table_SOP2_3.csv", +} +SECTORS = ("all", "retail", "offices", "industry", "other") +TOTAL_BAND = "Total" +PROPERTY_TYPE_MEMBER = "table_SOP1_2.csv" +#: Geography suffix in Table SOP1.2's column names. +PROPERTY_TYPE_SUFFIXES = { + "england_and_wales": "engwal", + "england": "eng", + "wales": "wal", +} +ALL_CODE_SOURCE = "[z]" +ALL_CODE = "ALL" +SUPPRESSED = "[c]" +COUNT_MEMBER = "table_SOP3_1.csv" +RV_MEMBER = "table_SOP3_2.csv" +#: Area code per geography in Tables SOP3.1 and SOP3.2. +AREA_CODES = { + "england_and_wales": "K04000001", + "england": "E92000001", + "wales": "W92000004", +} +#: 31 March years with the 2023 rating lists in force (from 1 April 2023). +YEARS = ("2024", "2025", "2026") + +_WHOLE = re.compile(r"^\d+$") +_DECIMAL = re.compile(r"^\d+(\.\d+)?$") +_BAND_RANGE = re.compile(r"^([\d,]+) - ([\d,]+)$") +_BAND_OPEN = re.compile(r"^([\d,]+) and over$") + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _rows(payload: bytes) -> list[dict[str, str]]: + text = payload.decode("utf-8-sig") + return list(csv.DictReader(io.StringIO(text))) + + +def _whole(value: str, where: str) -> str: + value = value.strip() + if not _WHOLE.match(value): + raise ValueError(f"{where}: {value!r} is not a whole number") + return value + + +def _decimal(value: str, where: str) -> str: + value = value.strip() + if not _DECIMAL.match(value): + raise ValueError(f"{where}: {value!r} is not a number") + return value + + +def _band_bounds(band: str) -> tuple[str, str]: + if band == TOTAL_BAND: + return "", "" + closed = _BAND_RANGE.match(band) + if closed: + return closed.group(1).replace(",", ""), closed.group(2).replace(",", "") + opened = _BAND_OPEN.match(band) + if opened: + return opened.group(1).replace(",", ""), "" + raise ValueError(f"unrecognised rateable-value band {band!r}") + + +def band_rows(members: dict[str, bytes]) -> list[tuple[str, ...]]: + out: list[tuple[str, ...]] = [] + for geography, member in BAND_MEMBERS.items(): + rows = _rows(members[member]) + if not rows or rows[-1]["rv_band"] != TOTAL_BAND: + raise ValueError(f"{member}: last row is not {TOTAL_BAND!r}") + for row in rows: + band = row["rv_band"].strip() + lower, upper = _band_bounds(band) + for sector in SECTORS: + where = f"{member} {band} {sector}" + out.append( + ( + geography, + band, + lower, + upper, + sector, + _whole(row[f"count_{sector}"], where), + _whole(row[f"total_rv_{sector}"], where), + ) + ) + return out + + +def property_type_rows(members: dict[str, bytes]) -> list[tuple[str, ...]]: + rows = _rows(members[PROPERTY_TYPE_MEMBER]) + out: list[tuple[str, ...]] = [] + for geography, suffix in PROPERTY_TYPE_SUFFIXES.items(): + sector = "" + for row in rows: + code = row["prop_type_code"].strip() + if code == ALL_CODE_SOURCE: + code, parent, level = ALL_CODE, "", "all" + elif len(code) == 1: + sector, parent, level = code, ALL_CODE, "sector" + elif len(code) == 2: + parent, level = sector, "sub_sector" + elif len(code) == 3: + parent, level = code[:2], "shop_type" + else: + raise ValueError(f"unrecognised property type code {code!r}") + where = f"{PROPERTY_TYPE_MEMBER} {code} {geography}" + cells = [ + row[f"{name}_{suffix}"].strip() + for name in ("count", "total_rv", "mean_rv", "median_rv") + ] + if SUPPRESSED in cells: + if set(cells) != {SUPPRESSED}: + raise ValueError(f"{where}: partly suppressed row") + numbers, marker = ["", "", "", ""], SUPPRESSED + else: + numbers = [ + _whole(cells[0], where), + _whole(cells[1], where), + _decimal(cells[2], where), + _decimal(cells[3], where), + ] + marker = "" + out.append( + ( + geography, + code, + parent, + level, + row["description"].strip(), + *numbers, + marker, + ) + ) + return out + + +def year_rows(members: dict[str, bytes]) -> list[tuple[str, ...]]: + counts = {row["area_code"]: row for row in _rows(members[COUNT_MEMBER])} + values = {row["area_code"]: row for row in _rows(members[RV_MEMBER])} + out: list[tuple[str, ...]] = [] + for geography, code in AREA_CODES.items(): + for year in YEARS: + where = f"{geography} {year}" + out.append( + ( + geography, + f"{year}-03-31", + _whole(counts[code][year], f"{COUNT_MEMBER} {where}"), + _whole(values[code][year], f"{RV_MEMBER} {where}"), + ) + ) + return out + + +def _csv_bytes(header: Sequence[str], rows: Sequence[Sequence[str]]) -> bytes: + buffer = io.StringIO() + writer = csv.writer(buffer, lineterminator="\n") + writer.writerow(header) + writer.writerows(rows) + return buffer.getvalue().encode("utf-8") + + +def _source_members() -> tuple[str, ...]: + return ( + *BAND_MEMBERS.values(), + PROPERTY_TYPE_MEMBER, + COUNT_MEMBER, + RV_MEMBER, + ) + + +def extract(zip_path: Path) -> tuple[dict[str, bytes], dict[str, bytes]]: + """The fixture CSVs' bytes by file name, and the members read.""" + + with zipfile.ZipFile(zip_path) as archive: + members = {name: archive.read(name) for name in _source_members()} + tables = { + BAND_FILE: _csv_bytes(BAND_HEADER, band_rows(members)), + PROPERTY_TYPE_FILE: _csv_bytes( + PROPERTY_TYPE_HEADER, property_type_rows(members) + ), + YEAR_FILE: _csv_bytes(YEAR_HEADER, year_rows(members)), + } + return tables, members + + +def _iso_date(value: str) -> str: + try: + return dt.date.fromisoformat(value).isoformat() + except ValueError: + raise argparse.ArgumentTypeError( + f"access date {value!r} is not YYYY-MM-DD" + ) from None + + +def provenance( + zip_path: Path, + tables: dict[str, bytes], + members: dict[str, bytes], + access_date: str = ACCESS_DATE, +) -> dict[str, Any]: + archive = zip_path.read_bytes() + headers = { + BAND_FILE: BAND_HEADER, + PROPERTY_TYPE_FILE: PROPERTY_TYPE_HEADER, + YEAR_FILE: YEAR_HEADER, + } + member_tables = { + BAND_FILE: list(BAND_MEMBERS.values()), + PROPERTY_TYPE_FILE: [PROPERTY_TYPE_MEMBER], + YEAR_FILE: [COUNT_MEMBER, RV_MEMBER], + } + return { + "kind": "uk_firm_rateable_value_fixture", + "schema_version": 1, + "accessed": access_date, + "rating_list": RATING_LIST, + "method": ( + "Every figure was copied digit for digit from the downloaded VOA " + "CSV bundle by the tool on the access date; none was filled from " + "memory and none is computed. Rateable values stay in the " + "source's unit, GBP thousand (the bundle's metadata file " + "ndr_sop_variable_names.csv: 'Total rateable value (GBP " + "thousands)'). Band bounds are parsed from the band labels." + ), + "source": { + "publisher": "Valuation Office Agency", + "title": "Non-domestic rating: stock of properties, March 2026", + "landing_page": LANDING_PAGE, + "collection_page": COLLECTION_PAGE, + "url": ZIP_URL, + "edition": EDITION, + "edition_note": ( + "The collection page listed this as the latest edition on the " + "access date (landing page public-updated-at " + "2026-05-14T09:30:00+01:00)." + ), + "zip_file": zip_path.name, + "sha256": _sha256(archive), + "zip_bytes": len(archive), + "members": { + name: {"sha256": _sha256(data), "bytes": len(data)} + for name, data in sorted(members.items()) + }, + "licence": "Open Government Licence v3.0", + }, + "coverage": ( + "Hereditaments (rateable properties), not firms, in England and " + "Wales. Scotland and Northern Ireland have their own valuation " + "rolls and are not in the release. Table SOP1.1 of the same " + "bundle lists central rating list rateable value separately; it " + "is not extracted." + ), + "reference_period": ( + "Stock at 31 March 2026 on the 2023 rating lists (in force 1 " + "April 2023 to 31 March 2026). The directory is named for the " + "firm build's rule period, 2024 (tax year 2024-25), not for the " + "VOA edition; voa_stock_by_year.csv carries the all-property " + "stock at 31 March 2024, 2025 and 2026 from the same bundle." + ), + "suppression": ( + "A Table SOP1.2 row the VOA marks '[c]' keeps blank numbers and " + "the marker; it is never written as 0." + ), + "extraction_date": dt.date.today().isoformat(), + "tool": "tools/extract_uk_firm_rateable_value_tables.py", + "command": ( + "uv run --no-sync python " + "tools/extract_uk_firm_rateable_value_tables.py " + "--zip /ndr_stock_of_properties_2026.zip" + ), + "files": { + name: { + "sha256": _sha256(payload), + "bytes": len(payload), + "rows": payload.count(b"\n") - 1, + "columns": list(headers[name]), + "source_members": member_tables[name], + } + for name, payload in tables.items() + }, + } + + +def _write( + out: Path, + zip_path: Path, + tables: dict[str, bytes], + members: dict[str, bytes], + access_date: str, +) -> None: + out.mkdir(parents=True, exist_ok=True) + for name, payload in tables.items(): + (out / name).write_bytes(payload) + print(f"wrote {out / name}") + record = provenance(zip_path, tables, members, access_date) + (out / PROVENANCE_NAME).write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8" + ) + print(f"wrote {out / PROVENANCE_NAME}") + + +def _check(out: Path, tables: dict[str, bytes]) -> int: + stale = [ + name + for name, payload in tables.items() + if not (out / name).is_file() or (out / name).read_bytes() != payload + ] + for name in stale: + print(f"stale or missing: {name}", file=sys.stderr) + if stale: + return 1 + print(f"{', '.join(tables)} match the VOA bundle") + return 0 + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--zip", 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", + ) + parser.add_argument( + "--access-date", + type=_iso_date, + default=ACCESS_DATE, + help=( + "date (YYYY-MM-DD) the zip was downloaded, written to the " + f"provenance (default {ACCESS_DATE}, the committed fixture's)" + ), + ) + args = parser.parse_args(argv) + zip_path = args.zip.resolve() + tables, members = extract(zip_path) + if args.check: + return _check(args.out, tables) + _write(args.out, zip_path, tables, members, args.access_date) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/extract_uk_firm_rd_tax_credits_tables.py b/tools/extract_uk_firm_rd_tax_credits_tables.py new file mode 100644 index 0000000000..984f21e049 --- /dev/null +++ b/tools/extract_uk_firm_rd_tax_credits_tables.py @@ -0,0 +1,393 @@ +#!/usr/bin/env python3 +"""Extract HMRC R&D tax credit tables for the UK firm R&D assignment. + +Reads the HMRC *Research and Development Tax Credits Statistics: September +2026* main tables (``rd_tax_credits_main_tables_2026.ods``) and writes three +CSVs with the published cells kept as published text (thousands separators, +HMRC's suppression marker, ``N/A`` and blanks included), so the fixture holds +raw published values and nothing else: + +- ``hmrc_rd_rd1_claims.csv``: sheet ``RD1``, number of claims by scheme and + financial year, 2016-17 to 2024-25; +- ``hmrc_rd_rd4_expenditure.csv``: sheet ``RD4``, R&D expenditure used to + claim (£ million) by scheme and financial year; +- ``hmrc_rd_rd6_sector_2024_25.csv``: sheet ``RD6_2425``, number and cost of + claims by SIC 2007 section and scheme, with total claims, total cost and + total expenditure (£ million), 2024-25. + +The ODS reader (``microcosm.build.uk_runtime.ods_tables``) is imported only +when a workbook is read, so engine-free CI, which reads the committed CSVs, +never opens one. + +Usage:: + + uv run --no-sync python tools/extract_uk_firm_rd_tax_credits_tables.py \\ + --ods /rd_tax_credits_main_tables_2026.ods + + # Exit 1 if re-extraction would change a committed CSV's bytes. + uv run --no-sync python tools/extract_uk_firm_rd_tax_credits_tables.py \\ + --ods /rd_tax_credits_main_tables_2026.ods --check +""" + +from __future__ import annotations + +import argparse +import csv +import datetime as dt +import hashlib +import io +import json +import sys +from collections.abc import Sequence +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_rd_tax_credits_2024_25" +) +PROVENANCE_NAME = "provenance.json" + +LANDING_PAGE = ( + "https://www.gov.uk/government/statistics/" + "corporate-tax-research-and-development-tax-credit" +) +ODS_URL = ( + "https://assets.publishing.service.gov.uk/media/6ab52b118cb3c0580e501188/" + "rd_tax_credits_main_tables_2026.ods" +) +#: The committed fixture's recorded access date: the default for +#: ``--access-date``, which the person who downloads the workbook sets. +ACCESS_DATE = "2026-11-23" +COVER_TITLE = ( + "HM Revenue and Customs: Research and Development Tax Credits Statistics 2026" +) + +#: (sheet, CSV name, title prefix, header cells as published, CSV columns). +RD1 = ( + "RD1", + "hmrc_rd_rd1_claims.csv", + "RD1: Number of claims for the R&D tax credit for all schemes by financial year", + ( + "Financial Year", + "Status", + "SME Deductions", + "SME Payable Credits", + "SME Combination", + "SME Scheme Intensives & ERIS", + "SME Total", + "RDEC by LCs", + "RDEC claims by SMEs", + "Merged RDEC by LCs", + "Merged RDEC by SMEs", + "RDEC & Merged RDEC Total", + "Total Claims", + "Total Returns", + "Total Companies", + ), + ( + "financial_year", + "status", + "sme_deductions", + "sme_payable_credits", + "sme_combination", + "sme_intensive_eris", + "sme_total", + "rdec_large", + "rdec_sme", + "merged_rdec_large", + "merged_rdec_sme", + "rdec_merged_total", + "total_claims", + "total_returns", + "total_companies", + ), +) +RD4 = ( + "RD4", + "hmrc_rd_rd4_expenditure.csv", + "RD4: R&D expenditure used to claim R&D tax credits by scheme and financial year", + ( + "Financial Year", + "Status", + "SME Scheme", + "SME Scheme Intensives & ERIS", + "RDEC by LCs", + "RDEC claims by SMEs", + "Merged RDEC by LCs", + "Merged RDEC by SMEs", + "All R&D schemes", + ), + ( + "financial_year", + "status", + "sme_scheme", + "sme_intensive_eris", + "rdec_large", + "rdec_sme", + "merged_rdec_large", + "merged_rdec_sme", + "all_schemes", + ), +) +RD6 = ( + "RD6_2425", + "hmrc_rd_rd6_sector_2024_25.csv", + "RD6: Industry sector analysis of number and cost of R&D tax credit claims, " + "2024-25", + ( + "Sector", + "Number of SME Scheme claims", + "Cost of SME Scheme claims", + "Number of SME Scheme Intensive & ERIS claims", + "Cost of SME Scheme Intensive & ERIS claims", + "Number of RDEC claims by LCs", + "Cost of RDEC claims by LCs", + "Number of RDEC claims by SMEs", + "Cost of RDEC claims by SMEs", + "Number of Merged RDEC claims by LCs", + "Cost of Merged RDEC claims by LCs", + "Number of Merged RDEC claims by SMEs", + "Cost of Merged RDEC claims by SMEs", + "Total Claims", + "Total Cost", + "Total Expenditure", + ), + ( + "sector", + "sme_scheme_claims", + "sme_scheme_cost_gbp_m", + "sme_intensive_eris_claims", + "sme_intensive_eris_cost_gbp_m", + "rdec_large_claims", + "rdec_large_cost_gbp_m", + "rdec_sme_claims", + "rdec_sme_cost_gbp_m", + "merged_rdec_large_claims", + "merged_rdec_large_cost_gbp_m", + "merged_rdec_sme_claims", + "merged_rdec_sme_cost_gbp_m", + "total_claims", + "total_cost_gbp_m", + "total_expenditure_gbp_m", + ), +) +TABLES = (RD1, RD4, RD6) +#: RD6 row labels start with the SIC 2007 section letter, then ". ". +RD6_SECTIONS = tuple("ABCDEFGHIJKLMNOPQRS") +RD6_UNKNOWN = "Unknown or other" +FIRST_YEAR, LAST_YEAR = "2016-17", "2024-25" + + +def _text(value: Any) -> str: + if value is None: + return "" + if isinstance(value, float) and value == int(value): + return str(int(value)) + return " ".join(str(value).split()) + + +def extract_table(rows: Sequence[Sequence[Any]], spec: tuple) -> list[list[str]]: + """One sheet's data rows as published text, checked against ``spec``.""" + + sheet, _, title, header, columns = spec + if not rows or not _text(rows[0][0] if rows[0] else "").startswith(title): + raise ValueError(f"{sheet}: title is not {title!r}") + found = [ + index + for index, row in enumerate(rows) + if tuple(_text(cell) for cell in row[: len(header)]) == header + ] + if len(found) != 1: + raise ValueError(f"{sheet}: header row found {len(found)}x") + out: list[list[str]] = [] + for row in rows[found[0] + 1 :]: + first = _text(row[0]) if row else "" + if first == "End of worksheet": + break + if not first: + raise ValueError(f"{sheet}: blank row label before 'End of worksheet'") + cells = [_text(row[i]) if i < len(row) else "" for i in range(len(header))] + out.append(cells) + else: + raise ValueError(f"{sheet}: no 'End of worksheet' row") + if sheet == "RD6_2425": + labels = [cells[0] for cells in out] + expected = [label[0] for label in labels[:-1]] + if expected != list(RD6_SECTIONS) or labels[-1] != RD6_UNKNOWN: + raise ValueError(f"{sheet}: unexpected sector rows {labels}") + if not all(label[1:3] == ". " for label in labels[:-1]): + raise ValueError(f"{sheet}: sector labels are not 'X. name'") + else: + years = [cells[0] for cells in out] + if years[0] != FIRST_YEAR or years[-1] != LAST_YEAR: + raise ValueError(f"{sheet}: years run {years[0]} to {years[-1]}") + del columns + return out + + +def to_csv_bytes(columns: Sequence[str], rows: list[list[str]]) -> bytes: + buffer = io.StringIO() + writer = csv.writer(buffer, lineterminator="\n") + writer.writerow(columns) + writer.writerows(rows) + return buffer.getvalue().encode("utf-8") + + +def extract(ods: Path) -> dict[str, bytes]: + """The three CSVs' bytes, keyed by file name.""" + + from microcosm.build.uk_runtime.ods_tables import ( # noqa: PLC0415 + read_ods_tables, + ) + + tables = read_ods_tables(ods, label="HMRC R&D tax credit statistics tables") + cover = _text(tables["Cover"].cell(0, 0)) + if cover != COVER_TITLE: + raise ValueError(f"workbook is {cover!r}, not {COVER_TITLE!r}") + payloads = {} + for spec in TABLES: + sheet, name, _, _, columns = spec + rows = extract_table(tables[sheet].rows, spec) + payloads[name] = to_csv_bytes(columns, rows) + return payloads + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _iso_date(value: str) -> str: + try: + return dt.date.fromisoformat(value).isoformat() + except ValueError: + raise argparse.ArgumentTypeError( + f"access date {value!r} is not YYYY-MM-DD" + ) from None + + +def provenance( + ods: Path, payloads: dict[str, bytes], access_date: str = ACCESS_DATE +) -> dict[str, Any]: + workbook = ods.read_bytes() + return { + "kind": "uk_firm_rd_tax_credit_fixture", + "schema_version": 1, + "period": ( + "Financial year 2024-25 (accounting periods; provisional, uplifted " + "by HMRC for claims not yet received)" + ), + "accessed": access_date, + "method": ( + "Cells were read from the downloaded workbook on the access date " + "by tools/extract_uk_firm_rd_tax_credits_tables.py and written as " + "published text: thousands separators, HMRC's suppression marker " + "(a '<' followed by the rounding floor), 'N/A' and blank cells " + "are kept. None was filled from memory." + ), + "source": { + "publisher": "HM Revenue and Customs", + "dataset_title": "Corporate tax: Research and Development Tax Credits", + "landing_page": LANDING_PAGE, + "url": ODS_URL, + "edition": ( + "Research and Development Tax Credits Statistics: September " + "2026 (published 29 September 2026); Main tables 2026; claims " + "in Company Tax returns received on or before 31 May 2026" + ), + "file": ods.name, + "size_bytes": len(workbook), + "sha256": _sha256(workbook), + "sheets": {spec[1]: spec[0] for spec in TABLES}, + "rounding": ( + "All figures independently rounded to the nearest 5 or £5 " + "million; components may not sum to totals (Cover sheet)." + ), + "licence": "Open Government Licence v3.0", + }, + "edition_note": ( + "The September 2026 edition is the latest on the access date and " + "replaces the September 2025 edition (2023-24 claims). Its 2024-25 " + "year is the first with the merged RDEC scheme (accounting " + "periods beginning on or after 1 April 2024): HMRC notes SME-level " + "figures for 2024-25 are not comparable with earlier years." + ), + "coverage": ( + "RD6 sector is the primary SIC 2007 code of the registered " + "company, which may not be the sector of the R&D. RD6 gives the " + "number and cost of claims by scheme but qualifying expenditure " + "only in total per sector; RD4 gives expenditure by scheme only " + "nationally. RD1 counts claims (40,325 in 2024-25) and companies " + "(37,545) separately." + ), + "extraction_date": dt.date.today().isoformat(), + "tool": "tools/extract_uk_firm_rd_tax_credits_tables.py", + "command": ( + "uv run --no-sync python tools/extract_uk_firm_rd_tax_credits_tables.py " + "--ods /rd_tax_credits_main_tables_2026.ods" + ), + "files": { + name: { + "sha256": _sha256(payload), + "bytes": len(payload), + "rows": payload.count(b"\n") - 1, + } + for name, payload in payloads.items() + }, + } + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--ods", 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", + ) + parser.add_argument( + "--access-date", + type=_iso_date, + default=ACCESS_DATE, + help=( + "date (YYYY-MM-DD) the workbook was downloaded, written to the " + f"provenance (default {ACCESS_DATE}, the committed fixture's)" + ), + ) + args = parser.parse_args(argv) + ods = args.ods.resolve() + payloads = extract(ods) + if args.check: + stale = [ + name + for name, payload in payloads.items() + if not (args.out / name).is_file() + or (args.out / name).read_bytes() != payload + ] + for name in stale: + print(f"stale or missing: {name}", file=sys.stderr) + if stale: + return 1 + print("the R&D tax credit CSVs match the workbook") + return 0 + args.out.mkdir(parents=True, exist_ok=True) + for name, payload in payloads.items(): + (args.out / name).write_bytes(payload) + print(f"wrote {args.out / name}") + record = provenance(ods, payloads, args.access_date) + (args.out / PROVENANCE_NAME).write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8" + ) + print(f"wrote {args.out / PROVENANCE_NAME}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/extract_uk_firm_supply_use_tables.py b/tools/extract_uk_firm_supply_use_tables.py new file mode 100644 index 0000000000..f6ba06f443 --- /dev/null +++ b/tools/extract_uk_firm_supply_use_tables.py @@ -0,0 +1,650 @@ +#!/usr/bin/env python3 +"""Extract the ONS Supply and Use Tables (Blue Book 2026) for UK firm consumption links. + +Reads the ONS *Input-output supply and use tables* publication workbook +consistent with UK National Accounts 2026 Blue Book (``supublicationtablesbb26 +.xlsx``, "Supply and Use Tables, 1997 - 2024"), the year 2024 sheets, and +writes three CSVs of raw values in pounds million (not shares): + +``sut_product_uses.csv`` + One row per CPA product (Table 1 and Table 2 rows, 103 products): the + product's total intermediate consumption (Table 2 - Int Con, column + "Total intermediate demand"), its final demand by component (Table 2 - + Final Demand: households, NPISH, central government, local government, + gross fixed capital formation, valuables, changes in inventories, total + exports of goods and services), total demand for products, and its supply + (Table 1: total domestic output at basic prices, total imports of goods + and services, distributors' trading margins, taxes less subsidies on + products, total supply at purchasers' prices). + +``sut_hhfce_product_coicop.csv`` + Table 3 - HHFCE (domestic concept) in long form: product, COICOP column + as printed (classes ``01.1`` .. ``09.6``, then divisions ``10``, ``11``, + ``12``, which the table does not split), pounds million. Zero cells are + dropped. Table 3 prints Table 1's ``CPA_C27`` and ``CPA_C28`` as one row, + ``CPA_C27 & C28``, kept under that code. + +``sut_product_sic_division.csv`` + Each product's SIC 2007 two-digit division(s). A product code is + ``CPA_`` then one or more parts joined by ``&`` or ``,``; each part is a + section letter and a SIC code whose first two digits are the division. + So ``CPA_C102_3`` (SIC 10.2-3: classes 10.2 and 10.3) is division 10; + ``CPA_B05 & B06`` is divisions 05 and 06 (two rows); ``CPA_C11.01-6 & + C12`` is divisions 11 and 12; ``CPA_F41, F42 & F43`` is 41, 42 and 43; + ``CPA_K65.1-2 & K65.3`` is 65; ``CPA_L68BXL683`` (68B excluding 68.3), + ``CPA_L68A`` (imputed rent) and ``CPA_L683`` are all 68; ``CPA_C23OTHER`` + is 23. A product spanning several divisions is listed once per division + with the whole product: the tables give no split. The parse is checked + against the *Industry and product map* sheet: the same set of divisions + (the map's 98 and 99, "not explicitly measured", have no product), the + same section letter per division, and per division as many products as + the map has distinct A103 (publication level) codes. The map's SIC codes + and A103 codes of the division are carried for reference. + +Identities asserted per product before writing: domestic output + imports + +margins + taxes = total supply; intermediate + final demand = total demand = +total supply; the final demand components sum to total final demand; +Table 3's classes sum to its domestic-concept total, and domestic total + +non-resident expenditure + resident expenditure abroad = the national concept +total = Table 2's households column. Distributors' margins sum to zero. + +openpyxl is imported only when a workbook is read, so engine-free CI, which +reads the committed CSVs, never needs it. + +Usage:: + + uv run --no-sync python tools/extract_uk_firm_supply_use_tables.py \\ + --xlsx /supublicationtablesbb26.xlsx + + # Exit 1 if re-extraction would change the committed CSVs' bytes. + uv run --no-sync python tools/extract_uk_firm_supply_use_tables.py \\ + --xlsx /supublicationtablesbb26.xlsx --check +""" + +from __future__ import annotations + +import argparse +import csv +import datetime as dt +import hashlib +import io +import json +import re +import sys +from collections.abc import Sequence +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_supply_use_2024" +) +USES_NAME = "sut_product_uses.csv" +HHFCE_NAME = "sut_hhfce_product_coicop.csv" +DIVISION_NAME = "sut_product_sic_division.csv" +PROVENANCE_NAME = "firm_supply_use_2024.provenance.json" + +LANDING_PAGE = ( + "https://www.ons.gov.uk/economy/nationalaccounts/supplyandusetables/" + "datasets/inputoutputsupplyandusetables" +) +XLSX_URL = ( + "https://www.ons.gov.uk/file?uri=/economy/nationalaccounts/" + "supplyandusetables/datasets/inputoutputsupplyandusetables/current/" + "supublicationtablesbb26.xlsx" +) +#: The workbook the committed CSVs were extracted from. +XLSX_SHA256 = "716c9e023e95cad60d3ca6affb058540887f436ad21a2f3c0f8f01eec0bbeaa8" +#: The committed fixture's recorded access date: the default for +#: ``--access-date``, which the person who downloads the workbook sets. +ACCESS_DATE = "2026-11-22" + +YEAR = 2024 +CONTENTS = "Contents" +EDITION_TITLE = "Supply and Use Tables, 1997 - 2024" +EDITION_BASIS = "(consistent with UK National Accounts 2026 Blue Book)" +SUPPLY = f"Table 1 - Supply {YEAR}" +INT_CON = f"Table 2 - Int Con {YEAR}" +FINAL_DEMAND = f"Table 2 - Final Demand {YEAR}" +HHFCE = f"Table 3 - HHFCE {YEAR}" +MAP = "Industry and product map" +SHEETS = (SUPPLY, INT_CON, FINAL_DEMAND, HHFCE, MAP) + +#: Table 1 column -> header text (whitespace-normalised) it must sit under. +SUPPLY_COLUMNS = { + "domestic_output": "Total domestic output of products at basic prices", + "imports": "Total imports of goods and services", + "distributors_margins": "Distributors' Trading Margins", + "taxes_less_subsidies": "Taxes less subsidies on products", + "total_supply": "Total supply of products at purchasers' prices", +} +#: Table 2 final demand column -> header text. +FINAL_DEMAND_COLUMNS = { + "households": "Households", + "npish": "Non-profit institutions serving households", + "central_government": "Central government", + "local_government": "Local government", + "gfcf": "Gross fixed capital formation", + "valuables": "Valuables", + "changes_in_inventories": "Changes in inventories", + "exports": "Total exports of goods and services", + "total_final_demand": "Total final demand", + "total_demand": "Total demand for products", +} +INT_CON_TOTAL = "Total intermediate demand" +HHFCE_DOMESTIC = "Total (domestic concept)" +HHFCE_NON_RESIDENT = "Non-resident household expenditure in the UK" +HHFCE_ABROAD = "UK resident household expenditure abroad" +HHFCE_NATIONAL = "Total HHFCE (national concept)" + +USES_HEADER = ( + "product_code", + "product_label", + "intermediate_consumption", + "households", + "npish", + "central_government", + "local_government", + "gfcf", + "valuables", + "changes_in_inventories", + "exports", + "total_demand", + "domestic_output", + "imports", + "distributors_margins", + "taxes_less_subsidies", + "total_supply", +) +HHFCE_HEADER = ("product_code", "coicop", "value_gbp_million") +DIVISION_HEADER = ( + "product_code", + "sic_division", + "sic_section", + "map_sic_codes", + "map_a103_codes", +) +_FINAL_COMPONENTS = ( + "households", + "npish", + "central_government", + "local_government", + "gfcf", + "valuables", + "changes_in_inventories", + "exports", +) + + +def _text(value: Any) -> str: + return "" if value is None else " ".join(str(value).split()) + + +def _number(value: Any, where: str) -> int: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError(f"{where}: expected a number, got {value!r}") + if value != int(value): + raise ValueError(f"{where}: expected whole pounds million, got {value!r}") + return int(value) + + +def _column(header: Sequence[Any], label: str, sheet: str) -> int: + hits = [i for i, cell in enumerate(header) if _text(cell) == label] + if len(hits) != 1: + raise ValueError(f"{sheet}: header {label!r} found {len(hits)}x") + return hits[0] + + +def _product_rows(rows: list[tuple[Any, ...]]) -> dict[str, tuple[Any, ...]]: + out: dict[str, tuple[Any, ...]] = {} + for row in rows: + code = _text(row[0]) + if code.startswith("CPA_"): + if code in out: + raise ValueError(f"product {code} appears twice") + out[code] = row + return out + + +def _header_row(rows: list[tuple[Any, ...]], label: str, sheet: str) -> int: + for index, row in enumerate(rows[:8]): + if any(_text(cell) == label for cell in row): + return index + raise ValueError(f"{sheet}: no header row with {label!r}") + + +def product_divisions(code: str) -> list[tuple[str, str]]: + """``(section, two-digit division)`` of each part of a CPA product code.""" + + if not code.startswith("CPA_"): + raise ValueError(f"{code!r} is not a CPA product code") + out: list[tuple[str, str]] = [] + for part in re.split(r"[&,]", code[len("CPA_") :]): + match = re.fullmatch(r"([A-U])(\d{2})\S*", part.strip()) + if match is None: + raise ValueError(f"cannot read a SIC division from {part!r} in {code}") + pair = (match.group(1), match.group(2)) + if pair not in out: + out.append(pair) + return out + + +def table3_products(code: str, products: Sequence[str]) -> list[str]: + """The Table 1 products a Table 3 row covers. + + Table 3 prints some Table 1 products as one row, ``CPA_C27 & C28`` for + ``CPA_C27`` and ``CPA_C28``; any other row is its own product. + """ + + if code in products: + return [code] + parts = ["CPA_" + part.strip() for part in code[len("CPA_") :].split("&")] + if len(parts) < 2 or any(part not in products for part in parts): + raise ValueError(f"Table 3 product {code} is not a union of Table 1 products") + return parts + + +def _map_divisions( + rows: list[tuple[Any, ...]], +) -> dict[str, tuple[str, list[str], list[str]]]: + """Map sheet: division -> (section, SIC codes, distinct A103 codes).""" + + header = _header_row(rows, "A103", MAP) + columns = [_text(cell) for cell in rows[header]] + a21 = columns.index("A21") + a103 = columns.index("A103") + section = "" + last_a103: Any = None + out: dict[str, tuple[str, list[str], list[str]]] = {} + for row in rows[header + 2 :]: + raw = row[0] + code = _text(raw) + if not code or code.startswith("*") or not code[:2].isdigit(): + continue + if isinstance(raw, float): + # 10.1, 11.07, 33.15: openpyxl gives the printed decimal back. + code = repr(raw) + elif isinstance(raw, int): + code = f"{raw:02d}" + if _text(row[a21]): + section = _text(row[a21]) + if row[a103] is not None: + last_a103 = row[a103] + if code.endswith("*"): + # 98*, 99*: "not explicitly measured", no A103 code of their own. + out.setdefault(code[:2], (section, [code], [])) + continue + division = code[:2] + entry = out.setdefault(division, (section, [], [])) + if entry[0] != section: + raise ValueError(f"division {division} spans sections") + entry[1].append(code) + label = str(last_a103) + if label not in entry[2]: + entry[2].append(label) + return out + + +def extract_tables( + sheets: dict[str, list[tuple[Any, ...]]], +) -> tuple[list[tuple[Any, ...]], list[tuple[Any, ...]], list[tuple[Any, ...]]]: + """The three CSVs' rows from the five sheets' cell rows.""" + + supply_rows = sheets[SUPPLY] + if f"Supply of products in {YEAR}" not in _text(supply_rows[0][1]): + raise ValueError(f"{SUPPLY}: unexpected title {supply_rows[0][1]!r}") + s_head = supply_rows[_header_row(supply_rows, "Product", SUPPLY)] + s_col = {k: _column(s_head, v, SUPPLY) for k, v in SUPPLY_COLUMNS.items()} + supply = _product_rows(supply_rows) + + fd_rows = sheets[FINAL_DEMAND] + fd_head = fd_rows[_header_row(fd_rows, "Product", FINAL_DEMAND)] + fd_col = { + k: _column(fd_head, v, FINAL_DEMAND) for k, v in FINAL_DEMAND_COLUMNS.items() + } + final = _product_rows(fd_rows) + + ic_rows = sheets[INT_CON] + ic_head = ic_rows[_header_row(ic_rows, INT_CON_TOTAL, INT_CON)] + ic_total = _column(ic_head, INT_CON_TOTAL, INT_CON) + intermediate = _product_rows(ic_rows) + + hh_rows = sheets[HHFCE] + hh_label_row = _header_row(hh_rows, HHFCE_DOMESTIC, HHFCE) + hh_labels = hh_rows[hh_label_row] + hh_codes = [_text(cell) for cell in hh_rows[hh_label_row - 1]] + hh_domestic = _column(hh_labels, HHFCE_DOMESTIC, HHFCE) + hh_non_resident = _column(hh_labels, HHFCE_NON_RESIDENT, HHFCE) + hh_abroad = _column(hh_labels, HHFCE_ABROAD, HHFCE) + hh_national = _column(hh_labels, HHFCE_NATIONAL, HHFCE) + coicop_columns = [ + (i, code) + for i, code in enumerate(hh_codes) + if i < hh_domestic and re.fullmatch(r"\d{2}(\.\d)?", code) + ] + if len({code[:2] for _, code in coicop_columns}) != 12: + raise ValueError(f"{HHFCE}: expected COICOP divisions 01-12") + household = _product_rows(hh_rows) + + codes = list(supply) + for name, table in ((FINAL_DEMAND, final), (INT_CON, intermediate)): + if sorted(table) != sorted(codes): + raise ValueError(f"{name} products differ from {SUPPLY}'s") + # Table 3 merges some Table 1 products into one row (CPA_C27 & C28). + covered = {code: table3_products(code, codes) for code in household} + flat = sorted(p for parts in covered.values() for p in parts) + if flat != sorted(codes): + raise ValueError(f"{HHFCE} products do not partition {SUPPLY}'s") + households_by_code: dict[str, int] = {} + + uses: list[tuple[Any, ...]] = [] + hhfce: list[tuple[Any, ...]] = [] + margins = 0 + for code in codes: + s = {k: _number(supply[code][c], f"{code} {k}") for k, c in s_col.items()} + f = {k: _number(final[code][c], f"{code} {k}") for k, c in fd_col.items()} + ic = _number(intermediate[code][ic_total], f"{code} intermediate") + if ( + s["domestic_output"] + + s["imports"] + + s["distributors_margins"] + + s["taxes_less_subsidies"] + != s["total_supply"] + ): + raise ValueError(f"{code}: supply components do not add up") + if sum(f[k] for k in _FINAL_COMPONENTS) != f["total_final_demand"]: + raise ValueError(f"{code}: final demand components do not add up") + if ic + f["total_final_demand"] != f["total_demand"]: + raise ValueError(f"{code}: intermediate + final != total demand") + if f["total_demand"] != s["total_supply"]: + raise ValueError(f"{code}: total demand != total supply") + margins += s["distributors_margins"] + households_by_code[code] = f["households"] + uses.append( + ( + code, + _text(supply[code][1]), + ic, + *(f[k] for k in _FINAL_COMPONENTS), + f["total_demand"], + *( + s[k] + for k in ( + "domestic_output", + "imports", + "distributors_margins", + "taxes_less_subsidies", + "total_supply", + ) + ), + ) + ) + if margins != 0: + raise ValueError(f"distributors' margins sum to {margins}, not 0") + + for code, row in household.items(): + classes = 0 + for column, coicop in coicop_columns: + value = _number(row[column], f"{code} {coicop}") + classes += value + if value != 0: + hhfce.append((code, coicop, value)) + domestic = _number(row[hh_domestic], f"{code} domestic") + national = _number(row[hh_national], f"{code} national") + if classes != domestic: + raise ValueError(f"{code}: Table 3 classes != domestic total") + if ( + domestic + + _number(row[hh_non_resident], f"{code} non-resident") + + _number(row[hh_abroad], f"{code} abroad") + != national + ): + raise ValueError(f"{code}: Table 3 domestic + adjustments != national") + if national != sum(households_by_code[p] for p in covered[code]): + raise ValueError(f"{code}: Table 3 national != Table 2 households") + + mapped = _map_divisions(sheets[MAP]) + divisions: list[tuple[Any, ...]] = [] + products_per_division: dict[str, int] = {} + for code in codes: + for section, division in product_divisions(code): + if division not in mapped: + raise ValueError(f"{code}: division {division} not in {MAP}") + map_section, sic_codes, a103 = mapped[division] + if map_section != section: + raise ValueError( + f"{code}: section {section} but {MAP} has {map_section}" + ) + products_per_division[division] = products_per_division.get(division, 0) + 1 + divisions.append( + (code, division, section, ";".join(sic_codes), ";".join(a103)) + ) + for division, (_, _, a103) in mapped.items(): + found = products_per_division.get(division, 0) + if found != len(a103): + raise ValueError( + f"division {division}: {found} products, {MAP} has " + f"{len(a103)} A103 codes" + ) + divisions.sort(key=lambda row: (row[1], codes.index(row[0]))) + return uses, hhfce, divisions + + +def to_csv_bytes(header: Sequence[str], rows: list[tuple[Any, ...]]) -> bytes: + buffer = io.StringIO() + writer = csv.writer(buffer, lineterminator="\n") + writer.writerow(header) + writer.writerows(rows) + return buffer.getvalue().encode("utf-8") + + +def _read(xlsx: Path) -> dict[str, list[tuple[Any, ...]]]: + import openpyxl # noqa: PLC0415 - local-only dependency, kept out of CI imports + + book = openpyxl.load_workbook(xlsx, read_only=True, data_only=True) + try: + return { + name: list(book[name].iter_rows(values_only=True)) + for name in (CONTENTS, *SHEETS) + } + finally: + book.close() + + +def edition(contents: list[tuple[Any, ...]]) -> str: + """The Contents sheet's title, basis and release month.""" + + title = [_text(cell) for row in contents[:6] for cell in row if _text(cell)] + if EDITION_TITLE not in title or EDITION_BASIS not in title: + raise ValueError(f"workbook is not {EDITION_TITLE!r} {EDITION_BASIS!r}") + month = title[title.index(EDITION_BASIS) + 1] + if not re.fullmatch(r"[A-Z][a-z]+ \d{4}", month): + raise ValueError(f"no release month after the basis line: {month!r}") + return f"{EDITION_TITLE} {EDITION_BASIS}, released {month}" + + +def payloads( + sheets: dict[str, list[tuple[Any, ...]]], +) -> tuple[dict[str, bytes], dict[str, int]]: + uses, hhfce, divisions = extract_tables(sheets) + files = { + USES_NAME: to_csv_bytes(USES_HEADER, uses), + HHFCE_NAME: to_csv_bytes(HHFCE_HEADER, hhfce), + DIVISION_NAME: to_csv_bytes(DIVISION_HEADER, divisions), + } + counts = { + USES_NAME: len(uses), + HHFCE_NAME: len(hhfce), + DIVISION_NAME: len(divisions), + } + return files, counts + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _iso_date(value: str) -> str: + try: + return dt.date.fromisoformat(value).isoformat() + except ValueError: + raise argparse.ArgumentTypeError( + f"access date {value!r} is not YYYY-MM-DD" + ) from None + + +def provenance( + xlsx: Path, + release: str, + files: dict[str, bytes], + counts: dict[str, int], + access_date: str = ACCESS_DATE, +) -> dict[str, Any]: + workbook = xlsx.read_bytes() + headers = { + USES_NAME: USES_HEADER, + HHFCE_NAME: HHFCE_HEADER, + DIVISION_NAME: DIVISION_HEADER, + } + return { + "kind": "uk_firm_supply_use_fixture", + "schema_version": 1, + "period": f"calendar year {YEAR}", + "accessed": access_date, + "method": ( + "Figures were read from the downloaded workbook on the access date " + "by tools/extract_uk_firm_supply_use_tables.py; none was filled " + "from memory. Values are pounds million at current prices as " + "published. Demand is at purchasers' prices (the 'Combined Use' " + "matrix, domestic output and imports together); domestic output " + "is at basic prices. The product -> SIC division rows are parsed " + "from the CPA product codes and checked against the Industry and " + "product map sheet; a product spanning several divisions is " + "repeated once per division with the whole product." + ), + "identities_checked": [ + "domestic output + imports + distributors' margins + taxes less " + "subsidies = total supply (each product)", + "intermediate consumption + total final demand = total demand = " + "total supply (each product)", + "final demand components sum to total final demand (each product)", + "Table 3 COICOP columns sum to Total (domestic concept); domestic + " + "non-resident expenditure in the UK + resident expenditure abroad " + "= Total HHFCE (national concept) = Table 2 households (each " + "product)", + "distributors' margins sum to zero over products", + "products per SIC division = distinct A103 codes per division in " + "the Industry and product map", + ], + "notes": [ + "Table 2's households column is the national concept (includes UK " + "residents' spending abroad, excludes non-residents' spending in " + "the UK, which sits in exports); Table 3's COICOP columns are the " + "domestic concept.", + "Table 3 publishes COICOP classes for divisions 01-09 and only " + "division totals for 10, 11 and 12 (no 12.6.1 FISIM class).", + "Distributors' trading margins are negative only on the trade " + "products CPA_G45, CPA_G46 and CPA_G47 and are spread over the " + "goods products (and publishing products J58, J59 & J60) as " + "positive margins; one combined column, not split by wholesale, " + "retail and motor trade.", + "Table 3 footnote: COICOP data here may differ from Consumer " + "Trends because of the CPA to COICOP correlator; at the total " + "level they are consistent.", + "Table 3 has 102 product rows: it prints CPA_C27 and CPA_C28 as " + "one row, CPA_C27 & C28, written under that code.", + f"Zero cells of Table 3 are not written to {HHFCE_NAME}.", + ], + "source": { + "publisher": "Office for National Statistics", + "dataset_title": "Input-output supply and use tables", + "landing_page": LANDING_PAGE, + "url": XLSX_URL, + "edition": release, + "file": xlsx.name, + "size_bytes": len(workbook), + "sha256": _sha256(workbook), + "sheets": list(SHEETS), + "units": "pounds million, current prices", + "licence": "Open Government Licence v3.0", + }, + "extraction_date": dt.date.today().isoformat(), + "tool": "tools/extract_uk_firm_supply_use_tables.py", + "command": ( + "uv run --no-sync python tools/extract_uk_firm_supply_use_tables.py " + "--xlsx /supublicationtablesbb26.xlsx" + ), + "files": { + name: { + "sha256": _sha256(payload), + "bytes": len(payload), + "rows": counts[name], + "columns": list(headers[name]), + } + for name, payload in files.items() + }, + } + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--xlsx", 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", + ) + parser.add_argument( + "--access-date", + type=_iso_date, + default=ACCESS_DATE, + help=( + "date (YYYY-MM-DD) the workbook was downloaded, written to the " + f"provenance (default {ACCESS_DATE}, the committed fixture's)" + ), + ) + args = parser.parse_args(argv) + xlsx = args.xlsx.resolve() + digest = _sha256(xlsx.read_bytes()) + if digest != XLSX_SHA256: + print( + f"warning: workbook sha256 {digest} is not the pinned {XLSX_SHA256}", + file=sys.stderr, + ) + sheets = _read(xlsx) + release = edition(sheets[CONTENTS]) + files, counts = payloads(sheets) + if args.check: + stale = [ + name + for name, payload in files.items() + if not (args.out / name).is_file() + or (args.out / name).read_bytes() != payload + ] + for name in stale: + print(f"stale or missing: {name}", file=sys.stderr) + if stale: + return 1 + print("supply and use CSVs match the workbook") + return 0 + args.out.mkdir(parents=True, exist_ok=True) + for name, payload in files.items(): + (args.out / name).write_bytes(payload) + print(f"wrote {args.out / name} ({counts[name]} rows)") + record = provenance(xlsx, release, files, counts, args.access_date) + (args.out / PROVENANCE_NAME).write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8" + ) + print(f"wrote {args.out / PROVENANCE_NAME}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/extract_uk_firm_vat_composition_tables.py b/tools/extract_uk_firm_vat_composition_tables.py new file mode 100644 index 0000000000..44c04828e3 --- /dev/null +++ b/tools/extract_uk_firm_vat_composition_tables.py @@ -0,0 +1,266 @@ +"""Extract the VAT composition inputs for UK firms (opt-in, ``firm_vat_composition.py``). + +Reads two downloaded workbooks and writes the extracted CSVs beside the +hand-written product treatment table in +``packages/microcosm-build/tests/fixtures/uk/firm_vat_composition_2024/``: + +- ``sut_intermediate_consumption.csv``: ONS Supply and Use Tables 1997-2024 + (Blue Book 2026), sheet "Table 2 - Int Con 2024", the 'Combined Use' + intermediate consumption matrix in long form (product, industry, pounds + million). Industries are written under the product code they make: the + sheet's 103 industry columns align one-to-one, in order, with its 103 + product rows. Each industry code must equal its product's code, or be one + of the three spellings in ``INDUSTRY_ALIASES``; the tool refuses the + workbook otherwise. +- ``sut_dwellings_gfcf.csv``: sheet "Table 4 - GFCF 2024", the Dwellings + column of the construction product row (``CPA_F41, F42 & F43``) and the + row's total GFCF. +- ``abs_section_turnover.csv``: ONS Annual Business Survey 2024 results, + sheet "Sections A to S", the 2024 rows (turnover, approximate GVA and + total purchases by SIC section, pounds million), and the 2024 division + rows of sheets "Division 45", "Division 46" and "Division 47" (written + with their division code in ``sic_section``). +- ``hmrc_vat_relief_costs.csv``: HMRC Tax relief statistics (January 2026), + sheet "Table_2", the 2024-25 cost (pounds million) of the VAT reliefs + ``RELIEF_CODES``, with their first forecast year. Checks only. + +No value is typed by hand. ``--check`` re-extracts into memory and compares +with the committed CSVs and the sha256 values recorded in +``provenance.json``; it needs the same two downloads. + + uv run --no-sync python tools/extract_uk_firm_vat_composition_tables.py \ + --sut-xlsx /supublicationtablesbb26.xlsx \ + --abs-xlsx /abssectionsas.xlsx \ + --relief-ods /tax_relief_statistics_january_2026.ods [--check] +""" + +from __future__ import annotations + +import argparse +import hashlib +import io +import json +import sys +from pathlib import Path + +import openpyxl +import pandas as pd + +FIXTURE = Path("packages/microcosm-build/tests/fixtures/uk/firm_vat_composition_2024") +SUT_SHA256 = "716c9e023e95cad60d3ca6affb058540887f436ad21a2f3c0f8f01eec0bbeaa8" +ABS_SHA256 = "9e548c5c410b73e5a7aec1f97db8f92843430cb6ef5457b1459a0e0e9b13e710" +RELIEF_SHA256 = "fa94a61fe6b6a02c19b87a656154f27eaf5f00f35f0cce9339b8101b9ac8ee4a" +RELIEF_SHEET = "Table_2" +RELIEF_YEAR = "2024 to 2025" +RELIEF_CODES = ( + "VAT - NS1", + "VAT - NS2", + "VAT - NS3", + "VAT - NS4", + "VAT - NS5", + "VAT - NS6", + "VAT - NS7", + "VAT - NS16", +) +#: Industry codes the Int Con sheet spells differently from their product. +INDUSTRY_ALIASES = { + "C1101T1106 & C12": "C11.01-6 & C12", + "C241T243": "C241_3", + "H493T495": "H493_5", +} +ABS_DIVISION_SHEETS = ("Division 45", "Division 46", "Division 47") +INT_CON_SHEET = "Table 2 - Int Con 2024" +GFCF_SHEET = "Table 4 - GFCF 2024" +ABS_SHEET = "Sections A to S" +ABS_YEAR = 2024 +CONSTRUCTION = "CPA_F41, F42 & F43" + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _number(value: object) -> float: + if value in (None, "", "..", "-"): + return 0.0 + return float(value) + + +def _norm(code: object) -> str: + return " ".join(str(code).replace(" ", " ").split()) + + +def _product_rows(rows: list[tuple]) -> list[tuple]: + return [r for r in rows if isinstance(r[0], str) and r[0].startswith("CPA_")] + + +def extract_intermediate_consumption(wb: openpyxl.Workbook) -> pd.DataFrame: + rows = list(wb[INT_CON_SHEET].iter_rows(values_only=True)) + industries = [c for c in rows[3][2:] if c is not None] + products = _product_rows(rows) + codes = [r[0] for r in products] + if len(industries) != len(codes): + raise ValueError(f"{len(industries)} industries for {len(codes)} products") + for industry, product in zip(industries, codes, strict=True): + code = _norm(industry) + code = INDUSTRY_ALIASES.get(code, code) + if code.replace(" ", "") != _norm(product[len("CPA_") :]).replace(" ", ""): + raise ValueError(f"industry {industry!r} does not align with {product!r}") + out = [] + for r in products: + for j, product in enumerate(codes): + value = _number(r[2 + j]) + if value != 0.0: + out.append((r[0], product, value)) + return pd.DataFrame( + out, columns=["product_code", "industry_product_code", "value_gbp_million"] + ) + + +def extract_dwellings(wb: openpyxl.Workbook) -> pd.DataFrame: + rows = list(wb[GFCF_SHEET].iter_rows(values_only=True)) + header = rows[4] + dwellings = [i for i, h in enumerate(header) if h == "Dwellings"] + total = [i for i, h in enumerate(header) if h == "Total GFCF"] + if len(dwellings) != 1 or len(total) != 1: + raise ValueError("GFCF sheet lacks one Dwellings and one Total GFCF column") + row = [r for r in rows if r[0] == CONSTRUCTION] + if len(row) != 1: + raise ValueError(f"GFCF sheet lacks one {CONSTRUCTION} row") + return pd.DataFrame( + [ + { + "product_code": CONSTRUCTION, + "dwellings_gfcf_gbp_million": _number(row[0][dwellings[0]]), + "total_gfcf_gbp_million": _number(row[0][total[0]]), + } + ] + ) + + +def extract_abs(wb: openpyxl.Workbook) -> pd.DataFrame: + rows = list(wb[ABS_SHEET].iter_rows(values_only=True)) + header = rows[6] + want = { + "Total turnover": "turnover_gbp_million", + "Approximate gross value added at basic prices (aGVA)": "agva_gbp_million", + "Total purchases of goods, materials and services": "purchases_gbp_million", + } + index = {v: header.index(k) for k, v in want.items()} + out = [] + for r in rows[8:]: + if r[2] == ABS_YEAR and isinstance(r[0], str): + out.append( + { + "sic_section": r[0].strip(), + "year": ABS_YEAR, + **{col: _number(r[i]) for col, i in index.items()}, + } + ) + for sheet in ABS_DIVISION_SHEETS: + division = sheet.split()[-1] + rows = list(wb[sheet].iter_rows(values_only=True)) + header = rows[6] + index = {v: header.index(k) for k, v in want.items()} + match = [ + r for r in rows[8:] if r[2] == ABS_YEAR and str(r[0]).strip() == division + ] + if len(match) != 1: + raise ValueError(f"{sheet} has no single 2024 division row") + out.append( + { + "sic_section": division, + "year": ABS_YEAR, + **{col: _number(match[0][i]) for col, i in index.items()}, + } + ) + frame = pd.DataFrame(out) + if not {"G", "45", "46", "47"} <= set(frame["sic_section"]): + raise ValueError("ABS sheets lack the 2024 section G or division 45-47 rows") + return frame + + +def extract_reliefs(path: Path) -> pd.DataFrame: + table = pd.read_excel( + path, sheet_name=RELIEF_SHEET, engine="odf", header=None, dtype=str + ) + header = list(table.iloc[1]) + year = header.index(RELIEF_YEAR) + out = [] + for code in RELIEF_CODES: + row = table[table[1] == code] + if len(row) != 1: + raise ValueError(f"{RELIEF_SHEET} has no single {code} row") + r = row.iloc[0] + out.append( + { + "code": code, + "name": str(r[0]).strip(), + "first_forecast_year": str(r[4]).strip(), + "cost_2024_25_gbp_million": float(str(r[year]).replace(",", "")), + } + ) + return pd.DataFrame(out) + + +def extract(sut: Path, abs_path: Path, relief: Path) -> dict[str, pd.DataFrame]: + for path, expected in ( + (sut, SUT_SHA256), + (abs_path, ABS_SHA256), + (relief, RELIEF_SHA256), + ): + got = _sha256(path) + if got != expected: + raise ValueError(f"{path.name} sha256 {got} is not the pinned {expected}") + sut_wb = openpyxl.load_workbook(sut, read_only=True, data_only=True) + abs_wb = openpyxl.load_workbook(abs_path, read_only=True, data_only=True) + return { + "sut_intermediate_consumption.csv": extract_intermediate_consumption(sut_wb), + "sut_dwellings_gfcf.csv": extract_dwellings(sut_wb), + "abs_section_turnover.csv": extract_abs(abs_wb), + "hmrc_vat_relief_costs.csv": extract_reliefs(relief), + } + + +def _csv(frame: pd.DataFrame) -> bytes: + buffer = io.StringIO() + frame.to_csv(buffer, index=False, lineterminator="\n", float_format="%.10g") + return buffer.getvalue().encode() + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--sut-xlsx", type=Path, required=True) + parser.add_argument("--abs-xlsx", type=Path, required=True) + parser.add_argument("--relief-ods", type=Path, required=True) + parser.add_argument("--out-dir", type=Path, default=FIXTURE) + parser.add_argument("--check", action="store_true") + args = parser.parse_args(argv) + tables = extract(args.sut_xlsx, args.abs_xlsx, args.relief_ods) + provenance_path = args.out_dir / "provenance.json" + if args.check: + provenance = json.loads(provenance_path.read_text()) + bad = [] + for name, frame in tables.items(): + payload = _csv(frame) + if (args.out_dir / name).read_bytes() != payload: + bad.append(f"{name} differs from a fresh extraction") + if ( + provenance["files"][name]["sha256"] + != hashlib.sha256(payload).hexdigest() + ): + bad.append(f"{name} sha256 differs from provenance.json") + if bad: + print("\n".join(bad), file=sys.stderr) + return 1 + print("ok: extraction matches the committed CSVs") + return 0 + args.out_dir.mkdir(parents=True, exist_ok=True) + for name, frame in tables.items(): + (args.out_dir / name).write_bytes(_csv(frame)) + print(f"wrote {name} ({len(frame)} rows)") + 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())