diff --git a/changelog.d/uk-centax-childcare-parent-targets.added.md b/changelog.d/uk-centax-childcare-parent-targets.added.md new file mode 100644 index 0000000000..70f0fe04b7 --- /dev/null +++ b/changelog.d/uk-centax-childcare-parent-targets.added.md @@ -0,0 +1,9 @@ +The UK national line now calibrates parents of 3- and 4-year-olds to CenTax's HMRC tabulations of their incomes (microcosm#1399, for the £100k childcare costing in scorecard#207). + +**A derived national target family, `centax_childcare_parents`.** `tools/build_uk_centax_childcare_parent_facts.py` checks CenTax's data for the charts of Advani, Flew, Pepin-Hall and Summers (2026), *Removing the £100,000 childcare cliff-edge*, against its Chronicle registration (`centax-childcare-cliff-edge-2026`, raw only), reads Figures 3.1, 3.6 and 3.7, and writes five counts at England grain to `uk/centax_childcare_parent_facts.json`: three adjusted net income bands that partition (£50k, £200k] in 2021-22 pounds, and two splits of (£80k, £150k] (women and London). Each count is CenTax's published share of the parents in (£50k, £200k] times the baseline build's own parents in that range, so the targets set the shape of the distribution above £50k and leave its level where the baseline put it. The edges are aged to the calibration year by the OBR average earnings index policyengine-uk carries. Five contract targets (`microcosm.centax_childcare_parents.*`) bind them on the national line only. CenTax's model outputs (bunching estimates, frictions, elasticities, marginal bunchers and costs) are never targets. + +**Two person measures.** `centax_parent_of_eligible_3_4_year_old` marks the adults of a benefit unit with a dependent child in England of DfE age 3 to 5 who is before school in at least one of the year's terms, on the DfE age and term share `uk_runtime/dfe_spring_term.py` reads. `centax_employment_main_income_source`, which the diagnostic reads, marks people whose year's pay plus taxable benefits in kind is positive and at least every other component of the year's adjusted net income. The resolver also computes `adjusted_net_income_annual` on the annual-income simulation. + +**The derived-facts loader.** `uk_runtime/derived_facts.py` reads the CenTax cells beside the high-value home stock and DESNZ's constituency energy at every compile site (the full and national target inputs, the release-cut certifier, the compile-parity receipts, the UC matrix diagnostic and the incumbent surface evaluation), and the target-input receipts name each resource. `tools/generate_uk_target_references.py` streams the feed line by line instead of holding its text. + +**A diagnostic.** `tools/diagnose_uk_centax_parents.py` reports each cell's fit and support on a national H5; the cells kept as diagnostics (the band up to £50k, with its parents who have no pay, profit or private pension in the year; the region groups outside London with the East of England in either; and the parents whose main income source is not employment, too thinly supported to bind); the drift of the H5's parents in (£50k, £200k] from the resource's; and, from the registered workbook, CenTax's own figures for those cells, Table A.1's levels and Figure 3.12. diff --git a/packages/microcosm-build/src/microcosm/build/uk/centax_childcare_parent_facts.json b/packages/microcosm-build/src/microcosm/build/uk/centax_childcare_parent_facts.json new file mode 100644 index 0000000000..dfee8c9812 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk/centax_childcare_parent_facts.json @@ -0,0 +1,488 @@ +{ + "built_on": "2026-11-24", + "description": "Microcosm-derived counts of parents of age-eligible 3- and 4-year-olds in England by adjusted net income, from CenTax's HMRC tabulations for 2021-22 (Advani, Flew, Pepin-Hall and Summers 2026, Figures 3.1, 3.3, 3.6 and 3.7, from the workbook Chronicle registers as centax-childcare-cliff-edge-2026): each published share of the parents in (\u00a350k, \u00a3200k] times the baseline build's own parents in that range. No CenTax model output, and none of the figures kept as diagnostics.", + "generator": { + "tool": "tools/build_uk_centax_childcare_parent_facts.py", + "version": "uk-centax-childcare-parents-v2" + }, + "inputs": { + "baseline": { + "dataset": "uk-frs-calibration-attempt-20261122T100732Z-b891aa69", + "diagnostics_schema": "microcosm.uk.centax_parent_diagnostics.v2", + "policyengine_uk_version": "2.179.2", + "sha256": "ae116bc3cff798fe68df253083f0b26d779e02a0a818ee68df7d29fbc557165a" + }, + "method": "uk-centax-childcare-parents-v2", + "workbook": { + "chronicle_package_id": "centax-childcare-cliff-edge-2026", + "chronicle_source_id": "centax", + "figures": [ + "Fig. 3.1", + "Fig. 3.6", + "Fig. 3.7" + ], + "files": { + "2026": { + "filename": "AdvaniFlewPepinhallSummers2026_ChildcareThreshold_data.xlsx", + "r2_key": "raw/uk/centax/centax-childcare-cliff-edge-2026/2026/8c23855745154a601064e766552c64bc2e88de51e043b4df1397c580e969354b/AdvaniFlewPepinhallSummers2026_ChildcareThreshold_data.xlsx", + "sha256": "8c23855745154a601064e766552c64bc2e88de51e043b4df1397c580e969354b", + "size_bytes": 194075, + "source_url": "https://arunadvani.com/data/AdvaniFlewPepinhallSummers2026_ChildcareThreshold_data.xlsx" + } + }, + "licence": { + "attribution": "Advani, A., Flew, J., Pepin-Hall, J. and Summers, A. (2026), Removing the \u00a3100,000 childcare cliff-edge: Impacts and cost of reform, CenTax Policy Report; data for the charts. Authors' calculations based on HMRC administrative datasets.", + "license": "None stated", + "license_evidence": "Neither the page that links the workbook (https://arunadvani.com/policy.html#ChildcareCliffEdge, \"Data for the charts\", beside the report) nor CenTax's report page (https://centax.org.uk/removing-the-childcare-cliff-edge-impacts-and-cost-of-reform/, which links only the PDF) nor the workbook states a licence; every sheet cites the authors' calculations based on HMRC administrative datasets. Arun Advani (CenTax) has said he is open to PolicyEngine using the data published at source_url (relayed by Mar\u00eda Juaristi, PolicyEngine, 23 November 2026). With no licence stated, the bytes stay out of this public repository: the workbook is git-ignored and the private ledger-raw bucket holds it.", + "license_source": "manifest", + "license_verified_at": "2026-11-23", + "package_id": "centax-childcare-cliff-edge-2026" + }, + "registration_kind": "raw_only", + "report_url": "https://centax.org.uk/wp-content/uploads/2026/09/AdvaniFlewPepin-HallSummers2026_Removing-the-childcare-cliff-edge.pdf", + "source_page": "https://arunadvani.com/policy.html#ChildcareCliffEdge" + } + }, + "inputs_sha256": "f6539c0a353ad60d95874f453b7e66e062663010255aa21b1852f1ea4c6ec860", + "kind": "uk_derived_consumer_facts", + "licence": { + "attribution": [ + "Advani, A., Flew, J., Pepin-Hall, J. and Summers, A. (2026), Removing the \u00a3100,000 childcare cliff-edge: Impacts and cost of reform, CenTax Policy Report; data for the charts. Authors' calculations based on HMRC administrative datasets." + ] + }, + "parameters": { + "ani_bands_2022": { + "ani_120k_to_200k": [ + 120000.0, + 200000.0 + ], + "ani_50k_to_80k": [ + 50000.0, + 80000.0 + ], + "ani_80k_to_120k": [ + 80000.0, + 120000.0 + ] + }, + "ani_uprating": 1.2337297844440867, + "ani_uprating_basis": "policyengine-uk gov.economic_assumptions.indices.obr.average_earnings, 2025 over 2021", + "calibration_year": 2025, + "model_ani_edges": { + "ani_120k_to_200k": [ + 148048, + 246746 + ], + "ani_50k_to_80k": [ + 61686, + 98698 + ], + "ani_80k_to_120k": [ + 98698, + 148048 + ], + "female_ani_80k_to_150k": [ + 98698, + 185059 + ], + "london_ani_80k_to_150k": [ + 98698, + 185059 + ] + }, + "never_targets": [ + "Tables 3.1, 3.2 and 4.1 (bunching estimates)", + "friction parameters, elasticities and marginal bunchers", + "every fiscal cost" + ], + "parent_count": 318478.71745317057, + "parent_count_basis": "baseline parents of age-eligible 3- and 4-year-olds with annual ANI in (61,686, 246,746] at 2025", + "share_base_2022": [ + 50000.0, + 200000.0 + ], + "shares": { + "ani_120k_to_200k": 0.10837445835339432, + "ani_50k_to_80k": 0.6443525818488204, + "ani_80k_to_120k": 0.24727295979778527, + "female_ani_80k_to_150k": 0.08181143441158602, + "london_ani_80k_to_150k": 0.08806832622390573 + }, + "split_band_2022": [ + 80000.0, + 150000.0 + ], + "split_band_share": 0.30851664058738565 + }, + "resource": "centax_childcare_parent_facts.json", + "row_count": 5, + "rows": [ + { + "aggregate_fact_key": "microcosm.derived_fact.centax_childcare_parents.v1:0bbe969a4232bd47960ab374", + "aggregation": { + "method": "sum" + }, + "assertion": "observation", + "concept_alignment": { + "canonical_concept": "uk.person.count", + "relation": "derived", + "source_concept": "microcosm.centax_childcare_parents.count" + }, + "dimension_labels": { + "microcosm.centax_cell": "CenTax parent cell (2021-22 ANI pounds)" + }, + "dimension_value_labels": { + "microcosm.centax_cell": { + "ani_80k_to_120k": "ANI over \u00a380,000 to \u00a3120,000" + } + }, + "dimensions": { + "microcosm.centax_cell": "ani_80k_to_120k" + }, + "entity": { + "name": "person", + "role": "parent" + }, + "geography": { + "id": "E92000001", + "level": "country", + "name": "England", + "vintage": "current" + }, + "label": "Parents of age-eligible 3- and 4-year-olds, ANI over \u00a380,000 to \u00a3120,000 (2021-22 pounds), England", + "layout": { + "measure_id": "parents_of_eligible_3_4_year_olds", + "record_set_id": "uk.centax_childcare_parents.ani_80k_to_120k", + "record_set_spec_id": "uk.centax_childcare_parents.ani_80k_to_120k.v1" + }, + "lineage": { + "source_record_id": "microcosm.centax_childcare_parents.ani_80k_to_120k" + }, + "measure": { + "unit": "count" + }, + "observed_measure": { + "source_concept": "microcosm.centax_childcare_parents.count", + "source_measure_id": "parents_of_eligible_3_4_year_olds", + "unit": "count" + }, + "period": { + "type": "calendar_year", + "value": "2025" + }, + "period_coverage": { + "basis": "flow", + "end_date": "2026-04-05", + "notes": "The 2025-26 tax year's ANI, which policyengine-uk dates 2025, the period value. CenTax's share for tax year 2021-22 times the baseline build's parents at 2025; the ANI edges are aged to 2025 pounds (98,698 to 148,048).", + "start_date": "2025-04-06" + }, + "provenance_class": "derived_administrative", + "schema_version": "microcosm.derived_consumer_fact.v1", + "semantic_fact_key": "microcosm.semantic_fact.centax_childcare_parents.v1:0bbe969a4232bd47960ab374", + "source": { + "source_file": "centax_childcare_parent_facts.json", + "source_name": "microcosm", + "source_sha256": "f6539c0a353ad60d95874f453b7e66e062663010255aa21b1852f1ea4c6ec860", + "source_table": "CenTax, Removing the \u00a3100,000 childcare cliff-edge (2026), Fig. 3.1 (Chronicle centax-childcare-cliff-edge-2026); Microcosm derivation", + "url": "https://centax.org.uk/wp-content/uploads/2026/09/AdvaniFlewPepin-HallSummers2026_Removing-the-childcare-cliff-edge.pdf", + "vintage": "centax_2026_09" + }, + "value": 78751.175, + "value_type": "float" + }, + { + "aggregate_fact_key": "microcosm.derived_fact.centax_childcare_parents.v1:a46422479b671c651ef9950e", + "aggregation": { + "method": "sum" + }, + "assertion": "observation", + "concept_alignment": { + "canonical_concept": "uk.person.count", + "relation": "derived", + "source_concept": "microcosm.centax_childcare_parents.count" + }, + "dimension_labels": { + "microcosm.centax_cell": "CenTax parent cell (2021-22 ANI pounds)" + }, + "dimension_value_labels": { + "microcosm.centax_cell": { + "female_ani_80k_to_150k": "women, ANI over \u00a380,000 to \u00a3150,000" + } + }, + "dimensions": { + "microcosm.centax_cell": "female_ani_80k_to_150k" + }, + "entity": { + "name": "person", + "role": "parent" + }, + "geography": { + "id": "E92000001", + "level": "country", + "name": "England", + "vintage": "current" + }, + "label": "Parents of age-eligible 3- and 4-year-olds, women, ANI over \u00a380,000 to \u00a3150,000 (2021-22 pounds), England", + "layout": { + "measure_id": "parents_of_eligible_3_4_year_olds", + "record_set_id": "uk.centax_childcare_parents.female_ani_80k_to_150k", + "record_set_spec_id": "uk.centax_childcare_parents.female_ani_80k_to_150k.v1" + }, + "lineage": { + "source_record_id": "microcosm.centax_childcare_parents.female_ani_80k_to_150k" + }, + "measure": { + "unit": "count" + }, + "observed_measure": { + "source_concept": "microcosm.centax_childcare_parents.count", + "source_measure_id": "parents_of_eligible_3_4_year_olds", + "unit": "count" + }, + "period": { + "type": "calendar_year", + "value": "2025" + }, + "period_coverage": { + "basis": "flow", + "end_date": "2026-04-05", + "notes": "The 2025-26 tax year's ANI, which policyengine-uk dates 2025, the period value. CenTax's share for tax year 2021-22 times the baseline build's parents at 2025; the ANI edges are aged to 2025 pounds (98,698 to 185,059).", + "start_date": "2025-04-06" + }, + "provenance_class": "derived_administrative", + "schema_version": "microcosm.derived_consumer_fact.v1", + "semantic_fact_key": "microcosm.semantic_fact.centax_childcare_parents.v1:a46422479b671c651ef9950e", + "source": { + "source_file": "centax_childcare_parent_facts.json", + "source_name": "microcosm", + "source_sha256": "f6539c0a353ad60d95874f453b7e66e062663010255aa21b1852f1ea4c6ec860", + "source_table": "CenTax, Removing the \u00a3100,000 childcare cliff-edge (2026), Fig. 3.6 (Chronicle centax-childcare-cliff-edge-2026); Microcosm derivation", + "url": "https://centax.org.uk/wp-content/uploads/2026/09/AdvaniFlewPepin-HallSummers2026_Removing-the-childcare-cliff-edge.pdf", + "vintage": "centax_2026_09" + }, + "value": 26055.201, + "value_type": "float" + }, + { + "aggregate_fact_key": "microcosm.derived_fact.centax_childcare_parents.v1:a6af4be857b390dc38982965", + "aggregation": { + "method": "sum" + }, + "assertion": "observation", + "concept_alignment": { + "canonical_concept": "uk.person.count", + "relation": "derived", + "source_concept": "microcosm.centax_childcare_parents.count" + }, + "dimension_labels": { + "microcosm.centax_cell": "CenTax parent cell (2021-22 ANI pounds)" + }, + "dimension_value_labels": { + "microcosm.centax_cell": { + "london_ani_80k_to_150k": "London, ANI over \u00a380,000 to \u00a3150,000" + } + }, + "dimensions": { + "microcosm.centax_cell": "london_ani_80k_to_150k" + }, + "entity": { + "name": "person", + "role": "parent" + }, + "geography": { + "id": "E92000001", + "level": "country", + "name": "England", + "vintage": "current" + }, + "label": "Parents of age-eligible 3- and 4-year-olds, London, ANI over \u00a380,000 to \u00a3150,000 (2021-22 pounds), England", + "layout": { + "measure_id": "parents_of_eligible_3_4_year_olds", + "record_set_id": "uk.centax_childcare_parents.london_ani_80k_to_150k", + "record_set_spec_id": "uk.centax_childcare_parents.london_ani_80k_to_150k.v1" + }, + "lineage": { + "source_record_id": "microcosm.centax_childcare_parents.london_ani_80k_to_150k" + }, + "measure": { + "unit": "count" + }, + "observed_measure": { + "source_concept": "microcosm.centax_childcare_parents.count", + "source_measure_id": "parents_of_eligible_3_4_year_olds", + "unit": "count" + }, + "period": { + "type": "calendar_year", + "value": "2025" + }, + "period_coverage": { + "basis": "flow", + "end_date": "2026-04-05", + "notes": "The 2025-26 tax year's ANI, which policyengine-uk dates 2025, the period value. CenTax's share for tax year 2021-22 times the baseline build's parents at 2025; the ANI edges are aged to 2025 pounds (98,698 to 185,059).", + "start_date": "2025-04-06" + }, + "provenance_class": "derived_administrative", + "schema_version": "microcosm.derived_consumer_fact.v1", + "semantic_fact_key": "microcosm.semantic_fact.centax_childcare_parents.v1:a6af4be857b390dc38982965", + "source": { + "source_file": "centax_childcare_parent_facts.json", + "source_name": "microcosm", + "source_sha256": "f6539c0a353ad60d95874f453b7e66e062663010255aa21b1852f1ea4c6ec860", + "source_table": "CenTax, Removing the \u00a3100,000 childcare cliff-edge (2026), Fig. 3.7 (Chronicle centax-childcare-cliff-edge-2026); Microcosm derivation", + "url": "https://centax.org.uk/wp-content/uploads/2026/09/AdvaniFlewPepin-HallSummers2026_Removing-the-childcare-cliff-edge.pdf", + "vintage": "centax_2026_09" + }, + "value": 28047.888, + "value_type": "float" + }, + { + "aggregate_fact_key": "microcosm.derived_fact.centax_childcare_parents.v1:c230adc0ce149f0b98da6684", + "aggregation": { + "method": "sum" + }, + "assertion": "observation", + "concept_alignment": { + "canonical_concept": "uk.person.count", + "relation": "derived", + "source_concept": "microcosm.centax_childcare_parents.count" + }, + "dimension_labels": { + "microcosm.centax_cell": "CenTax parent cell (2021-22 ANI pounds)" + }, + "dimension_value_labels": { + "microcosm.centax_cell": { + "ani_120k_to_200k": "ANI over \u00a3120,000 to \u00a3200,000" + } + }, + "dimensions": { + "microcosm.centax_cell": "ani_120k_to_200k" + }, + "entity": { + "name": "person", + "role": "parent" + }, + "geography": { + "id": "E92000001", + "level": "country", + "name": "England", + "vintage": "current" + }, + "label": "Parents of age-eligible 3- and 4-year-olds, ANI over \u00a3120,000 to \u00a3200,000 (2021-22 pounds), England", + "layout": { + "measure_id": "parents_of_eligible_3_4_year_olds", + "record_set_id": "uk.centax_childcare_parents.ani_120k_to_200k", + "record_set_spec_id": "uk.centax_childcare_parents.ani_120k_to_200k.v1" + }, + "lineage": { + "source_record_id": "microcosm.centax_childcare_parents.ani_120k_to_200k" + }, + "measure": { + "unit": "count" + }, + "observed_measure": { + "source_concept": "microcosm.centax_childcare_parents.count", + "source_measure_id": "parents_of_eligible_3_4_year_olds", + "unit": "count" + }, + "period": { + "type": "calendar_year", + "value": "2025" + }, + "period_coverage": { + "basis": "flow", + "end_date": "2026-04-05", + "notes": "The 2025-26 tax year's ANI, which policyengine-uk dates 2025, the period value. CenTax's share for tax year 2021-22 times the baseline build's parents at 2025; the ANI edges are aged to 2025 pounds (148,048 to 246,746).", + "start_date": "2025-04-06" + }, + "provenance_class": "derived_administrative", + "schema_version": "microcosm.derived_consumer_fact.v1", + "semantic_fact_key": "microcosm.semantic_fact.centax_childcare_parents.v1:c230adc0ce149f0b98da6684", + "source": { + "source_file": "centax_childcare_parent_facts.json", + "source_name": "microcosm", + "source_sha256": "f6539c0a353ad60d95874f453b7e66e062663010255aa21b1852f1ea4c6ec860", + "source_table": "CenTax, Removing the \u00a3100,000 childcare cliff-edge (2026), Fig. 3.1 (Chronicle centax-childcare-cliff-edge-2026); Microcosm derivation", + "url": "https://centax.org.uk/wp-content/uploads/2026/09/AdvaniFlewPepin-HallSummers2026_Removing-the-childcare-cliff-edge.pdf", + "vintage": "centax_2026_09" + }, + "value": 34514.959, + "value_type": "float" + }, + { + "aggregate_fact_key": "microcosm.derived_fact.centax_childcare_parents.v1:d0a4f4a79c439e3222f10172", + "aggregation": { + "method": "sum" + }, + "assertion": "observation", + "concept_alignment": { + "canonical_concept": "uk.person.count", + "relation": "derived", + "source_concept": "microcosm.centax_childcare_parents.count" + }, + "dimension_labels": { + "microcosm.centax_cell": "CenTax parent cell (2021-22 ANI pounds)" + }, + "dimension_value_labels": { + "microcosm.centax_cell": { + "ani_50k_to_80k": "ANI over \u00a350,000 to \u00a380,000" + } + }, + "dimensions": { + "microcosm.centax_cell": "ani_50k_to_80k" + }, + "entity": { + "name": "person", + "role": "parent" + }, + "geography": { + "id": "E92000001", + "level": "country", + "name": "England", + "vintage": "current" + }, + "label": "Parents of age-eligible 3- and 4-year-olds, ANI over \u00a350,000 to \u00a380,000 (2021-22 pounds), England", + "layout": { + "measure_id": "parents_of_eligible_3_4_year_olds", + "record_set_id": "uk.centax_childcare_parents.ani_50k_to_80k", + "record_set_spec_id": "uk.centax_childcare_parents.ani_50k_to_80k.v1" + }, + "lineage": { + "source_record_id": "microcosm.centax_childcare_parents.ani_50k_to_80k" + }, + "measure": { + "unit": "count" + }, + "observed_measure": { + "source_concept": "microcosm.centax_childcare_parents.count", + "source_measure_id": "parents_of_eligible_3_4_year_olds", + "unit": "count" + }, + "period": { + "type": "calendar_year", + "value": "2025" + }, + "period_coverage": { + "basis": "flow", + "end_date": "2026-04-05", + "notes": "The 2025-26 tax year's ANI, which policyengine-uk dates 2025, the period value. CenTax's share for tax year 2021-22 times the baseline build's parents at 2025; the ANI edges are aged to 2025 pounds (61,686 to 98,698).", + "start_date": "2025-04-06" + }, + "provenance_class": "derived_administrative", + "schema_version": "microcosm.derived_consumer_fact.v1", + "semantic_fact_key": "microcosm.semantic_fact.centax_childcare_parents.v1:d0a4f4a79c439e3222f10172", + "source": { + "source_file": "centax_childcare_parent_facts.json", + "source_name": "microcosm", + "source_sha256": "f6539c0a353ad60d95874f453b7e66e062663010255aa21b1852f1ea4c6ec860", + "source_table": "CenTax, Removing the \u00a3100,000 childcare cliff-edge (2026), Fig. 3.1 (Chronicle centax-childcare-cliff-edge-2026); Microcosm derivation", + "url": "https://centax.org.uk/wp-content/uploads/2026/09/AdvaniFlewPepin-HallSummers2026_Removing-the-childcare-cliff-edge.pdf", + "vintage": "centax_2026_09" + }, + "value": 205212.584, + "value_type": "float" + } + ], + "rows_sha256": "97c7b47a5667b9e262bcb0e063b38b27cdd9699c94cb498e7e88fe8f0428333e", + "schema_version": 2 +} diff --git a/packages/microcosm-build/src/microcosm/build/uk/country_package.json b/packages/microcosm-build/src/microcosm/build/uk/country_package.json index 0e0d5328f9..4031ed2699 100644 --- a/packages/microcosm-build/src/microcosm/build/uk/country_package.json +++ b/packages/microcosm-build/src/microcosm/build/uk/country_package.json @@ -287,6 +287,11 @@ "kind": "legacy_json", "schema_id": "legacy_json" }, + { + "path": "centax_childcare_parent_facts.json", + "kind": "legacy_json", + "schema_id": "legacy_json" + }, { "path": "high_value_home_value_knots.json", "kind": "legacy_json", diff --git a/packages/microcosm-build/src/microcosm/build/uk/ledger_compile_parity_incumbent_2025_signed_differences.json b/packages/microcosm-build/src/microcosm/build/uk/ledger_compile_parity_incumbent_2025_signed_differences.json index b0849c049e..3462e35ef0 100644 --- a/packages/microcosm-build/src/microcosm/build/uk/ledger_compile_parity_incumbent_2025_signed_differences.json +++ b/packages/microcosm-build/src/microcosm/build/uk/ledger_compile_parity_incumbent_2025_signed_differences.json @@ -1,11 +1,11 @@ { - "compiled_count": 1714, + "compiled_count": 1719, "counts_by_kind": { "calibration_drift": 564, "fixture_only": 44, - "ledger_only": 1121 + "ledger_only": 1126 }, - "difference_count": 1729, + "difference_count": 1734, "differences": [ { "fixture_value": 1608000.0, @@ -6370,6 +6370,41 @@ "period": 2025, "reason": "Ledger-compiled row has no fixture counterpart at this comparison period." }, + { + "kind": "ledger_only", + "ledger_value": 34514.959, + "name": "microcosm.centax_childcare_parents.ani_120k_to_200k", + "period": 2025, + "reason": "ledger_only by construction: the row is a Microcosm-derived count of parents of age-eligible 3- and 4-year-olds in England in one adjusted net income cell: CenTax's share of HMRC's 2021-22 tabulation (Advani, Flew, Pepin-Hall and Summers 2026, Figures 3.1, 3.3, 3.6 and 3.7) times the baseline build's own parents (uk/centax_childcare_parent_facts.json), compiled beside the Chronicle feed. The incumbent registry carries no such row, so the difference is the derived target itself. The rows bind on the national line only (calibration_lines; microcosm#1399)." + }, + { + "kind": "ledger_only", + "ledger_value": 205212.584, + "name": "microcosm.centax_childcare_parents.ani_50k_to_80k", + "period": 2025, + "reason": "ledger_only by construction: the row is a Microcosm-derived count of parents of age-eligible 3- and 4-year-olds in England in one adjusted net income cell: CenTax's share of HMRC's 2021-22 tabulation (Advani, Flew, Pepin-Hall and Summers 2026, Figures 3.1, 3.3, 3.6 and 3.7) times the baseline build's own parents (uk/centax_childcare_parent_facts.json), compiled beside the Chronicle feed. The incumbent registry carries no such row, so the difference is the derived target itself. The rows bind on the national line only (calibration_lines; microcosm#1399)." + }, + { + "kind": "ledger_only", + "ledger_value": 78751.175, + "name": "microcosm.centax_childcare_parents.ani_80k_to_120k", + "period": 2025, + "reason": "ledger_only by construction: the row is a Microcosm-derived count of parents of age-eligible 3- and 4-year-olds in England in one adjusted net income cell: CenTax's share of HMRC's 2021-22 tabulation (Advani, Flew, Pepin-Hall and Summers 2026, Figures 3.1, 3.3, 3.6 and 3.7) times the baseline build's own parents (uk/centax_childcare_parent_facts.json), compiled beside the Chronicle feed. The incumbent registry carries no such row, so the difference is the derived target itself. The rows bind on the national line only (calibration_lines; microcosm#1399)." + }, + { + "kind": "ledger_only", + "ledger_value": 26055.201, + "name": "microcosm.centax_childcare_parents.female_ani_80k_to_150k", + "period": 2025, + "reason": "ledger_only by construction: the row is a Microcosm-derived count of parents of age-eligible 3- and 4-year-olds in England in one adjusted net income cell: CenTax's share of HMRC's 2021-22 tabulation (Advani, Flew, Pepin-Hall and Summers 2026, Figures 3.1, 3.3, 3.6 and 3.7) times the baseline build's own parents (uk/centax_childcare_parent_facts.json), compiled beside the Chronicle feed. The incumbent registry carries no such row, so the difference is the derived target itself. The rows bind on the national line only (calibration_lines; microcosm#1399)." + }, + { + "kind": "ledger_only", + "ledger_value": 28047.888, + "name": "microcosm.centax_childcare_parents.london_ani_80k_to_150k", + "period": 2025, + "reason": "ledger_only by construction: the row is a Microcosm-derived count of parents of age-eligible 3- and 4-year-olds in England in one adjusted net income cell: CenTax's share of HMRC's 2021-22 tabulation (Advani, Flew, Pepin-Hall and Summers 2026, Figures 3.1, 3.3, 3.6 and 3.7) times the baseline build's own parents (uk/centax_childcare_parent_facts.json), compiled beside the Chronicle feed. The incumbent registry carries no such row, so the difference is the derived target itself. The rows bind on the national line only (calibration_lines; microcosm#1399)." + }, { "kind": "ledger_only", "ledger_value": 492.631, diff --git a/packages/microcosm-build/src/microcosm/build/uk/target_reference_membership.json b/packages/microcosm-build/src/microcosm/build/uk/target_reference_membership.json index 342f5a291e..32957a39ec 100644 --- a/packages/microcosm-build/src/microcosm/build/uk/target_reference_membership.json +++ b/packages/microcosm-build/src/microcosm/build/uk/target_reference_membership.json @@ -1,11 +1,11 @@ { "source_fact_feed": "chronicle-uk-15040ea-consumer-facts", "target_period": 2025, - "candidate_count": 1751, - "contract_target_count": 595, - "active_reference_count": 1714, + "candidate_count": 1756, + "contract_target_count": 600, + "active_reference_count": 1719, "status_counts": { - "active": 1714, + "active": 1719, "signed_excluded": 37 }, "geography_pins": { @@ -5874,6 +5874,26 @@ "ons.paye_rti.pay_aged_18_to_24": { "geography_level": "country", "geography_id": "K02000001" + }, + "microcosm.centax_childcare_parents.ani_50k_to_80k": { + "geography_level": "country", + "geography_id": "E92000001" + }, + "microcosm.centax_childcare_parents.ani_80k_to_120k": { + "geography_level": "country", + "geography_id": "E92000001" + }, + "microcosm.centax_childcare_parents.ani_120k_to_200k": { + "geography_level": "country", + "geography_id": "E92000001" + }, + "microcosm.centax_childcare_parents.female_ani_80k_to_150k": { + "geography_level": "country", + "geography_id": "E92000001" + }, + "microcosm.centax_childcare_parents.london_ani_80k_to_150k": { + "geography_level": "country", + "geography_id": "E92000001" } }, "genuine_sum_residue": [ @@ -37984,6 +38004,81 @@ "resolved_fact_key": "ledger_aggregate_fact_v2_9e20bbd11c08e48d759e07de" } ] + }, + "microcosm.centax_childcare_parents.ani_50k_to_80k": { + "status": "active", + "candidates": [ + { + "name": "microcosm.centax_childcare_parents.ani_50k_to_80k", + "status": "active", + "matched_fact_count_overall": 1, + "matched_fact_count_at_or_before_period": 1, + "resolved_period": 2025, + "resolved_value": 205212.584, + "resolved_fact_period": "2025", + "resolved_fact_key": "microcosm_derived_fact_centax_childcare_parents_v1_d0a4f4a79c439e3222f10172" + } + ] + }, + "microcosm.centax_childcare_parents.ani_80k_to_120k": { + "status": "active", + "candidates": [ + { + "name": "microcosm.centax_childcare_parents.ani_80k_to_120k", + "status": "active", + "matched_fact_count_overall": 1, + "matched_fact_count_at_or_before_period": 1, + "resolved_period": 2025, + "resolved_value": 78751.175, + "resolved_fact_period": "2025", + "resolved_fact_key": "microcosm_derived_fact_centax_childcare_parents_v1_0bbe969a4232bd47960ab374" + } + ] + }, + "microcosm.centax_childcare_parents.ani_120k_to_200k": { + "status": "active", + "candidates": [ + { + "name": "microcosm.centax_childcare_parents.ani_120k_to_200k", + "status": "active", + "matched_fact_count_overall": 1, + "matched_fact_count_at_or_before_period": 1, + "resolved_period": 2025, + "resolved_value": 34514.959, + "resolved_fact_period": "2025", + "resolved_fact_key": "microcosm_derived_fact_centax_childcare_parents_v1_c230adc0ce149f0b98da6684" + } + ] + }, + "microcosm.centax_childcare_parents.female_ani_80k_to_150k": { + "status": "active", + "candidates": [ + { + "name": "microcosm.centax_childcare_parents.female_ani_80k_to_150k", + "status": "active", + "matched_fact_count_overall": 1, + "matched_fact_count_at_or_before_period": 1, + "resolved_period": 2025, + "resolved_value": 26055.201, + "resolved_fact_period": "2025", + "resolved_fact_key": "microcosm_derived_fact_centax_childcare_parents_v1_a46422479b671c651ef9950e" + } + ] + }, + "microcosm.centax_childcare_parents.london_ani_80k_to_150k": { + "status": "active", + "candidates": [ + { + "name": "microcosm.centax_childcare_parents.london_ani_80k_to_150k", + "status": "active", + "matched_fact_count_overall": 1, + "matched_fact_count_at_or_before_period": 1, + "resolved_period": 2025, + "resolved_value": 28047.888, + "resolved_fact_period": "2025", + "resolved_fact_key": "microcosm_derived_fact_centax_childcare_parents_v1_a6af4be857b390dc38982965" + } + ] } }, "fanout_family_outcomes": [ @@ -38126,6 +38221,12 @@ "rows": 5430, "rows_sha256": "65e09bc52c4719cd58bc47fc98be9204d6bf9cabd5808cbbb17703f49c732262", "inputs_sha256": "41c4f1595befe47a299aa03c803f8539e2406750ab8a312e469affdc7d4990fa" + }, + { + "resource": "centax_childcare_parent_facts.json", + "rows": 5, + "rows_sha256": "97c7b47a5667b9e262bcb0e063b38b27cdd9699c94cb498e7e88fe8f0428333e", + "inputs_sha256": "f6539c0a353ad60d95874f453b7e66e062663010255aa21b1852f1ea4c6ec860" } ] } diff --git a/packages/microcosm-build/src/microcosm/build/uk/target_references.json b/packages/microcosm-build/src/microcosm/build/uk/target_references.json index 6cb738b2a8..becc2c2b4f 100644 --- a/packages/microcosm-build/src/microcosm/build/uk/target_references.json +++ b/packages/microcosm-build/src/microcosm/build/uk/target_references.json @@ -259,6 +259,10 @@ "hmrc.benefits_in_kind": { "provider_id": "hmrc", "label": "Benefits in kind" + }, + "microcosm.centax_childcare_parents": { + "provider_id": "microcosm", + "label": "Parents of 3- and 4-year-olds by income (CenTax)" } }, "target_categories": { @@ -609,6 +613,11 @@ "mhclg.council_tax_stock.band_h": "mhclg.council_tax_stock", "mhclg.council_tax_stock.single_adult_discount": "mhclg.council_tax_stock", "mhclg.council_tax_stock.total": "mhclg.council_tax_stock", + "microcosm.centax_childcare_parents.ani_120k_to_200k": "microcosm.centax_childcare_parents", + "microcosm.centax_childcare_parents.ani_50k_to_80k": "microcosm.centax_childcare_parents", + "microcosm.centax_childcare_parents.ani_80k_to_120k": "microcosm.centax_childcare_parents", + "microcosm.centax_childcare_parents.female_ani_80k_to_150k": "microcosm.centax_childcare_parents", + "microcosm.centax_childcare_parents.london_ani_80k_to_150k": "microcosm.centax_childcare_parents", "microcosm.high_value_homes.over_1_5m_by_region": "microcosm.high_value_homes", "microcosm.high_value_homes.over_1m_by_region": "microcosm.high_value_homes", "microcosm.high_value_homes.over_2m_by_region": "microcosm.high_value_homes", @@ -1199,6 +1208,11 @@ "mhclg.council_tax_stock.band_h": "Band h", "mhclg.council_tax_stock.single_adult_discount": "Single adult discount", "mhclg.council_tax_stock.total": "Total", + "microcosm.centax_childcare_parents.ani_120k_to_200k": "Parents of age-eligible 3- and 4-year-olds, ANI over \u00a3120,000 to \u00a3200,000 (2021-22 pounds)", + "microcosm.centax_childcare_parents.ani_50k_to_80k": "Parents of age-eligible 3- and 4-year-olds, ANI over \u00a350,000 to \u00a380,000 (2021-22 pounds)", + "microcosm.centax_childcare_parents.ani_80k_to_120k": "Parents of age-eligible 3- and 4-year-olds, ANI over \u00a380,000 to \u00a3120,000 (2021-22 pounds)", + "microcosm.centax_childcare_parents.female_ani_80k_to_150k": "Parents of age-eligible 3- and 4-year-olds, women, ANI over \u00a380,000 to \u00a3150,000 (2021-22 pounds)", + "microcosm.centax_childcare_parents.london_ani_80k_to_150k": "Parents of age-eligible 3- and 4-year-olds, London, ANI over \u00a380,000 to \u00a3150,000 (2021-22 pounds)", "microcosm.high_value_homes.over_1_5m_by_region": "Owner-occupied homes valued over \u00a31.5 million by region", "microcosm.high_value_homes.over_1m_by_region": "Owner-occupied homes valued over \u00a31 million by region", "microcosm.high_value_homes.over_2m_by_region": "Owner-occupied homes valued over \u00a32 million by region", @@ -60935,6 +60949,101 @@ "period_factor": 12 } ] + }, + { + "name": "microcosm.centax_childcare_parents.ani_50k_to_80k", + "ledger_selector": { + "source_name": "microcosm", + "source_measure_id": "parents_of_eligible_3_4_year_olds", + "record_set_spec_id": "uk.centax_childcare_parents.ani_50k_to_80k.v1", + "geography_level": "country", + "geography_id": "E92000001" + }, + "entity": "person", + "measure": "microcosm/centax_childcare_parents/ani_50k_to_80k", + "family": "centax_childcare_parents", + "period": 2025, + "metadata": { + "contract_target_id": "microcosm.centax_childcare_parents.ani_50k_to_80k", + "measure_kind": "prepared_column", + "observation_basis": "fiscal_year_flow" + } + }, + { + "name": "microcosm.centax_childcare_parents.ani_80k_to_120k", + "ledger_selector": { + "source_name": "microcosm", + "source_measure_id": "parents_of_eligible_3_4_year_olds", + "record_set_spec_id": "uk.centax_childcare_parents.ani_80k_to_120k.v1", + "geography_level": "country", + "geography_id": "E92000001" + }, + "entity": "person", + "measure": "microcosm/centax_childcare_parents/ani_80k_to_120k", + "family": "centax_childcare_parents", + "period": 2025, + "metadata": { + "contract_target_id": "microcosm.centax_childcare_parents.ani_80k_to_120k", + "measure_kind": "prepared_column", + "observation_basis": "fiscal_year_flow" + } + }, + { + "name": "microcosm.centax_childcare_parents.ani_120k_to_200k", + "ledger_selector": { + "source_name": "microcosm", + "source_measure_id": "parents_of_eligible_3_4_year_olds", + "record_set_spec_id": "uk.centax_childcare_parents.ani_120k_to_200k.v1", + "geography_level": "country", + "geography_id": "E92000001" + }, + "entity": "person", + "measure": "microcosm/centax_childcare_parents/ani_120k_to_200k", + "family": "centax_childcare_parents", + "period": 2025, + "metadata": { + "contract_target_id": "microcosm.centax_childcare_parents.ani_120k_to_200k", + "measure_kind": "prepared_column", + "observation_basis": "fiscal_year_flow" + } + }, + { + "name": "microcosm.centax_childcare_parents.female_ani_80k_to_150k", + "ledger_selector": { + "source_name": "microcosm", + "source_measure_id": "parents_of_eligible_3_4_year_olds", + "record_set_spec_id": "uk.centax_childcare_parents.female_ani_80k_to_150k.v1", + "geography_level": "country", + "geography_id": "E92000001" + }, + "entity": "person", + "measure": "microcosm/centax_childcare_parents/female_ani_80k_to_150k", + "family": "centax_childcare_parents", + "period": 2025, + "metadata": { + "contract_target_id": "microcosm.centax_childcare_parents.female_ani_80k_to_150k", + "measure_kind": "prepared_column", + "observation_basis": "fiscal_year_flow" + } + }, + { + "name": "microcosm.centax_childcare_parents.london_ani_80k_to_150k", + "ledger_selector": { + "source_name": "microcosm", + "source_measure_id": "parents_of_eligible_3_4_year_olds", + "record_set_spec_id": "uk.centax_childcare_parents.london_ani_80k_to_150k.v1", + "geography_level": "country", + "geography_id": "E92000001" + }, + "entity": "person", + "measure": "microcosm/centax_childcare_parents/london_ani_80k_to_150k", + "family": "centax_childcare_parents", + "period": 2025, + "metadata": { + "contract_target_id": "microcosm.centax_childcare_parents.london_ani_80k_to_150k", + "measure_kind": "prepared_column", + "observation_basis": "fiscal_year_flow" + } } ] } diff --git a/packages/microcosm-build/src/microcosm/build/uk/uk_population_targets.json b/packages/microcosm-build/src/microcosm/build/uk/uk_population_targets.json index befe72d23c..1f092b8c73 100644 --- a/packages/microcosm-build/src/microcosm/build/uk/uk_population_targets.json +++ b/packages/microcosm-build/src/microcosm/build/uk/uk_population_targets.json @@ -1097,7 +1097,12 @@ "ons.paye_rti.pay_aged_18_to_24": "No incumbent target: uk-data binds no PAYE RTI row. ONS and HMRC's payrolled employees and their mean pay by age (PolicyEngine/chronicle#420 item 4) join as a held-out pay check (PolicyEngine/microcosm#1663).", "dwp.pip.cases_england_aged_16_to_24_daily_living_enhanced": "No incumbent target: uk-data binds no PIP row by age or award. DWP's PIP cases with entitlement by award and age (PolicyEngine/chronicle#420 item 6) join as a held-out check on the young award mix (PolicyEngine/microcosm#1663).", "dwp.pip.cases_england_aged_16_to_24_mobility_enhanced": "No incumbent target: uk-data binds no PIP row by age or award. DWP's PIP cases with entitlement by award and age (PolicyEngine/chronicle#420 item 6) join as a held-out check on the young award mix (PolicyEngine/microcosm#1663).", - "dwp.uc.people_aged_16_to_24_lcwra_element": "No incumbent target: uk-data binds no UC row by age and capability. DWP's young people with the UC health element (Young people and work: interim report, Table 28; PolicyEngine/chronicle#443) bind with part 3 of PolicyEngine/microcosm#1663." + "dwp.uc.people_aged_16_to_24_lcwra_element": "No incumbent target: uk-data binds no UC row by age and capability. DWP's young people with the UC health element (Young people and work: interim report, Table 28; PolicyEngine/chronicle#443) bind with part 3 of PolicyEngine/microcosm#1663.", + "microcosm.centax_childcare_parents.ani_50k_to_80k": "Microcosm-derived fact family (parents of age-eligible 3- and 4-year-olds in England by adjusted net income, from CenTax's HMRC tabulations; uk/centax_childcare_parent_facts.json, microcosm#1399), no uk-data metric. Bound on the national line only (calibration_lines).", + "microcosm.centax_childcare_parents.ani_80k_to_120k": "Microcosm-derived fact family (parents of age-eligible 3- and 4-year-olds in England by adjusted net income, from CenTax's HMRC tabulations; uk/centax_childcare_parent_facts.json, microcosm#1399), no uk-data metric. Bound on the national line only (calibration_lines).", + "microcosm.centax_childcare_parents.ani_120k_to_200k": "Microcosm-derived fact family (parents of age-eligible 3- and 4-year-olds in England by adjusted net income, from CenTax's HMRC tabulations; uk/centax_childcare_parent_facts.json, microcosm#1399), no uk-data metric. Bound on the national line only (calibration_lines).", + "microcosm.centax_childcare_parents.female_ani_80k_to_150k": "Microcosm-derived fact family (parents of age-eligible 3- and 4-year-olds in England by adjusted net income, from CenTax's HMRC tabulations; uk/centax_childcare_parent_facts.json, microcosm#1399), no uk-data metric. Bound on the national line only (calibration_lines).", + "microcosm.centax_childcare_parents.london_ani_80k_to_150k": "Microcosm-derived fact family (parents of age-eligible 3- and 4-year-olds in England by adjusted net income, from CenTax's HMRC tabulations; uk/centax_childcare_parent_facts.json, microcosm#1399), no uk-data metric. Bound on the national line only (calibration_lines)." }, "suppressed_ancestors": { "hmrc/salary_sacrifice_it_relief_basic_rate": { @@ -1133,7 +1138,8 @@ "ons_20_24_sex_band_split": "Y5 of the November event-data plan, approved by María on 2026-11-06 (microcosm#1095): the two national 20_24 sex bands are split into the single years 20 to 24. The bands fitted, but the light read of 6 November 2026 on the occs-df032 inspection build found the single ages inside them off ONS around the ages at which the young people and work review's measures change (21, 22 and 25). The ten rows partition the two bands and read the same ONS mid-year estimate by single year of age, so each sex's five rows sum to the band they replace. The incumbent ons/female_20_24 and ons/male_20_24 rows move from mapped to excluded: no single contract row has their definition.", "ons_single_year_ages_0_2": "microcosm#1278 (the pre-Budget PR's plan, approved by María on 2026-10-20; microcosm#1095): three all-persons rows bind ages 0, 1 and 2, read from the same ONS mid-year estimate by single year of age as the 0_4 sex bands. Unlike the 15_19 split, whose pieces replaced the bands, the 0_4 sex bands keep their incumbent mapping and stay bound: the three rows cover ages 0 to 2 for both sexes together, so neither band is their sum. The three are contract-only declarations; no incumbent row moves.", "ons_single_year_ages_0_6": "Requested by María on 2026-10-21 for the £100k childcare costing fixes (item 6; microcosm#1278, #1095). Eleven all-persons rows extend the single years of age: the UK rows go on from age 2 to age 6, and England binds ages 0 to 6 at E92000001. Every row reads the ONS mid-2025 estimate by single year of age (Population estimates for the UK, England, Wales, Scotland and Northern Ireland: mid-2025, published 1 October 2026; on the feed since the 942a1fa re-pin, microcosm#1123), the series the 0_4 and 5_9 sex bands and the region 0_9 cells sum, so the nested rows are consistent: the UK rows for ages 0 to 4 sum to the two 0_4 sex bands, and England's rows sit inside England's nine region 0_9 cells. Every band stays bound; the eleven are contract-only declarations and no incumbent row moves. Scotland's age 0 is already bound as ons.population.scotland_babies_under_1; Wales and Northern Ireland are left to the UK rows, as each nation's single year rests on too few FRS households.", - "dfe_funded_childcare_single_ages": "Requested by María on 2026-10-21 for the £100k childcare costing fixes (microcosm#1278, #1095): bind every DfE funded-childcare count the model can carry, even on few records, and sign out only those with a real reason. María's ruling of 2026-10-22 (Vahid's round-2 finding A on microcosm#1338) measures every DfE row at the spring term. DfE counts the children registered in its January census by their age on the preceding 31 December, so each row counts the children funded in the term that starts on 1 January of the model year's April-to-March span, by their age on 31 December (uk_runtime/dfe_spring_term.py). policyengine-uk 2.147.2 stops the free hours when a child starts school, from its date of birth (reception the September after the fourth birthday), and starts working parent hours the term after the minimum age; the universal and 2-year-old measures count every child of the DfE age, as the term after the birthday does, where the engine still gates them on the age on 6 October. No row reads current_education. Bound, England, January 2026 census: working parent registrations at 9 to 11 months and at ages 1, 2 and 3; universal registrations in nursery at age 3; and the three earlier rows, working parent 2 to 4, early learning for 2-year-olds and universal-only (nursery ages 3 and 4 less working parent ages 3 and 4). The under-2 rows take their own take-up: a child under 2 in a family that claims working-parent hours draws whether it uses them, at its own contract rate, as DfE registers far fewer of the youngest eligible children (parental leave) than of those aged 2 to 4. The model year is 2025, so its spring term is January 2026, the census the rows read (each declares observation_period 2026-01; microcosm#1095 D5), which retired the in-year snapshot holds that had read the January 2025 census. Signed out, each for its reason: the three age-4 cells (working parent and universal in nursery: the bound 2 to 4 and universal-only rows, less the bound ages 2 and 3, already fix them on the facts and on the measures; universal in reception: the school place meets those children's entitlement, the model funds no early-years hours for them, and who is in reception follows only the date of birth, which the survey does not record); reception at age 3 (the same reason, and DfE records a handful); the 9 months to 2 years, 3 to 4 years and Total working parent cells, the nursery and reception Totals, the early learning for 2-year-olds Total and the all-entitlements Total (sums or copies of bound cells, or sums that include a signed-out cell); the universal all-provision cells at ages 3, 4 and Total (nursery plus reception, a few children off their sum in DfE's own table); the estimated eligible children, eligible nursery children and all-children estimates (DfE builds them from population and survey-based inputs, not administrative counts, and the all-children estimates restate the ONS England single years already bound at a different reference date); and the registered percentages (ratios of a bound count to one of those estimates). The FRS records no deferred school start and no council-funded independent reception place, so the model starts every child at school on the date its date of birth implies, which slightly undercounts the 4-year-olds in nursery; DfE notes that in 2025 some 2-year-olds eligible for both entitlements were recorded under working parents rather than early learning." + "dfe_funded_childcare_single_ages": "Requested by María on 2026-10-21 for the £100k childcare costing fixes (microcosm#1278, #1095): bind every DfE funded-childcare count the model can carry, even on few records, and sign out only those with a real reason. María's ruling of 2026-10-22 (Vahid's round-2 finding A on microcosm#1338) measures every DfE row at the spring term. DfE counts the children registered in its January census by their age on the preceding 31 December, so each row counts the children funded in the term that starts on 1 January of the model year's April-to-March span, by their age on 31 December (uk_runtime/dfe_spring_term.py). policyengine-uk 2.147.2 stops the free hours when a child starts school, from its date of birth (reception the September after the fourth birthday), and starts working parent hours the term after the minimum age; the universal and 2-year-old measures count every child of the DfE age, as the term after the birthday does, where the engine still gates them on the age on 6 October. No row reads current_education. Bound, England, January 2026 census: working parent registrations at 9 to 11 months and at ages 1, 2 and 3; universal registrations in nursery at age 3; and the three earlier rows, working parent 2 to 4, early learning for 2-year-olds and universal-only (nursery ages 3 and 4 less working parent ages 3 and 4). The under-2 rows take their own take-up: a child under 2 in a family that claims working-parent hours draws whether it uses them, at its own contract rate, as DfE registers far fewer of the youngest eligible children (parental leave) than of those aged 2 to 4. The model year is 2025, so its spring term is January 2026, the census the rows read (each declares observation_period 2026-01; microcosm#1095 D5), which retired the in-year snapshot holds that had read the January 2025 census. Signed out, each for its reason: the three age-4 cells (working parent and universal in nursery: the bound 2 to 4 and universal-only rows, less the bound ages 2 and 3, already fix them on the facts and on the measures; universal in reception: the school place meets those children's entitlement, the model funds no early-years hours for them, and who is in reception follows only the date of birth, which the survey does not record); reception at age 3 (the same reason, and DfE records a handful); the 9 months to 2 years, 3 to 4 years and Total working parent cells, the nursery and reception Totals, the early learning for 2-year-olds Total and the all-entitlements Total (sums or copies of bound cells, or sums that include a signed-out cell); the universal all-provision cells at ages 3, 4 and Total (nursery plus reception, a few children off their sum in DfE's own table); the estimated eligible children, eligible nursery children and all-children estimates (DfE builds them from population and survey-based inputs, not administrative counts, and the all-children estimates restate the ONS England single years already bound at a different reference date); and the registered percentages (ratios of a bound count to one of those estimates). The FRS records no deferred school start and no council-funded independent reception place, so the model starts every child at school on the date its date of birth implies, which slightly undercounts the 4-year-olds in nursery; DfE notes that in 2025 some 2-year-olds eligible for both entitlements were recorded under working parents rather than early learning.", + "centax_childcare_parents": "Requested for the £100k childcare costing (scorecard#207, microcosm#1399): six Microcosm-derived parent cells from CenTax's HMRC tabulations of parents of age-eligible 3- and 4-year-olds in England for 2021-22 (Advani, Flew, Pepin-Hall and Summers 2026; Chronicle centax-childcare-cliff-edge-2026). Three bands partition (£50k, £200k] in 2021-22 pounds (Figure 3.1); three splits of (£80k, £150k] give the female share (3.6), the share whose main income source is not employment (3.3) and London's share (3.7, pooled 2018-19 to 2021-22, England columns). Microcosm targets are sums, so every share is a count: the share times the baseline build's parents in the aged (£50k, £200k] at 2025. Vahid's review (microcosm#1399) left the band up to £50k, which holds the adults HMRC's PAYE and Self Assessment data do not, and the two region groups outside London, whose regions the figure does not list, as diagnostics of tools/diagnose_uk_centax_parents.py, with Figure 2.1 (childcare-account shares), Figure 3.12 (non-working partners) and Table A.1's levels. CenTax's model outputs are never targets (d2014). The rows have no uk-data metric and bind on the national line only." }, "scope_target_ids": [ "obr.income_tax", @@ -1730,7 +1736,12 @@ "ons.neet.people_aged_16_to_24", "ons.paye_rti.employees_aged_0_to_17", "ons.paye_rti.employees_aged_18_to_24", - "ons.paye_rti.pay_aged_18_to_24" + "ons.paye_rti.pay_aged_18_to_24", + "microcosm.centax_childcare_parents.ani_50k_to_80k", + "microcosm.centax_childcare_parents.ani_80k_to_120k", + "microcosm.centax_childcare_parents.ani_120k_to_200k", + "microcosm.centax_childcare_parents.female_ani_80k_to_150k", + "microcosm.centax_childcare_parents.london_ani_80k_to_150k" ] }, "profile_parity": { @@ -50478,6 +50489,376 @@ } ] }, + { + "target_id": "microcosm.centax_childcare_parents.ani_50k_to_80k", + "family": "centax_childcare_parents", + "geography_levels": [ + "country" + ], + "calibration_lines": [ + "national" + ], + "measurement": { + "entity": "person", + "map_to": "household", + "concept": "uk.person.count", + "observation_basis": "fiscal_year_flow", + "filters": [ + { + "concept": "uk.childcare.centax_parent_of_eligible_3_4_year_old", + "equals": 1 + }, + { + "concept": "uk.income.adjusted_net.amount", + "operator": ">", + "value": 61686 + }, + { + "concept": "uk.income.adjusted_net.amount", + "operator": "<=", + "value": 98698 + } + ] + }, + "bindings": { + "policyengine": { + "metric_name": "microcosm/centax_childcare_parents/ani_50k_to_80k", + "value_variable": "person_count", + "from_entity": "person", + "map_to": "household", + "filters": [ + { + "variable": "centax_parent_of_eligible_3_4_year_old", + "equals": 1 + }, + { + "variable": "adjusted_net_income_annual", + "operator": ">", + "value": 61686 + }, + { + "variable": "adjusted_net_income_annual", + "operator": "<=", + "value": 98698 + } + ], + "notes": "One of the six CenTax parent cells (microcosm#1399). centax_parent_of_eligible_3_4_year_old is 1 for an adult (not an HBAI dependent child) of a benefit unit with a dependent child in England whose DfE age (the model year less birth_year, as uk_runtime/dfe_spring_term.py keys it) is 3, 4 or 5 and whose early_years_term_share_before_school exceeds a sixth: a child age-eligible for the universal hours in at least one of the year's three terms, as CenTax counts it. The DfE caseloads read the same age and term share but count the spring term only (share above a half). adjusted_net_income_annual is the year's ANI on the annual-income simulation, because HMRC's data count what each parent received in the tax year. The edges are CenTax's 2021-22 pounds aged to the calibration year by the OBR average earnings index policyengine-uk carries, rounded to whole pounds; the derived-facts loader refuses a resource whose edges differ." + }, + "axiom": { + "metric_name": "microcosm/centax_childcare_parents/ani_50k_to_80k", + "status": "pending", + "value_rule": "uk.person.count" + } + }, + "ledger_selector": { + "source_name": "microcosm", + "source_measure_id": "parents_of_eligible_3_4_year_olds", + "record_set_spec_id": "uk.centax_childcare_parents.ani_50k_to_80k.v1" + }, + "category_id": "microcosm.centax_childcare_parents", + "label": "Parents of age-eligible 3- and 4-year-olds, ANI over £50,000 to £80,000 (2021-22 pounds)", + "selector_note": "Microcosm-derived counts (uk/centax_childcare_parent_facts.json, built by tools/build_uk_centax_childcare_parent_facts.py from CenTax's data for the charts of Advani, Flew, Pepin-Hall and Summers 2026, Removing the £100,000 childcare cliff-edge, which Chronicle registers raw-only as centax-childcare-cliff-edge-2026; the builder checks the workbook's bytes against that registration). Each value is a share CenTax published from HMRC's 2021-22 tabulations (Figures 3.1, 3.3, 3.6 and 3.7) of the parents with ANI in (£50k, £200k], times the baseline build's own parents in that range aged to the calibration year, so the cells set the shape of the distribution above £50k and leave its level where the baseline put it. The range starts at £50k because CenTax counts the taxpayers HMRC's PAYE and Self Assessment data hold: a parent whose only income is savings interest or a taxable benefit has positive ANI in the model but no such record, and almost all of them sit below £50k, so a share of (0, £200k] would have scaled every cell up with them. The band up to £50k is a diagnostic (tools/diagnose_uk_centax_parents.py), not a target. The bands are wide on purpose: in 2021-22, with the cliff at £100k, the (£80k, £120k] band held both the parents who bunched below it and those they came from above it, and the FRS has too few effective households above £80k to bind narrower bins. Aged to the calibration year, though, that band and the split band start at £98,698 while the cliff stays at £100k, so a parent who bunches that year to below £98,698 leaves them for the band below. Their counts therefore assume no bunching under the frozen cliff, and lean high by about the parents who bunch below that edge: CenTax estimates 2,610 bunching parents of 3- and 4-year-olds in 2022 (p. 22). The edges are aged by average earnings because the spine's incomes are, so each cell keeps its place in the distribution. The three splits cover (£80k, £150k], the widest band every split figure covers. Its top edge was the additional-rate threshold in 2021-22, and Figures 3.3 and 3.7 show a spike in the last bin; aged to £185,059 it marks no 2025-26 threshold, while the £125,140 additional-rate threshold falls inside the band, so the band holds that bin's extra mass. London binds; the South excluding London and the North and Midlands are diagnostics, because Figure 3.7 does not list its regions and the East of England's place in the South is inferred. Figure 3.7 pools the tax years 2018-19 to 2021-22 in nominal pounds, so London's share of the band is a pooled share held for 2021-22's band. England only: CenTax tabulates England's free hours. CenTax finds parents through childcare accounts (2018-2025), PAYE parental leave (from 2014-15) and address matching of partners (pp. 12-13 and Appendix A, Figure A.1), so it misses couples with none of these, mostly self-employed or company-owning parents over £100k; the report says this understates parents above £100k relative to those below, so the upper cells may lean low. CenTax's model outputs (the bunching estimates of Tables 3.1, 3.2 and 4.1, frictions, elasticities, marginal bunchers and costs) never enter. Bound on the national line only (calibration_lines); the local line drops the rows." + }, + { + "target_id": "microcosm.centax_childcare_parents.ani_80k_to_120k", + "family": "centax_childcare_parents", + "geography_levels": [ + "country" + ], + "calibration_lines": [ + "national" + ], + "measurement": { + "entity": "person", + "map_to": "household", + "concept": "uk.person.count", + "observation_basis": "fiscal_year_flow", + "filters": [ + { + "concept": "uk.childcare.centax_parent_of_eligible_3_4_year_old", + "equals": 1 + }, + { + "concept": "uk.income.adjusted_net.amount", + "operator": ">", + "value": 98698 + }, + { + "concept": "uk.income.adjusted_net.amount", + "operator": "<=", + "value": 148048 + } + ] + }, + "bindings": { + "policyengine": { + "metric_name": "microcosm/centax_childcare_parents/ani_80k_to_120k", + "value_variable": "person_count", + "from_entity": "person", + "map_to": "household", + "filters": [ + { + "variable": "centax_parent_of_eligible_3_4_year_old", + "equals": 1 + }, + { + "variable": "adjusted_net_income_annual", + "operator": ">", + "value": 98698 + }, + { + "variable": "adjusted_net_income_annual", + "operator": "<=", + "value": 148048 + } + ], + "notes": "One of the six CenTax parent cells (microcosm#1399). centax_parent_of_eligible_3_4_year_old is 1 for an adult (not an HBAI dependent child) of a benefit unit with a dependent child in England whose DfE age (the model year less birth_year, as uk_runtime/dfe_spring_term.py keys it) is 3, 4 or 5 and whose early_years_term_share_before_school exceeds a sixth: a child age-eligible for the universal hours in at least one of the year's three terms, as CenTax counts it. The DfE caseloads read the same age and term share but count the spring term only (share above a half). adjusted_net_income_annual is the year's ANI on the annual-income simulation, because HMRC's data count what each parent received in the tax year. The edges are CenTax's 2021-22 pounds aged to the calibration year by the OBR average earnings index policyengine-uk carries, rounded to whole pounds; the derived-facts loader refuses a resource whose edges differ." + }, + "axiom": { + "metric_name": "microcosm/centax_childcare_parents/ani_80k_to_120k", + "status": "pending", + "value_rule": "uk.person.count" + } + }, + "ledger_selector": { + "source_name": "microcosm", + "source_measure_id": "parents_of_eligible_3_4_year_olds", + "record_set_spec_id": "uk.centax_childcare_parents.ani_80k_to_120k.v1" + }, + "category_id": "microcosm.centax_childcare_parents", + "label": "Parents of age-eligible 3- and 4-year-olds, ANI over £80,000 to £120,000 (2021-22 pounds)", + "selector_note": "Microcosm-derived counts (uk/centax_childcare_parent_facts.json, built by tools/build_uk_centax_childcare_parent_facts.py from CenTax's data for the charts of Advani, Flew, Pepin-Hall and Summers 2026, Removing the £100,000 childcare cliff-edge, which Chronicle registers raw-only as centax-childcare-cliff-edge-2026; the builder checks the workbook's bytes against that registration). Each value is a share CenTax published from HMRC's 2021-22 tabulations (Figures 3.1, 3.3, 3.6 and 3.7) of the parents with ANI in (£50k, £200k], times the baseline build's own parents in that range aged to the calibration year, so the cells set the shape of the distribution above £50k and leave its level where the baseline put it. The range starts at £50k because CenTax counts the taxpayers HMRC's PAYE and Self Assessment data hold: a parent whose only income is savings interest or a taxable benefit has positive ANI in the model but no such record, and almost all of them sit below £50k, so a share of (0, £200k] would have scaled every cell up with them. The band up to £50k is a diagnostic (tools/diagnose_uk_centax_parents.py), not a target. The bands are wide on purpose: in 2021-22, with the cliff at £100k, the (£80k, £120k] band held both the parents who bunched below it and those they came from above it, and the FRS has too few effective households above £80k to bind narrower bins. Aged to the calibration year, though, that band and the split band start at £98,698 while the cliff stays at £100k, so a parent who bunches that year to below £98,698 leaves them for the band below. Their counts therefore assume no bunching under the frozen cliff, and lean high by about the parents who bunch below that edge: CenTax estimates 2,610 bunching parents of 3- and 4-year-olds in 2022 (p. 22). The edges are aged by average earnings because the spine's incomes are, so each cell keeps its place in the distribution. The three splits cover (£80k, £150k], the widest band every split figure covers. Its top edge was the additional-rate threshold in 2021-22, and Figures 3.3 and 3.7 show a spike in the last bin; aged to £185,059 it marks no 2025-26 threshold, while the £125,140 additional-rate threshold falls inside the band, so the band holds that bin's extra mass. London binds; the South excluding London and the North and Midlands are diagnostics, because Figure 3.7 does not list its regions and the East of England's place in the South is inferred. Figure 3.7 pools the tax years 2018-19 to 2021-22 in nominal pounds, so London's share of the band is a pooled share held for 2021-22's band. England only: CenTax tabulates England's free hours. CenTax finds parents through childcare accounts (2018-2025), PAYE parental leave (from 2014-15) and address matching of partners (pp. 12-13 and Appendix A, Figure A.1), so it misses couples with none of these, mostly self-employed or company-owning parents over £100k; the report says this understates parents above £100k relative to those below, so the upper cells may lean low. CenTax's model outputs (the bunching estimates of Tables 3.1, 3.2 and 4.1, frictions, elasticities, marginal bunchers and costs) never enter. Bound on the national line only (calibration_lines); the local line drops the rows." + }, + { + "target_id": "microcosm.centax_childcare_parents.ani_120k_to_200k", + "family": "centax_childcare_parents", + "geography_levels": [ + "country" + ], + "calibration_lines": [ + "national" + ], + "measurement": { + "entity": "person", + "map_to": "household", + "concept": "uk.person.count", + "observation_basis": "fiscal_year_flow", + "filters": [ + { + "concept": "uk.childcare.centax_parent_of_eligible_3_4_year_old", + "equals": 1 + }, + { + "concept": "uk.income.adjusted_net.amount", + "operator": ">", + "value": 148048 + }, + { + "concept": "uk.income.adjusted_net.amount", + "operator": "<=", + "value": 246746 + } + ] + }, + "bindings": { + "policyengine": { + "metric_name": "microcosm/centax_childcare_parents/ani_120k_to_200k", + "value_variable": "person_count", + "from_entity": "person", + "map_to": "household", + "filters": [ + { + "variable": "centax_parent_of_eligible_3_4_year_old", + "equals": 1 + }, + { + "variable": "adjusted_net_income_annual", + "operator": ">", + "value": 148048 + }, + { + "variable": "adjusted_net_income_annual", + "operator": "<=", + "value": 246746 + } + ], + "notes": "One of the six CenTax parent cells (microcosm#1399). centax_parent_of_eligible_3_4_year_old is 1 for an adult (not an HBAI dependent child) of a benefit unit with a dependent child in England whose DfE age (the model year less birth_year, as uk_runtime/dfe_spring_term.py keys it) is 3, 4 or 5 and whose early_years_term_share_before_school exceeds a sixth: a child age-eligible for the universal hours in at least one of the year's three terms, as CenTax counts it. The DfE caseloads read the same age and term share but count the spring term only (share above a half). adjusted_net_income_annual is the year's ANI on the annual-income simulation, because HMRC's data count what each parent received in the tax year. The edges are CenTax's 2021-22 pounds aged to the calibration year by the OBR average earnings index policyengine-uk carries, rounded to whole pounds; the derived-facts loader refuses a resource whose edges differ." + }, + "axiom": { + "metric_name": "microcosm/centax_childcare_parents/ani_120k_to_200k", + "status": "pending", + "value_rule": "uk.person.count" + } + }, + "ledger_selector": { + "source_name": "microcosm", + "source_measure_id": "parents_of_eligible_3_4_year_olds", + "record_set_spec_id": "uk.centax_childcare_parents.ani_120k_to_200k.v1" + }, + "category_id": "microcosm.centax_childcare_parents", + "label": "Parents of age-eligible 3- and 4-year-olds, ANI over £120,000 to £200,000 (2021-22 pounds)", + "selector_note": "Microcosm-derived counts (uk/centax_childcare_parent_facts.json, built by tools/build_uk_centax_childcare_parent_facts.py from CenTax's data for the charts of Advani, Flew, Pepin-Hall and Summers 2026, Removing the £100,000 childcare cliff-edge, which Chronicle registers raw-only as centax-childcare-cliff-edge-2026; the builder checks the workbook's bytes against that registration). Each value is a share CenTax published from HMRC's 2021-22 tabulations (Figures 3.1, 3.3, 3.6 and 3.7) of the parents with ANI in (£50k, £200k], times the baseline build's own parents in that range aged to the calibration year, so the cells set the shape of the distribution above £50k and leave its level where the baseline put it. The range starts at £50k because CenTax counts the taxpayers HMRC's PAYE and Self Assessment data hold: a parent whose only income is savings interest or a taxable benefit has positive ANI in the model but no such record, and almost all of them sit below £50k, so a share of (0, £200k] would have scaled every cell up with them. The band up to £50k is a diagnostic (tools/diagnose_uk_centax_parents.py), not a target. The bands are wide on purpose: in 2021-22, with the cliff at £100k, the (£80k, £120k] band held both the parents who bunched below it and those they came from above it, and the FRS has too few effective households above £80k to bind narrower bins. Aged to the calibration year, though, that band and the split band start at £98,698 while the cliff stays at £100k, so a parent who bunches that year to below £98,698 leaves them for the band below. Their counts therefore assume no bunching under the frozen cliff, and lean high by about the parents who bunch below that edge: CenTax estimates 2,610 bunching parents of 3- and 4-year-olds in 2022 (p. 22). The edges are aged by average earnings because the spine's incomes are, so each cell keeps its place in the distribution. The three splits cover (£80k, £150k], the widest band every split figure covers. Its top edge was the additional-rate threshold in 2021-22, and Figures 3.3 and 3.7 show a spike in the last bin; aged to £185,059 it marks no 2025-26 threshold, while the £125,140 additional-rate threshold falls inside the band, so the band holds that bin's extra mass. London binds; the South excluding London and the North and Midlands are diagnostics, because Figure 3.7 does not list its regions and the East of England's place in the South is inferred. Figure 3.7 pools the tax years 2018-19 to 2021-22 in nominal pounds, so London's share of the band is a pooled share held for 2021-22's band. England only: CenTax tabulates England's free hours. CenTax finds parents through childcare accounts (2018-2025), PAYE parental leave (from 2014-15) and address matching of partners (pp. 12-13 and Appendix A, Figure A.1), so it misses couples with none of these, mostly self-employed or company-owning parents over £100k; the report says this understates parents above £100k relative to those below, so the upper cells may lean low. CenTax's model outputs (the bunching estimates of Tables 3.1, 3.2 and 4.1, frictions, elasticities, marginal bunchers and costs) never enter. Bound on the national line only (calibration_lines); the local line drops the rows." + }, + { + "target_id": "microcosm.centax_childcare_parents.female_ani_80k_to_150k", + "family": "centax_childcare_parents", + "geography_levels": [ + "country" + ], + "calibration_lines": [ + "national" + ], + "measurement": { + "entity": "person", + "map_to": "household", + "concept": "uk.person.count", + "observation_basis": "fiscal_year_flow", + "filters": [ + { + "concept": "uk.childcare.centax_parent_of_eligible_3_4_year_old", + "equals": 1 + }, + { + "concept": "uk.income.adjusted_net.amount", + "operator": ">", + "value": 98698 + }, + { + "concept": "uk.income.adjusted_net.amount", + "operator": "<=", + "value": 185059 + }, + { + "concept": "uk.demographics.gender", + "equals": "FEMALE" + } + ] + }, + "bindings": { + "policyengine": { + "metric_name": "microcosm/centax_childcare_parents/female_ani_80k_to_150k", + "value_variable": "person_count", + "from_entity": "person", + "map_to": "household", + "filters": [ + { + "variable": "centax_parent_of_eligible_3_4_year_old", + "equals": 1 + }, + { + "variable": "adjusted_net_income_annual", + "operator": ">", + "value": 98698 + }, + { + "variable": "adjusted_net_income_annual", + "operator": "<=", + "value": 185059 + }, + { + "variable": "gender", + "equals": "FEMALE" + } + ], + "notes": "One of the six CenTax parent cells (microcosm#1399). centax_parent_of_eligible_3_4_year_old is 1 for an adult (not an HBAI dependent child) of a benefit unit with a dependent child in England whose DfE age (the model year less birth_year, as uk_runtime/dfe_spring_term.py keys it) is 3, 4 or 5 and whose early_years_term_share_before_school exceeds a sixth: a child age-eligible for the universal hours in at least one of the year's three terms, as CenTax counts it. The DfE caseloads read the same age and term share but count the spring term only (share above a half). adjusted_net_income_annual is the year's ANI on the annual-income simulation, because HMRC's data count what each parent received in the tax year. The edges are CenTax's 2021-22 pounds aged to the calibration year by the OBR average earnings index policyengine-uk carries, rounded to whole pounds; the derived-facts loader refuses a resource whose edges differ." + }, + "axiom": { + "metric_name": "microcosm/centax_childcare_parents/female_ani_80k_to_150k", + "status": "pending", + "value_rule": "uk.person.count" + } + }, + "ledger_selector": { + "source_name": "microcosm", + "source_measure_id": "parents_of_eligible_3_4_year_olds", + "record_set_spec_id": "uk.centax_childcare_parents.female_ani_80k_to_150k.v1" + }, + "category_id": "microcosm.centax_childcare_parents", + "label": "Parents of age-eligible 3- and 4-year-olds, women, ANI over £80,000 to £150,000 (2021-22 pounds)", + "selector_note": "Microcosm-derived counts (uk/centax_childcare_parent_facts.json, built by tools/build_uk_centax_childcare_parent_facts.py from CenTax's data for the charts of Advani, Flew, Pepin-Hall and Summers 2026, Removing the £100,000 childcare cliff-edge, which Chronicle registers raw-only as centax-childcare-cliff-edge-2026; the builder checks the workbook's bytes against that registration). Each value is a share CenTax published from HMRC's 2021-22 tabulations (Figures 3.1, 3.3, 3.6 and 3.7) of the parents with ANI in (£50k, £200k], times the baseline build's own parents in that range aged to the calibration year, so the cells set the shape of the distribution above £50k and leave its level where the baseline put it. The range starts at £50k because CenTax counts the taxpayers HMRC's PAYE and Self Assessment data hold: a parent whose only income is savings interest or a taxable benefit has positive ANI in the model but no such record, and almost all of them sit below £50k, so a share of (0, £200k] would have scaled every cell up with them. The band up to £50k is a diagnostic (tools/diagnose_uk_centax_parents.py), not a target. The bands are wide on purpose: in 2021-22, with the cliff at £100k, the (£80k, £120k] band held both the parents who bunched below it and those they came from above it, and the FRS has too few effective households above £80k to bind narrower bins. Aged to the calibration year, though, that band and the split band start at £98,698 while the cliff stays at £100k, so a parent who bunches that year to below £98,698 leaves them for the band below. Their counts therefore assume no bunching under the frozen cliff, and lean high by about the parents who bunch below that edge: CenTax estimates 2,610 bunching parents of 3- and 4-year-olds in 2022 (p. 22). The edges are aged by average earnings because the spine's incomes are, so each cell keeps its place in the distribution. The three splits cover (£80k, £150k], the widest band every split figure covers. Its top edge was the additional-rate threshold in 2021-22, and Figures 3.3 and 3.7 show a spike in the last bin; aged to £185,059 it marks no 2025-26 threshold, while the £125,140 additional-rate threshold falls inside the band, so the band holds that bin's extra mass. London binds; the South excluding London and the North and Midlands are diagnostics, because Figure 3.7 does not list its regions and the East of England's place in the South is inferred. Figure 3.7 pools the tax years 2018-19 to 2021-22 in nominal pounds, so London's share of the band is a pooled share held for 2021-22's band. England only: CenTax tabulates England's free hours. CenTax finds parents through childcare accounts (2018-2025), PAYE parental leave (from 2014-15) and address matching of partners (pp. 12-13 and Appendix A, Figure A.1), so it misses couples with none of these, mostly self-employed or company-owning parents over £100k; the report says this understates parents above £100k relative to those below, so the upper cells may lean low. CenTax's model outputs (the bunching estimates of Tables 3.1, 3.2 and 4.1, frictions, elasticities, marginal bunchers and costs) never enter. Bound on the national line only (calibration_lines); the local line drops the rows." + }, + { + "target_id": "microcosm.centax_childcare_parents.london_ani_80k_to_150k", + "family": "centax_childcare_parents", + "geography_levels": [ + "country" + ], + "calibration_lines": [ + "national" + ], + "measurement": { + "entity": "person", + "map_to": "household", + "concept": "uk.person.count", + "observation_basis": "fiscal_year_flow", + "filters": [ + { + "concept": "uk.childcare.centax_parent_of_eligible_3_4_year_old", + "equals": 1 + }, + { + "concept": "uk.income.adjusted_net.amount", + "operator": ">", + "value": 98698 + }, + { + "concept": "uk.income.adjusted_net.amount", + "operator": "<=", + "value": 185059 + }, + { + "concept": "uk.geography.region", + "in": [ + "LONDON" + ] + } + ] + }, + "bindings": { + "policyengine": { + "metric_name": "microcosm/centax_childcare_parents/london_ani_80k_to_150k", + "value_variable": "person_count", + "from_entity": "person", + "map_to": "household", + "filters": [ + { + "variable": "centax_parent_of_eligible_3_4_year_old", + "equals": 1 + }, + { + "variable": "adjusted_net_income_annual", + "operator": ">", + "value": 98698 + }, + { + "variable": "adjusted_net_income_annual", + "operator": "<=", + "value": 185059 + }, + { + "variable": "region", + "in": [ + "LONDON" + ] + } + ], + "notes": "One of the six CenTax parent cells (microcosm#1399). centax_parent_of_eligible_3_4_year_old is 1 for an adult (not an HBAI dependent child) of a benefit unit with a dependent child in England whose DfE age (the model year less birth_year, as uk_runtime/dfe_spring_term.py keys it) is 3, 4 or 5 and whose early_years_term_share_before_school exceeds a sixth: a child age-eligible for the universal hours in at least one of the year's three terms, as CenTax counts it. The DfE caseloads read the same age and term share but count the spring term only (share above a half). adjusted_net_income_annual is the year's ANI on the annual-income simulation, because HMRC's data count what each parent received in the tax year. The edges are CenTax's 2021-22 pounds aged to the calibration year by the OBR average earnings index policyengine-uk carries, rounded to whole pounds; the derived-facts loader refuses a resource whose edges differ." + }, + "axiom": { + "metric_name": "microcosm/centax_childcare_parents/london_ani_80k_to_150k", + "status": "pending", + "value_rule": "uk.person.count" + } + }, + "ledger_selector": { + "source_name": "microcosm", + "source_measure_id": "parents_of_eligible_3_4_year_olds", + "record_set_spec_id": "uk.centax_childcare_parents.london_ani_80k_to_150k.v1" + }, + "category_id": "microcosm.centax_childcare_parents", + "label": "Parents of age-eligible 3- and 4-year-olds, London, ANI over £80,000 to £150,000 (2021-22 pounds)", + "selector_note": "Microcosm-derived counts (uk/centax_childcare_parent_facts.json, built by tools/build_uk_centax_childcare_parent_facts.py from CenTax's data for the charts of Advani, Flew, Pepin-Hall and Summers 2026, Removing the £100,000 childcare cliff-edge, which Chronicle registers raw-only as centax-childcare-cliff-edge-2026; the builder checks the workbook's bytes against that registration). Each value is a share CenTax published from HMRC's 2021-22 tabulations (Figures 3.1, 3.3, 3.6 and 3.7) of the parents with ANI in (£50k, £200k], times the baseline build's own parents in that range aged to the calibration year, so the cells set the shape of the distribution above £50k and leave its level where the baseline put it. The range starts at £50k because CenTax counts the taxpayers HMRC's PAYE and Self Assessment data hold: a parent whose only income is savings interest or a taxable benefit has positive ANI in the model but no such record, and almost all of them sit below £50k, so a share of (0, £200k] would have scaled every cell up with them. The band up to £50k is a diagnostic (tools/diagnose_uk_centax_parents.py), not a target. The bands are wide on purpose: in 2021-22, with the cliff at £100k, the (£80k, £120k] band held both the parents who bunched below it and those they came from above it, and the FRS has too few effective households above £80k to bind narrower bins. Aged to the calibration year, though, that band and the split band start at £98,698 while the cliff stays at £100k, so a parent who bunches that year to below £98,698 leaves them for the band below. Their counts therefore assume no bunching under the frozen cliff, and lean high by about the parents who bunch below that edge: CenTax estimates 2,610 bunching parents of 3- and 4-year-olds in 2022 (p. 22). The edges are aged by average earnings because the spine's incomes are, so each cell keeps its place in the distribution. The three splits cover (£80k, £150k], the widest band every split figure covers. Its top edge was the additional-rate threshold in 2021-22, and Figures 3.3 and 3.7 show a spike in the last bin; aged to £185,059 it marks no 2025-26 threshold, while the £125,140 additional-rate threshold falls inside the band, so the band holds that bin's extra mass. London binds; the South excluding London and the North and Midlands are diagnostics, because Figure 3.7 does not list its regions and the East of England's place in the South is inferred. Figure 3.7 pools the tax years 2018-19 to 2021-22 in nominal pounds, so London's share of the band is a pooled share held for 2021-22's band. England only: CenTax tabulates England's free hours. CenTax finds parents through childcare accounts (2018-2025), PAYE parental leave (from 2014-15) and address matching of partners (pp. 12-13 and Appendix A, Figure A.1), so it misses couples with none of these, mostly self-employed or company-owning parents over £100k; the report says this understates parents above £100k relative to those below, so the upper cells may lean low. CenTax's model outputs (the bunching estimates of Tables 3.1, 3.2 and 4.1, frictions, elasticities, marginal bunchers and costs) never enter. Bound on the national line only (calibration_lines); the local line drops the rows." + }, { "target_id": "hmrc.self_employment_income.amount", "family": "hmrc", @@ -54887,6 +55268,10 @@ "hmrc.benefits_in_kind": { "provider_id": "hmrc", "label": "Benefits in kind" + }, + "microcosm.centax_childcare_parents": { + "provider_id": "microcosm", + "label": "Parents of 3- and 4-year-olds by income (CenTax)" } } } diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/centax_childcare_parents.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/centax_childcare_parents.py new file mode 100644 index 0000000000..13099a8420 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/centax_childcare_parents.py @@ -0,0 +1,699 @@ +"""CenTax's HMRC tabulations of parents of 3- and 4-year-olds, as derived facts. + +Advani, Flew, Pepin-Hall and Summers (CenTax, September 2026), *Removing the +£100,000 childcare cliff-edge*, tabulate HMRC's administrative data for tax +year 2021-22 (their "2022"): the adjusted net income (ANI) of every identified +parent in England with a child age-eligible for the free hours in at least +one term of the year (Figure 3.1), split by main source of income (3.3), sex +(3.6) and region (3.7, pooled 2018-19 to 2021-22). Their data for the charts +is registered raw-only in Chronicle as ``centax-childcare-cliff-edge-2026``; +``tools/build_uk_centax_childcare_parent_facts.py`` checks the workbook's bytes +against that registration and writes the committed resource +``uk/centax_childcare_parent_facts.json``: five counts at England grain. + +- Three ANI bands, (£50k, £80k], (£80k, £120k] and (£120k, £200k] in 2021-22 + pounds, each Figure 3.1's share of the parents in (£50k, £200k]. +- Two splits of the parents in (£80k, £150k], the widest band every split + figure covers: female (3.6) and London (3.7). + +Microcosm targets are sums, so each share becomes a count: the share times +``parent_count``, the baseline build's own parents with ANI in the aged +(£50k, £200k] at the calibration year. The targets set the shape of the +distribution above £50k and leave its level where the baseline put it. + +Three cells of the first design are diagnostics, reported by +``tools/diagnose_uk_centax_parents.py`` and never bound (Vahid's reviews of +microcosm#1399): + +- ANI up to £50k. CenTax counts taxpayers that HMRC's PAYE and Self Assessment + data hold. A model adult whose only income is savings interest or a taxable + benefit has positive ANI but no such record, and almost all of them sit in + that band, so a share of (0, £200k] times the model's count of it would + scale every cell up with them. Above £50k a parent is in HMRC's data. +- The South excluding London and the North and Midlands. Figure 3.7 does not + list its regions; the East of England's place in the South is inferred + (``CENTAX_REGION_GROUP_CODES``). London binds; the diagnostic reports the + other two groups under both placements of the East. +- Main source other than employment (Figure 3.3). The cell rests on fewer than + 3 FRS source households, too few to bind (María's ruling of 24 November + 2026). + +Only the published tabulations are used. CenTax's model outputs (bunching +estimates, frictions, elasticities, marginal bunchers, costs) never enter the +resource, and neither do the figures kept as diagnostics (Table A.1's levels, +Figure 3.12's non-working partners): the diagnostic reads those from the +registered workbook. + +The band edges are in 2021-22 pounds. The contract filters age them to the +calibration year by the OBR average earnings index policyengine-uk carries +(``ani_uprating``), rounded to whole pounds, and the loader refuses a contract +whose edges differ. ANI is the year's annual concept +(``adjusted_net_income_annual``): HMRC's data count what each parent received +in the tax year. + +This module is the one place that knows the resource's shape and the two +measures the cells read: ``centax_parent_of_eligible_3_4_year_old`` (an +adult in a benefit unit with such a child, as policyengine-uk dates its +terms) and ``centax_employment_main_income_source`` (employment is the +largest income source in the year), which only the diagnostic's +non-employee cell reads. +""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from functools import cache +from importlib import resources +from pathlib import Path +from types import MappingProxyType +from typing import Any + +import numpy as np + +from microcosm.calibrate.geography_constants import UK_REGION_TIER_ENUM + +__all__ = [ + "CENTAX_ANI_BANDS_2022", + "CENTAX_ANI_MEASURE", + "CENTAX_BOUND_REGION_GROUPS", + "CENTAX_CHRONICLE_PACKAGE_ID", + "CENTAX_CHRONICLE_SOURCE_ID", + "CENTAX_DATA_ENGINE_YEAR", + "CENTAX_DATA_TAX_YEAR", + "CENTAX_DERIVED_FACT_KEY_PREFIX", + "CENTAX_DIAGNOSTIC_BAND_2022", + "CENTAX_DIAGNOSTIC_SPLITS", + "CENTAX_EAST_OF_ENGLAND", + "CENTAX_ELIGIBLE_DFE_AGES", + "CENTAX_EMPLOYEE_MAIN_SOURCE", + "CENTAX_EMPLOYEE_SOURCE_COMPONENTS", + "CENTAX_EMPLOYEE_SOURCE_ENGINE_NAMES", + "CENTAX_EMPLOYEE_SOURCE_INPUTS", + "CENTAX_FACTS_RESOURCE", + "CENTAX_FILTER_CONCEPTS", + "CENTAX_PARENT_ENGINE_INPUTS", + "CENTAX_PARENT_MEASURES", + "CENTAX_PARENT_OF_ELIGIBLE_3_4", + "CENTAX_REGION_GROUPS", + "CENTAX_REGION_GROUP_CODES", + "CENTAX_REPORT_URL", + "CENTAX_SHARE_BASE_2022", + "CENTAX_SPLIT_BAND_2022", + "CENTAX_SPLITS", + "CENTAX_WORKBOOK_FILENAME", + "CENTAX_WORKBOOK_SHA256", + "RESOURCE_SCHEMA_VERSION", + "UKCenTaxChildcareParentFacts", + "aged_edges", + "centax_ani_uprating", + "centax_cell_filters", + "centax_cell_ids", + "centax_cell_measurement_filters", + "centax_diagnostic_cell_ids", + "centax_region_codes", + "employment_main_income_source", + "load_uk_centax_childcare_parent_facts", + "model_ani_edges", + "parent_of_eligible_3_4_year_old", + "rows_sha256", + "uk_centax_childcare_parent_facts", +] + +CENTAX_FACTS_RESOURCE = "centax_childcare_parent_facts.json" +CENTAX_DERIVED_FACT_KEY_PREFIX = "microcosm.derived_fact.centax_childcare_parents.v1:" +RESOURCE_KIND = "uk_derived_consumer_facts" +#: Schema 2 (microcosm#1399's review): the shares are taken within the share +#: base, the workbook is named by its Chronicle registration, and the +#: diagnostics-only figures left the resource. +RESOURCE_SCHEMA_VERSION = 2 +ROW_SCHEMA_VERSION = "microcosm.derived_consumer_fact.v1" +#: The Chronicle registration of CenTax's data for the charts (raw only). +CENTAX_CHRONICLE_SOURCE_ID = "centax" +CENTAX_CHRONICLE_PACKAGE_ID = "centax-childcare-cliff-edge-2026" +CENTAX_WORKBOOK_FILENAME = "AdvaniFlewPepinhallSummers2026_ChildcareThreshold_data.xlsx" +#: The workbook's bytes, as the registration pins them (the copy CenTax shared +#: on 21 October 2026 and the one arunadvani.com publishes are the same). +CENTAX_WORKBOOK_SHA256 = ( + "8c23855745154a601064e766552c64bc2e88de51e043b4df1397c580e969354b" +) +CENTAX_REPORT_URL = ( + "https://centax.org.uk/wp-content/uploads/2026/09/" + "AdvaniFlewPepin-HallSummers2026_Removing-the-childcare-cliff-edge.pdf" +) +#: Tax year of the HMRC data behind Figures 3.1, 3.3 and 3.6; policyengine-uk +#: dates it 2021, the year the tax year starts in. +CENTAX_DATA_TAX_YEAR = "2021-22" +CENTAX_DATA_ENGINE_YEAR = 2021 + +#: The 2021-22 ANI range the shares are taken within, lower edge exclusive. +#: Above £50k a parent is in HMRC's PAYE or Self Assessment data, so the +#: model's parents there are the ones CenTax can count (see the module notes). +CENTAX_SHARE_BASE_2022 = (50_000.0, 200_000.0) +#: The bound ANI bands in 2021-22 pounds, lower edge exclusive and upper edge +#: inclusive, as the workbook's bins are labelled by their upper edge. They +#: partition the share base. Wide around £100k on purpose (see the contract's +#: selector notes). +CENTAX_ANI_BANDS_2022: tuple[tuple[str, float, float], ...] = ( + ("ani_50k_to_80k", 50_000.0, 80_000.0), + ("ani_80k_to_120k", 80_000.0, 120_000.0), + ("ani_120k_to_200k", 120_000.0, 200_000.0), +) +#: The band below the share base: a diagnostic, never a target. +CENTAX_DIAGNOSTIC_BAND_2022 = ("ani_0_to_50k", 0.0, 50_000.0) +#: The band every split figure covers (Figures 3.3, 3.6 and 3.7 stop at £150k). +CENTAX_SPLIT_BAND_2022 = (80_000.0, 150_000.0) +#: Region groups of Figure 3.7, by English region GSS code. The figure does +#: not list its regions; the East of England sits in the South because only +#: then do the figure's low-income shares match the ONS child-population shares +#: of the three groups. That placement is inferred, so only London binds. +CENTAX_REGION_GROUP_CODES: Mapping[str, tuple[str, ...]] = MappingProxyType( + { + "london": ("E12000007",), + "south_excl_london": ("E12000006", "E12000008", "E12000009"), + "north_and_midlands": ( + "E12000001", + "E12000002", + "E12000003", + "E12000004", + "E12000005", + ), + } +) +#: The region whose group the figure leaves open. +CENTAX_EAST_OF_ENGLAND = "E12000006" +#: The same groups by the spine's ``region`` enum name, the value the +#: contract filters compare against. +CENTAX_REGION_GROUPS: Mapping[str, tuple[str, ...]] = MappingProxyType( + { + group: tuple(UK_REGION_TIER_ENUM[code] for code in codes) + for group, codes in CENTAX_REGION_GROUP_CODES.items() + } +) +#: The region groups the targets bind: London, the one group the figure names +#: without doubt (Vahid's review, item 3). +CENTAX_BOUND_REGION_GROUPS: tuple[str, ...] = ("london",) +#: The split cells the targets bind, each with the workbook figure it reads. +CENTAX_SPLITS: tuple[tuple[str, str], ...] = ( + ("female", "Fig. 3.6"), + ("london", "Fig. 3.7"), +) +#: The split the diagnostic reports and the targets never bind: its cell rests +#: on fewer than 3 FRS source households (María's ruling of 24 November 2026). +CENTAX_DIAGNOSTIC_SPLITS: tuple[tuple[str, str], ...] = (("non_employee", "Fig. 3.3"),) + +CENTAX_PARENT_OF_ELIGIBLE_3_4 = "centax_parent_of_eligible_3_4_year_old" +CENTAX_EMPLOYEE_MAIN_SOURCE = "centax_employment_main_income_source" +CENTAX_PARENT_MEASURES = (CENTAX_PARENT_OF_ELIGIBLE_3_4, CENTAX_EMPLOYEE_MAIN_SOURCE) +#: Engine variables the parent measure reads at person grain. The spine sets +#: ``is_hbai_dependent_child`` for the FRS child-table members of each benefit +#: unit, so the others are its adults, the claimant and any partner; SPI +#: cloning keeps the roles. +CENTAX_PARENT_ENGINE_INPUTS = ( + "birth_year", + "country", + "early_years_term_share_before_school", + "is_hbai_dependent_child", +) +#: Each component of the engine's adjusted net income +#: (``gov.hmrc.income_tax.adjusted_net_income_components``, the sources ITA +#: 2007 s. 23 totals) and the sources the main-source measure compares for it: +#: the social security income benefit by benefit, and savings interest apart +#: from other investment income. Employment is pay plus the company car and +#: car fuel benefits, which HMRC's employment income counts and +#: policyengine-uk keeps apart from pay since 2.165.0, as the HMRC rows on +#: employment income read it (PolicyEngine/uk-autumn-budget-dashboard-2026#316). +CENTAX_EMPLOYEE_SOURCE_COMPONENTS: Mapping[str, tuple[str, ...]] = MappingProxyType( + { + "taxable_employment_income": ( + "employment_income_with_benefits_in_kind_annual", + ), + "taxable_self_employment_income": ( + "self_employment_income_after_loss_relief_annual", + ), + "taxable_pension_income": ("private_pension_income_annual",), + "taxable_social_security_income": ( + "state_pension_annual", + "incapacity_benefit", + "jsa_contrib_reported", + "esa_contrib_reported", + "carers_allowance", + "carer_support_payment", + "scottish_carer_supplement", + "widowed_parents_allowance", + ), + "taxable_property_income": ("property_income",), + "taxable_savings_interest_income": ( + "savings_interest_income", + "other_investment_income", + ), + "taxable_dividend_income": ("dividend_income",), + "taxable_miscellaneous_income": ("taxable_miscellaneous_income",), + } +) +#: The year's income sources the main-source measure compares, employment +#: first. The first four are the annual measures. The investment, property and +#: miscellaneous incomes are annual amounts already. The taxable benefits other +#: than the State Pension are read as the engine computes them for the year. +CENTAX_EMPLOYEE_SOURCE_INPUTS: tuple[str, ...] = tuple( + name for sources in CENTAX_EMPLOYEE_SOURCE_COMPONENTS.values() for name in sources +) +#: The engine variable each compared social security source stands for, +#: where the name differs: the State Pension's annual measure. +CENTAX_EMPLOYEE_SOURCE_ENGINE_NAMES: Mapping[str, str] = MappingProxyType( + {"state_pension_annual": "state_pension"} +) +#: DfE ages (``Y - birth_year``, the age on 31 December of model year Y) of a +#: child age-eligible for the universal hours in at least one of the year's +#: terms (1 April, 1 September, 1 January). The hours start the term after the +#: third birthday, so a DfE age 2 child is never eligible before April Y + 1; +#: every DfE age 3 and 4 child is; a DfE age 5 child is only while it has not +#: started school, which ``early_years_term_share_before_school`` dates. +CENTAX_ELIGIBLE_DFE_AGES = (3, 4, 5) +#: ``early_years_term_share_before_school`` is 0, 1/3 or 1 in float32, so it +#: is tested against a sixth, never for equality. +_TERM_SHARE_FLOOR = 1.0 / 6.0 +_ENGLAND_GSS = "E92000001" + + +def parent_of_eligible_3_4_year_old( + *, + birth_year: np.ndarray, + country: np.ndarray, + term_share_before_school: np.ndarray, + dependent_child: np.ndarray, + benunit_id: np.ndarray, + year: int, +) -> np.ndarray: + """One for an adult whose benefit unit has an eligible child in England. + + A child is eligible when it is a dependent child of its benefit unit in + England, its DfE age is 3, 4 or 5 and it is before school in at least one + of the year's terms. The parent is any adult of the child's benefit unit, + the FRS's family: CenTax's identified parents and partners. Every array + is at person grain. + """ + + dfe_age = float(year) - np.asarray(birth_year, dtype=float) + child = np.asarray(dependent_child).astype(bool) + eligible = ( + child + & (np.asarray(country).astype(str) == "ENGLAND") + & np.isin(dfe_age, CENTAX_ELIGIBLE_DFE_AGES) + & (np.asarray(term_share_before_school, dtype=float) > _TERM_SHARE_FLOOR) + ) + units = np.asarray(benunit_id) + with_child = np.isin(units, units[eligible]) + return (with_child & ~child).astype(float) + + +def employment_main_income_source(sources: Mapping[str, np.ndarray]) -> np.ndarray: + """One where employment income is positive and at least every other source. + + ``sources`` maps each name in ``CENTAX_EMPLOYEE_SOURCE_INPUTS`` to a person + array. CenTax's employees are taxpayers whose main source of income is + employment (Figure 3.3's notes). The report does not say whether that is + the largest single source or more than half of income; this reads the + largest single source, and a tie goes to employment. + """ + + missing = [name for name in CENTAX_EMPLOYEE_SOURCE_INPUTS if name not in sources] + if missing: + raise ValueError(f"the main-source measure needs {missing}.") + employment = np.asarray(sources[CENTAX_EMPLOYEE_SOURCE_INPUTS[0]], dtype=float) + others = np.vstack( + [ + np.asarray(sources[name], dtype=float) + for name in CENTAX_EMPLOYEE_SOURCE_INPUTS[1:] + ] + ) + return ((employment > 0) & (employment >= others.max(axis=0))).astype(float) + + +def centax_ani_uprating(calibration_year: int) -> float: + """The OBR average earnings index at ``calibration_year`` over 2021. + + Read from the installed policyengine-uk, which carries the index the + engine uprates earnings by; 2021 is the engine's year of tax year 2021-22. + """ + + from policyengine_uk import CountryTaxBenefitSystem + + index = CountryTaxBenefitSystem().parameters.gov.economic_assumptions.indices.obr.average_earnings + return float(index(f"{int(calibration_year)}-01-01")) / float( + index(f"{CENTAX_DATA_ENGINE_YEAR}-01-01") + ) + + +def centax_cell_ids() -> tuple[str, ...]: + """Every bound cell of the resource: the three bands, then the bound splits.""" + + return tuple(band for band, _, _ in CENTAX_ANI_BANDS_2022) + tuple( + f"{split}_ani_80k_to_150k" for split, _ in CENTAX_SPLITS + ) + + +def centax_diagnostic_cell_ids() -> tuple[str, ...]: + """The split cells the diagnostic reports and the targets never bind.""" + + return tuple(f"{split}_ani_80k_to_150k" for split, _ in CENTAX_DIAGNOSTIC_SPLITS) + + +def centax_region_codes( + *, east_in: str = "south_excl_london" +) -> dict[str, tuple[str, ...]]: + """Figure 3.7's region groups with the East of England in ``east_in``. + + ``south_excl_london`` is the inferred placement the module binds against; + ``north_and_midlands`` is the other one, which the diagnostic also reports. + London never moves. + """ + + if east_in not in {"south_excl_london", "north_and_midlands"}: + raise ValueError(f"the East of England cannot sit in {east_in!r}.") + groups = { + group: tuple(code for code in codes if code != CENTAX_EAST_OF_ENGLAND) + for group, codes in CENTAX_REGION_GROUP_CODES.items() + } + groups[east_in] = tuple(sorted((*groups[east_in], CENTAX_EAST_OF_ENGLAND))) + return groups + + +#: The annual ANI measure every cell bands on. +CENTAX_ANI_MEASURE = "adjusted_net_income_annual" +#: Each split's extra predicate, in the contract's binding filter vocabulary. +_SPLIT_FILTERS: Mapping[str, Mapping[str, Any]] = MappingProxyType( + { + "female": {"variable": "gender", "equals": "FEMALE"}, + "non_employee": {"variable": CENTAX_EMPLOYEE_MAIN_SOURCE, "equals": 0}, + **{ + group: {"variable": "region", "in": list(CENTAX_REGION_GROUPS[group])} + for group in CENTAX_BOUND_REGION_GROUPS + }, + } +) + + +def centax_cell_filters(cell_id: str, edges: Sequence[int]) -> list[dict[str, Any]]: + """The policyengine binding filters of a cell at its model ANI edges. + + The parent flag, then ANI above the lower edge and at most the upper one, + then the split's own predicate. The contract carries exactly these, which + the tests check. + """ + + lower, upper = (int(edge) for edge in edges) + filters: list[dict[str, Any]] = [ + {"variable": CENTAX_PARENT_OF_ELIGIBLE_3_4, "equals": 1}, + {"variable": CENTAX_ANI_MEASURE, "operator": ">", "value": lower}, + {"variable": CENTAX_ANI_MEASURE, "operator": "<=", "value": upper}, + ] + split = cell_id.removesuffix("_ani_80k_to_150k") + if split != cell_id: + filters.append(dict(_SPLIT_FILTERS[split])) + elif cell_id not in {band for band, _, _ in CENTAX_ANI_BANDS_2022}: + raise KeyError(cell_id) + return filters + + +#: The contract's measurement concept for each variable a cell filters on. +CENTAX_FILTER_CONCEPTS: Mapping[str, str] = MappingProxyType( + { + CENTAX_PARENT_OF_ELIGIBLE_3_4: ( + "uk.childcare.centax_parent_of_eligible_3_4_year_old" + ), + CENTAX_ANI_MEASURE: "uk.income.adjusted_net.amount", + CENTAX_EMPLOYEE_MAIN_SOURCE: "uk.income.employment.main_source", + "gender": "uk.demographics.gender", + "region": "uk.geography.region", + } +) + + +def centax_cell_measurement_filters( + cell_id: str, edges: Sequence[int] +) -> list[dict[str, Any]]: + """The cell's filters in the contract's measurement (concept) vocabulary.""" + + filters = [] + for predicate in centax_cell_filters(cell_id, edges): + concept = dict(predicate) + concept = { + "concept": CENTAX_FILTER_CONCEPTS[concept.pop("variable")], + **concept, + } + filters.append(concept) + return filters + + +@dataclass(frozen=True) +class UKCenTaxChildcareParentFacts: + """The validated derived-facts resource.""" + + rows: tuple[Mapping[str, Any], ...] + rows_sha256: str + inputs_sha256: str + parameters: Mapping[str, Any] + inputs: Mapping[str, Any] + generator: Mapping[str, Any] + shares: Mapping[str, float] + + @property + def ani_uprating(self) -> float: + return float(self.parameters["ani_uprating"]) + + @property + def parent_count(self) -> float: + return float(self.parameters["parent_count"]) + + @property + def baseline(self) -> Mapping[str, Any]: + """The national build the parent count was read off.""" + + return self.inputs["baseline"] + + def model_edges(self, cell_id: str) -> tuple[int, int]: + """A cell's ANI edges at the calibration year, in whole pounds.""" + + return tuple(self.parameters["model_ani_edges"][cell_id]) # type: ignore[return-value] + + def value(self, cell_id: str) -> float: + for row in self.rows: + if row["dimensions"]["microcosm.centax_cell"] == cell_id: + return float(row["value"]) + raise KeyError(cell_id) + + +def _package_text(name: str) -> str: + return ( + resources.files("microcosm.build.uk").joinpath(name).read_text(encoding="utf-8") + ) + + +def rows_sha256(rows: Sequence[Mapping[str, Any]]) -> str: + """Digest of the rows, independent of their order.""" + + digest = hashlib.sha256() + for line in sorted( + json.dumps(row, sort_keys=True, separators=(",", ":"), ensure_ascii=True) + for row in rows + ): + digest.update(line.encode("utf-8")) + digest.update(b"\n") + return digest.hexdigest() + + +def aged_edges(lower: float, upper: float, uprating: float) -> list[int]: + """A 2021-22 band's edges aged by ``uprating``, rounded to whole pounds.""" + + return [round(lower * uprating), round(upper * uprating)] + + +def model_ani_edges(uprating: float) -> dict[str, list[int]]: + """Each bound cell's 2021-22 edges aged by ``uprating``.""" + + edges: dict[str, list[int]] = {} + for band, lower, upper in CENTAX_ANI_BANDS_2022: + edges[band] = aged_edges(lower, upper, uprating) + for split, _ in CENTAX_SPLITS: + edges[f"{split}_ani_80k_to_150k"] = aged_edges( + *CENTAX_SPLIT_BAND_2022, uprating + ) + return edges + + +def _validate_row(row: Mapping[str, Any]) -> str: + key = str(row.get("aggregate_fact_key") or "") + if not key.startswith(CENTAX_DERIVED_FACT_KEY_PREFIX): + raise ValueError(f"CenTax fact {key!r} is outside the derived-fact namespace.") + if row.get("schema_version") != ROW_SCHEMA_VERSION: + raise ValueError( + f"CenTax fact {key!r} has schema {row.get('schema_version')!r}." + ) + geography = row.get("geography") or {} + if geography.get("level") != "country" or geography.get("id") != _ENGLAND_GSS: + raise ValueError(f"CenTax fact {key!r} must sit at England (country) grain.") + value = row.get("value") + if ( + not isinstance(value, (int, float)) + or isinstance(value, bool) + or not np.isfinite(value) + or value <= 0 + ): + raise ValueError(f"CenTax fact {key!r} has invalid value {value!r}.") + if (row.get("aggregation") or {}).get("method") != "sum": + raise ValueError(f"CenTax fact {key!r} must aggregate by sum.") + if (row.get("source") or {}).get("source_name") != "microcosm": + raise ValueError(f"CenTax fact {key!r} must name source microcosm.") + cell = str((row.get("dimensions") or {}).get("microcosm.centax_cell") or "") + if cell not in centax_cell_ids(): + raise ValueError(f"CenTax fact {key!r} names an unknown cell {cell!r}.") + spec = str((row.get("layout") or {}).get("record_set_spec_id") or "") + if spec != f"uk.centax_childcare_parents.{cell}.v1": + raise ValueError(f"CenTax fact {key!r} has record set spec {spec!r}.") + if not str(row.get("label") or "").strip(): + raise ValueError(f"CenTax fact {key!r} requires a label.") + return cell + + +def _validate_registration(workbook: Mapping[str, Any]) -> None: + """The workbook must be the one Chronicle registers, with its pinned bytes.""" + + if workbook.get("chronicle_package_id") != CENTAX_CHRONICLE_PACKAGE_ID or ( + workbook.get("chronicle_source_id") != CENTAX_CHRONICLE_SOURCE_ID + ): + raise ValueError( + f"{CENTAX_FACTS_RESOURCE} must name the Chronicle registration " + f"{CENTAX_CHRONICLE_PACKAGE_ID}." + ) + if workbook.get("registration_kind") != "raw_only": + raise ValueError(f"{CENTAX_CHRONICLE_PACKAGE_ID} is a raw-only registration.") + files = list((workbook.get("files") or {}).values()) + if ( + len(files) != 1 + or files[0].get("filename") != CENTAX_WORKBOOK_FILENAME + or files[0].get("sha256") != CENTAX_WORKBOOK_SHA256 + ): + raise ValueError( + f"{CENTAX_FACTS_RESOURCE} was not built from the pinned CenTax workbook." + ) + + +def load_uk_centax_childcare_parent_facts( + path: Path | None = None, +) -> UKCenTaxChildcareParentFacts: + """Load and validate the derived-facts resource. + + Refused when the rows differ from their digest, the workbook is not the + one Chronicle registers with the pinned bytes, a cell is missing or + repeated, a share falls outside (0, 1), the bands' shares do not sum to + one or a split's exceeds the split band's, a value is not its share times + the parent count, or the recorded edges are not the 2021-22 edges aged by + the recorded uprating. + """ + + text = ( + path.read_text(encoding="utf-8") + if path is not None + else _package_text(CENTAX_FACTS_RESOURCE) + ) + payload = json.loads(text) + if ( + payload.get("kind") != RESOURCE_KIND + or payload.get("schema_version") != RESOURCE_SCHEMA_VERSION + ): + raise ValueError( + f"{CENTAX_FACTS_RESOURCE} is not a schema-{RESOURCE_SCHEMA_VERSION} " + "derived-facts resource." + ) + rows = payload.get("rows") + if not isinstance(rows, list) or not rows: + raise ValueError(f"{CENTAX_FACTS_RESOURCE} carries no rows.") + if payload.get("row_count") != len(rows): + raise ValueError(f"{CENTAX_FACTS_RESOURCE} row_count disagrees with its rows.") + digest = rows_sha256(rows) + if digest != payload.get("rows_sha256"): + raise ValueError(f"{CENTAX_FACTS_RESOURCE} rows differ from their digest.") + inputs = payload.get("inputs") or {} + _validate_registration(inputs.get("workbook") or {}) + baseline = inputs.get("baseline") or {} + if not baseline.get("dataset") or len(str(baseline.get("sha256") or "")) != 64: + raise ValueError(f"{CENTAX_FACTS_RESOURCE} must name its baseline build.") + parameters = payload.get("parameters") or {} + for required in ( + "ani_uprating", + "calibration_year", + "model_ani_edges", + "parent_count", + "shares", + "share_base_2022", + "split_band_share", + ): + if required not in parameters: + raise ValueError(f"{CENTAX_FACTS_RESOURCE} lacks parameter {required!r}.") + if parameters["share_base_2022"] != list(CENTAX_SHARE_BASE_2022): + raise ValueError( + f"{CENTAX_FACTS_RESOURCE} shares are not taken within " + f"{CENTAX_SHARE_BASE_2022}." + ) + uprating = float(parameters["ani_uprating"]) + if not 1.0 < uprating < 2.0: + raise ValueError(f"implausible ANI uprating {uprating!r}.") + if parameters["model_ani_edges"] != model_ani_edges(uprating): + raise ValueError( + f"{CENTAX_FACTS_RESOURCE} edges are not the 2021-22 edges aged by " + f"{uprating!r}." + ) + parent_count = float(parameters["parent_count"]) + if not parent_count > 0: + raise ValueError("the parent count must be positive.") + shares = {str(cell): float(share) for cell, share in parameters["shares"].items()} + if set(shares) != set(centax_cell_ids()): + raise ValueError(f"{CENTAX_FACTS_RESOURCE} shares do not cover every cell.") + if any(not 0.0 < share < 1.0 for share in shares.values()): + raise ValueError(f"{CENTAX_FACTS_RESOURCE} has a share outside (0, 1).") + band_total = sum(shares[band] for band, _, _ in CENTAX_ANI_BANDS_2022) + if abs(band_total - 1.0) > 1e-9: + raise ValueError(f"the ANI band shares sum to {band_total!r}, not 1.") + split_share = float(parameters["split_band_share"]) + if not 0.0 < split_share < 1.0: + raise ValueError(f"implausible split band share {split_share!r}.") + for split, _ in CENTAX_SPLITS: + if shares[f"{split}_ani_80k_to_150k"] >= split_share: + raise ValueError( + f"the {split} share exceeds the (£80k, £150k] parents' share." + ) + seen: set[str] = set() + for row in rows: + cell = _validate_row(row) + if cell in seen: + raise ValueError(f"CenTax cell {cell!r} is repeated.") + seen.add(cell) + expected = round(shares[cell] * parent_count, 3) + if abs(float(row["value"]) - expected) > 1e-6: + raise ValueError( + f"CenTax cell {cell!r} value {row['value']!r} is not its share " + f"times the parent count ({expected!r})." + ) + if seen != set(centax_cell_ids()): + raise ValueError( + f"{CENTAX_FACTS_RESOURCE} lacks cells {sorted(set(centax_cell_ids()) - seen)}." + ) + return UKCenTaxChildcareParentFacts( + rows=tuple(rows), + rows_sha256=digest, + inputs_sha256=str(payload.get("inputs_sha256") or ""), + parameters=parameters, + inputs=inputs, + generator=payload.get("generator") or {}, + shares=shares, + ) + + +@cache +def uk_centax_childcare_parent_facts() -> UKCenTaxChildcareParentFacts: + """The committed resource, loaded once.""" + + return load_uk_centax_childcare_parent_facts() diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/derived_facts.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/derived_facts.py index 3f84720dae..92d0fa71b0 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/derived_facts.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/derived_facts.py @@ -1,12 +1,14 @@ """The Microcosm-derived fact resources compiled beside the pinned Chronicle feed. -Two committed resources carry facts Microcosm computes from public data, in +Three committed resources carry facts Microcosm computes from public data, in consumer-fact row shape under the ``microcosm.derived_fact.`` key namespace: the high-value home stock (``uk/high_value_home_stock_facts.json``, -microcosm#1240) and DESNZ's domestic energy split onto constituencies -(``uk/desnz_constituency_energy_facts.json``, microcosm#1095). Every compile of -the UK target references reads both beside the feed, so they are listed here -once; a compile that left one out would find its family's cells absent. +microcosm#1240), DESNZ's domestic energy split onto constituencies +(``uk/desnz_constituency_energy_facts.json``, microcosm#1095) and CenTax's +tabulations of parents of 3- and 4-year-olds +(``uk/centax_childcare_parent_facts.json``, microcosm#1399). Every compile of +the UK target references reads all three beside the feed, so they are listed +here once; a compile that left one out would find its family's cells absent. """ from __future__ import annotations @@ -14,6 +16,9 @@ from collections.abc import Mapping from typing import Any +from microcosm.build.uk_runtime.centax_childcare_parents import ( + load_uk_centax_childcare_parent_facts, +) from microcosm.build.uk_runtime.desnz_constituency_energy import ( load_uk_desnz_constituency_energy_facts, ) @@ -34,6 +39,7 @@ def load_uk_derived_facts() -> dict[str, Any]: return { "high_value_home_stock_facts": load_uk_high_value_home_stock_facts(), "desnz_constituency_energy_facts": load_uk_desnz_constituency_energy_facts(), + "centax_childcare_parent_facts": load_uk_centax_childcare_parent_facts(), } diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/full_targets.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/full_targets.py index c77406a135..89691f7218 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/full_targets.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/full_targets.py @@ -234,8 +234,9 @@ def load_uk_full_target_inputs( ) # Microcosm-derived facts compile beside the Chronicle feed: the high-value # homes stock (HM Land Registry counts, microcosm#1240) at local grain and - # its region rows (microcosm#1301) at national grain, and DESNZ's domestic - # energy split onto constituencies (microcosm#1095). + # its region rows (microcosm#1301) at national grain, DESNZ's domestic + # energy split onto constituencies (microcosm#1095), and CenTax's parent + # cells (microcosm#1399) on the national line. derived = load_uk_derived_facts() facts = (*artifact.facts, *uk_derived_fact_rows(derived)) for period in national_periods: @@ -416,7 +417,8 @@ def load_uk_national_target_inputs( # on their Microcosm-derived facts included (microcosm#1301); those rows # bind on the local line only, so the national surface drops them before # reconciliation, the exclusions and the frozen-register check, and its - # registry is the one it was without them. + # registry is the one it was without them. CenTax's parent cells + # (microcosm#1399) bind on the national line and stay. derived = load_uk_derived_facts() compilation = compile_uk_target_registry( chain(artifact.facts, uk_derived_fact_rows(derived)), target_period=year diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/measure_simulation.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/measure_simulation.py index ef2cff31f5..bdbbbb7a4d 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/measure_simulation.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/measure_simulation.py @@ -22,6 +22,15 @@ from microcosm.build.uk_runtime.atomic_area_support import ( without_uk_native_alias_columns, ) +from microcosm.build.uk_runtime.centax_childcare_parents import ( + CENTAX_EMPLOYEE_MAIN_SOURCE, + CENTAX_EMPLOYEE_SOURCE_INPUTS, + CENTAX_PARENT_ENGINE_INPUTS, + CENTAX_PARENT_MEASURES, + CENTAX_PARENT_OF_ELIGIBLE_3_4, + employment_main_income_source, + parent_of_eligible_3_4_year_old, +) from microcosm.build.uk_runtime.cgt_calibration import UK_CGT_DATED_MEASURE from microcosm.build.uk_runtime.dfe_spring_term import ( DFE_SPRING_TERM_ENGINE_INPUTS, @@ -370,6 +379,8 @@ def annuity_and_trust_share(frame: Any) -> np.ndarray: #: tax year: the 12 months before the interview, applied to the engine's #: amounts at the calibration year (the stage module says how). Poverty, #: benefits and the engine's published tax keep reading current income. +#: CenTax's tabulations of parents' adjusted net income come from the same +#: HMRC data, so they band on the year's ANI too. UK_ANNUAL_INCOME_MEASURES: Mapping[str, str] = { "employment_income_annual": "employment_income", # Pay plus the company car and car fuel benefits, which HMRC's employment @@ -401,6 +412,8 @@ def annuity_and_trust_share(frame: Any) -> np.ndarray: "basic_rate_savings_income_annual": "basic_rate_savings_income", "higher_rate_savings_income_annual": "higher_rate_savings_income", "add_rate_savings_income_annual": "add_rate_savings_income", + # CenTax's parent cells band on the year's ANI (microcosm#1399). + "adjusted_net_income_annual": "adjusted_net_income", } #: The inputs the annual simulation replaces at the measurement year: the #: engine's current amount times its annual share, plus its other spells, @@ -650,6 +663,30 @@ def compute_uk_measure_input( ) return status[variable], f"dfe_spring_term:{variable}" + if variable == CENTAX_PARENT_OF_ELIGIBLE_3_4: + if entity != "person": + raise KeyError(f"{variable} is person-only: {entity}") + inputs = { + name: compute_uk_measure_input(frame, simulation, "person", name, year)[0] + for name in CENTAX_PARENT_ENGINE_INPUTS + } + return ( + parent_of_eligible_3_4_year_old( + birth_year=inputs["birth_year"], + country=inputs["country"], + term_share_before_school=inputs["early_years_term_share_before_school"], + dependent_child=inputs["is_hbai_dependent_child"], + benunit_id=frame.table("person")[_ENTITY_LINK["benunit"]].to_numpy(), + year=year, + ), + f"engine_terms_and_benunit_roles:{variable}", + ) + if variable == CENTAX_EMPLOYEE_MAIN_SOURCE: + raise KeyError( + f"{variable} compares the year's income sources; resolve it through " + "UKMeasureResolver, which computes the annual measures." + ) + if variable in UK_NAMED_TERMS: if entity != "person": raise KeyError(f"{variable} is person-only: {entity}") @@ -1157,6 +1194,14 @@ def __init__( "DfE spring-term measures must not be persisted as source inputs: " f"{persisted_spring_term}" ) + persisted_centax = sorted( + set(CENTAX_PARENT_MEASURES) & set(map(str, frame.table("person"))) + ) + if persisted_centax: + raise ValueError( + "CenTax parent measures must not be persisted as source inputs: " + f"{persisted_centax}" + ) self.simulation = self._new_simulation() validate_uc_claimant_input(self.simulation, frame.table("person"), self.year) self.contract_targets = _uk_contract_targets() @@ -1291,6 +1336,14 @@ def knows(self, entity: str, variable: str) -> bool: return entity == "person" and all( self.knows("person", name) for name in DFE_SPRING_TERM_ENGINE_INPUTS ) + if variable == CENTAX_PARENT_OF_ELIGIBLE_3_4: + return entity == "person" and all( + self.knows("person", name) for name in CENTAX_PARENT_ENGINE_INPUTS + ) + if variable == CENTAX_EMPLOYEE_MAIN_SOURCE: + return entity == "person" and all( + self.knows("person", name) for name in CENTAX_EMPLOYEE_SOURCE_INPUTS + ) cgt_measure = _cgt_model_measure(variable, self.year) if cgt_measure is not None: return entity == "person" and self.knows(entity, cgt_measure[0]) @@ -1342,7 +1395,11 @@ def entity_for(self, variable: str) -> str | None: return "person" if company_car_dated_benefit_year(variable) is not None: return "person" - if variable in UK_NAMED_TERMS or variable in DFE_SPRING_TERM_MEASURES: + if ( + variable in UK_NAMED_TERMS + or variable in DFE_SPRING_TERM_MEASURES + or variable in CENTAX_PARENT_MEASURES + ): return "person" if variable in UK_HOUSEHOLD_ENERGY_MEASURES: return "household" @@ -1390,6 +1447,8 @@ def compute(self, entity: str, variable: str) -> tuple[np.ndarray, str]: self._refuse_dated_measure_after_window(variable) if variable in UK_ANNUAL_INCOME_MEASURES: return self._annual_income_measure(entity, variable) + if variable == CENTAX_EMPLOYEE_MAIN_SOURCE: + return self._employment_main_income_source(entity) if variable in UK_HOUSEHOLD_ENERGY_MEASURES: return self._household_energy(entity, variable) result = compute_uk_measure_input( @@ -1642,6 +1701,39 @@ def _annual_income_measure( ) return values, f"annual_income_simulation:{route}" + def _employment_main_income_source(self, entity: str) -> tuple[np.ndarray, str]: + """One where employment is the largest of the year's income sources. + + Every source is the year's, as in the annual ANI the cells band on: the + annual measures through their own route, and the rest on the annual + simulation, which carries the contributory benefits at their share of + the year and every other source as the engine computes it. At their + current amounts, a benefit paid for part of the year could outrank the + year's pay. + """ + + if entity != "person": + raise KeyError(f"{CENTAX_EMPLOYEE_MAIN_SOURCE} is person-only: {entity}") + simulation = ( + self._annual_income_simulation() + if self._carries_annual_income_descriptors() + else self.simulation + ) + sources = { + name: ( + self.compute("person", name)[0] + if name in UK_ANNUAL_INCOME_MEASURES + else compute_uk_measure_input( + self.frame, simulation, "person", name, self.year + )[0] + ) + for name in CENTAX_EMPLOYEE_SOURCE_INPUTS + } + return ( + employment_main_income_source(sources), + "annual_income_sources:" + ",".join(CENTAX_EMPLOYEE_SOURCE_INPUTS), + ) + def _household_energy(self, entity: str, variable: str) -> tuple[np.ndarray, str]: """A household's domestic energy measure from its stored spend.""" diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/target_compile_modules.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/target_compile_modules.py index bb6b495cbe..0cf7b3007d 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/target_compile_modules.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/target_compile_modules.py @@ -40,6 +40,7 @@ "microcosm.build.target_materialization", "microcosm.build.target_reference_authoring", "microcosm.build.uk_runtime.bus_fare_pricing", + "microcosm.build.uk_runtime.centax_childcare_parents", "microcosm.build.uk_runtime.cgt_calibration", "microcosm.build.uk_runtime.chronicle_feed", "microcosm.build.uk_runtime.council_tax_constants", diff --git a/packages/microcosm-build/tests/engine/uk/test_uk_annual_income_measures.py b/packages/microcosm-build/tests/engine/uk/test_uk_annual_income_measures.py index 0488b408ad..5d6a1f6aa9 100644 --- a/packages/microcosm-build/tests/engine/uk/test_uk_annual_income_measures.py +++ b/packages/microcosm-build/tests/engine/uk/test_uk_annual_income_measures.py @@ -160,6 +160,16 @@ def test_the_annual_measures_tax_each_persons_year(tmp_path) -> None: "employment_income_with_benefits_in_kind" ) np.testing.assert_allclose(with_cars, annual_pay, rtol=1e-6) + # CenTax's parent cells band on the year's adjusted net income + # (microcosm#1399): the leaver's spell raises it, the entrant's half year + # lowers it, and a year paid in full leaves it as it is. + ani, _ = resolver.compute("person", "adjusted_net_income") + annual_ani, route = resolver.compute("person", "adjusted_net_income_annual") + assert route.startswith("annual_income_simulation:") + ani, annual_ani = np.asarray(ani, dtype=float), np.asarray(annual_ani, dtype=float) + assert annual_ani[1] > ani[1] + assert annual_ani[2] < ani[2] + np.testing.assert_allclose(annual_ani[[0, 4]], ani[[0, 4]], rtol=1e-6) receipt = resolver.receipt()["annual_income_measures"] assert receipt["route"] == "annual_income_simulation" factors = receipt["other_spells_engine_factors"] diff --git a/packages/microcosm-build/tests/engine/uk/test_uk_centax_main_income_source.py b/packages/microcosm-build/tests/engine/uk/test_uk_centax_main_income_source.py new file mode 100644 index 0000000000..6ff190b174 --- /dev/null +++ b/packages/microcosm-build/tests/engine/uk/test_uk_centax_main_income_source.py @@ -0,0 +1,53 @@ +"""CenTax's main-source measure compares every component of the engine's ANI. + +CenTax's employees are taxpayers whose main source of income is employment, so +the measure must weigh pay against each source the engine counts in adjusted +net income: the components ``gov.hmrc.income_tax.adjusted_net_income_components`` +lists, which ``total_income_charged_to_tax`` (ITA 2007 s. 23) also sums. A +source left out cannot outrank pay, and a parent whose largest income is that +source would count as an employee. +""" + +from __future__ import annotations + +from microcosm.build.uk_runtime.centax_childcare_parents import ( + CENTAX_EMPLOYEE_SOURCE_COMPONENTS, + CENTAX_EMPLOYEE_SOURCE_ENGINE_NAMES, + CENTAX_EMPLOYEE_SOURCE_INPUTS, +) +from microcosm.build.uk_runtime.ledger_targets import UK_TARGET_REFERENCE_PERIOD + + +def test_the_main_source_measure_compares_every_ani_component(): + from policyengine_uk import CountryTaxBenefitSystem + + system = CountryTaxBenefitSystem() + components = system.parameters.gov.hmrc.income_tax.adjusted_net_income_components( + f"{UK_TARGET_REFERENCE_PERIOD}-01-01" + ) + assert sorted(CENTAX_EMPLOYEE_SOURCE_COMPONENTS) == sorted(components) + assert len(set(CENTAX_EMPLOYEE_SOURCE_INPUTS)) == len(CENTAX_EMPLOYEE_SOURCE_INPUTS) + assert CENTAX_EMPLOYEE_SOURCE_INPUTS[0] == ( + "employment_income_with_benefits_in_kind_annual" + ) + + +def test_the_measure_takes_social_security_and_pensions_as_the_engine_adds_them(): + from policyengine_uk import CountryTaxBenefitSystem + + variables = CountryTaxBenefitSystem().variables + assert variables["taxable_social_security_income"].adds == [ + "social_security_income" + ] + compared = [ + CENTAX_EMPLOYEE_SOURCE_ENGINE_NAMES.get(name, name) + for name in CENTAX_EMPLOYEE_SOURCE_COMPONENTS["taxable_social_security_income"] + ] + assert sorted(compared) == sorted(variables["social_security_income"].adds) + assert variables["taxable_pension_income"].adds == ["private_pension_income"] + # Employment is pay plus the company car and car fuel benefits, which the + # engine's taxable employment income counts and keeps apart from pay. + assert variables["benefits_in_kind"].adds == [ + "company_car_benefit", + "car_fuel_benefit", + ] diff --git a/packages/microcosm-build/tests/engine_free/shared/test_country_spec.py b/packages/microcosm-build/tests/engine_free/shared/test_country_spec.py index 5f7a3d867c..9dec423275 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_country_spec.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_country_spec.py @@ -1125,6 +1125,7 @@ def test_spi_spine_adds_no_country_package_resources(self) -> None: "etb_services_support_bounds.json", "regional_land_values.json", "high_value_home_stock_facts.json", + "centax_childcare_parent_facts.json", "high_value_home_value_knots.json", "high_value_home_stock.provenance.json", "voa_council_tax_band_mix_lsoa.json", @@ -1316,6 +1317,7 @@ def test_uk_package_loads(self) -> None: "etb_services_support_bounds.json", "regional_land_values.json", "high_value_home_stock_facts.json", + "centax_childcare_parent_facts.json", "high_value_home_value_knots.json", "high_value_home_stock.provenance.json", "voa_council_tax_band_mix_lsoa.json", diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_centax_childcare_parents.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_centax_childcare_parents.py new file mode 100644 index 0000000000..b85ef20d86 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_centax_childcare_parents.py @@ -0,0 +1,819 @@ +"""CenTax's parent tabulations as Microcosm-derived facts (microcosm#1399). + +Invariants, for every input the strategies draw: + +- the three ANI band shares sum to one, so the bands partition the share base + (£50k, £200k], and every split share is below the (£80k, £150k] share; +- every committed value is its share times the baseline parent count; +- the aged edges are the 2021-22 edges times the uprating, rounded, so the + bands stay contiguous and increasing from the aged £50k and move up with the + uprating; +- the parent measure is 0 or 1, never 1 for a child, the same for every adult + of a benefit unit, 0 in a unit with no eligible child, and follows its + people when they are reordered; +- the main-source measure is 0 or 1, 0 without positive pay, never turns off + as pay rises, and ignores the scale of all sources together; +- the region groups partition England's nine regions with the East of England + in either group outside London; +- the diagnostic's support over FRS source households never exceeds its + support over Microcosm households (fewer sources, a lower Kish count, a + larger top-ten share), and equals it when each household is its own source; +- the workbook is the one Chronicle registers, with the pinned bytes; +- the contract binds exactly the resource's cells, with its edges. +""" + +from __future__ import annotations + +import copy +import hashlib +import importlib.util +import json +from pathlib import Path + +import numpy as np +import pytest +import yaml +from hypothesis import given, settings +from hypothesis import strategies as st + +from microcosm.build.uk_runtime.centax_childcare_parents import ( + CENTAX_ANI_BANDS_2022, + CENTAX_ANI_MEASURE, + CENTAX_BOUND_REGION_GROUPS, + CENTAX_CHRONICLE_PACKAGE_ID, + CENTAX_EAST_OF_ENGLAND, + CENTAX_EMPLOYEE_MAIN_SOURCE, + CENTAX_EMPLOYEE_SOURCE_COMPONENTS, + CENTAX_EMPLOYEE_SOURCE_INPUTS, + CENTAX_FACTS_RESOURCE, + CENTAX_FILTER_CONCEPTS, + CENTAX_PARENT_OF_ELIGIBLE_3_4, + CENTAX_REGION_GROUP_CODES, + CENTAX_SHARE_BASE_2022, + CENTAX_SPLIT_BAND_2022, + CENTAX_SPLITS, + CENTAX_WORKBOOK_FILENAME, + CENTAX_WORKBOOK_SHA256, + aged_edges, + centax_cell_filters, + centax_cell_ids, + centax_cell_measurement_filters, + centax_region_codes, + employment_main_income_source, + load_uk_centax_childcare_parent_facts, + model_ani_edges, + parent_of_eligible_3_4_year_old, + rows_sha256, +) +from microcosm.build.uk_runtime.derived_facts import ( + load_uk_derived_facts, + uk_derived_fact_resource_pins, + uk_derived_fact_rows, +) +from microcosm.build.uk_runtime.ledger_targets import ( + _uk_contract_targets, + uk_contract_target_calibration_lines, +) +from test_support.paths import paths_for + +ROOT = paths_for("microcosm-build").repository +_BUILDER_SPEC = importlib.util.spec_from_file_location( + "build_uk_centax_childcare_parent_facts", + ROOT / "tools/build_uk_centax_childcare_parent_facts.py", +) +assert _BUILDER_SPEC is not None and _BUILDER_SPEC.loader is not None +_builder = importlib.util.module_from_spec(_BUILDER_SPEC) +_BUILDER_SPEC.loader.exec_module(_builder) +_DIAGNOSTIC_SPEC = importlib.util.spec_from_file_location( + "diagnose_uk_centax_parents", ROOT / "tools/diagnose_uk_centax_parents.py" +) +assert _DIAGNOSTIC_SPEC is not None and _DIAGNOSTIC_SPEC.loader is not None +_diagnostic = importlib.util.module_from_spec(_DIAGNOSTIC_SPEC) +_DIAGNOSTIC_SPEC.loader.exec_module(_diagnostic) + +_PREFIX = "microcosm.centax_childcare_parents." +_BANDS = tuple(band for band, _, _ in CENTAX_ANI_BANDS_2022) +_SPLIT_CELLS = tuple(f"{split}_ani_80k_to_150k" for split, _ in CENTAX_SPLITS) +#: The cells of the first design that the review left as diagnostics. +_DIAGNOSTIC_CELLS = ( + "ani_0_to_50k", + "south_excl_london_ani_80k_to_150k", + "north_and_midlands_ani_80k_to_150k", +) +_ENGLISH_REGIONS = {f"E1200000{index}" for index in range(1, 10)} + + +def _resource_payload() -> dict: + from importlib.resources import files + + return json.loads( + files("microcosm.build.uk").joinpath(CENTAX_FACTS_RESOURCE).read_text() + ) + + +def _write(tmp_path: Path, payload: dict) -> Path: + path = tmp_path / CENTAX_FACTS_RESOURCE + path.write_text(json.dumps(payload)) + return path + + +# The committed resource. + + +def test_the_committed_resource_partitions_and_scales_its_shares() -> None: + facts = load_uk_centax_childcare_parent_facts() + shares = facts.shares + + assert set(shares) == set(centax_cell_ids()) == {*_BANDS, *_SPLIT_CELLS} + assert sum(shares[band] for band in _BANDS) == pytest.approx(1.0, abs=1e-12) + split_share = facts.parameters["split_band_share"] + for cell in _SPLIT_CELLS: + assert 0.0 < shares[cell] < split_share + for cell in centax_cell_ids(): + assert facts.value(cell) == pytest.approx( + round(shares[cell] * facts.parent_count, 3), abs=1e-9 + ) + # The bands' counts add back to the parent count the shares scale. + assert sum(facts.value(band) for band in _BANDS) == pytest.approx( + facts.parent_count, abs=0.01 + ) + + +def test_the_committed_resource_ages_its_edges_contiguously() -> None: + facts = load_uk_centax_childcare_parent_facts() + edges = facts.parameters["model_ani_edges"] + uprating = facts.ani_uprating + + assert edges == model_ani_edges(uprating) + assert [edges[band][0] for band in _BANDS[1:]] == [ + edges[band][1] for band in _BANDS[:-1] + ] + # The bands cover the aged share base and nothing below it. + assert [edges[_BANDS[0]][0], edges[_BANDS[-1]][1]] == aged_edges( + *CENTAX_SHARE_BASE_2022, uprating + ) + split = edges[_SPLIT_CELLS[0]] + assert all(edges[cell] == split for cell in _SPLIT_CELLS) + # The split band starts where the (£80k, £120k] band does. + assert split[0] == edges["ani_80k_to_120k"][0] + assert split[1] < edges["ani_120k_to_200k"][1] + + +def test_the_committed_resource_names_its_registration_and_baseline() -> None: + payload = _resource_payload() + facts = load_uk_centax_childcare_parent_facts() + workbook = facts.inputs["workbook"] + + assert payload["rows_sha256"] == rows_sha256(payload["rows"]) + assert workbook["chronicle_package_id"] == CENTAX_CHRONICLE_PACKAGE_ID + assert workbook["registration_kind"] == "raw_only" + (registered,) = workbook["files"].values() + assert registered["filename"] == CENTAX_WORKBOOK_FILENAME + assert registered["sha256"] == CENTAX_WORKBOOK_SHA256 + assert registered["r2_key"].startswith( + f"raw/uk/centax/{CENTAX_CHRONICLE_PACKAGE_ID}/" + ) + assert workbook["source_page"] == ( + "https://arunadvani.com/policy.html#ChildcareCliffEdge" + ) + # The attribution is the registration's, not typed here. + assert payload["licence"]["attribution"] == [workbook["licence"]["attribution"]] + assert "Flew, J." in workbook["licence"]["attribution"] + assert len(facts.baseline["sha256"]) == 64 and facts.baseline["dataset"] + assert payload["parameters"]["parent_count_basis"].endswith( + f"at {facts.parameters['calibration_year']}" + ) + + +def test_the_committed_resource_holds_only_its_derivation() -> None: + facts = load_uk_centax_childcare_parent_facts() + # Vahid's review, item 8: the diagnostics-only figures left the resource. + assert "diagnostic_comparators" not in facts.parameters + assert "workbook_sums" not in facts.parameters + assert {row["source"]["url"] for row in facts.rows} == { + "https://centax.org.uk/wp-content/uploads/2026/09/" + "AdvaniFlewPepin-HallSummers2026_Removing-the-childcare-cliff-edge.pdf" + } + tables = {row["source"]["source_table"] for row in facts.rows} + assert all( + any(f"Fig. {figure}" in table for figure in ("3.1", "3.3", "3.6", "3.7")) + and CENTAX_CHRONICLE_PACKAGE_ID in table + for table in tables + ) + never = " ".join(facts.parameters["never_targets"]) + for excluded in ("3.1, 3.2 and 4.1", "elasticities", "cost"): + assert excluded in never + assert {row["geography"]["id"] for row in facts.rows} == {"E92000001"} + # Item 7: the cells count the 2025-26 tax year, which the engine dates 2025. + year = int(facts.parameters["calibration_year"]) + for row in facts.rows: + assert row["period"] == {"type": "calendar_year", "value": str(year)} + assert row["period_coverage"]["start_date"] == f"{year}-04-06" + assert row["period_coverage"]["end_date"] == f"{year + 1}-04-05" + + +@pytest.mark.parametrize( + ("mutate", "message"), + [ + (lambda p: p["rows"][0].__setitem__("value", 1.0), "digest"), + (lambda p: p["rows"].pop(), "row_count"), + ( + lambda p: next(iter(p["inputs"]["workbook"]["files"].values())).__setitem__( + "sha256", "0" * 64 + ), + "pinned CenTax workbook", + ), + ( + lambda p: p["inputs"]["workbook"].__setitem__( + "chronicle_package_id", "centax-another-package" + ), + "Chronicle registration", + ), + ( + lambda p: p["inputs"]["workbook"].__setitem__( + "registration_kind", "committed" + ), + "raw-only", + ), + (lambda p: p["inputs"]["baseline"].__setitem__("sha256", ""), "baseline"), + ( + lambda p: p["parameters"].__setitem__("ani_uprating", 1.25), + "edges are not", + ), + ( + lambda p: p["parameters"]["shares"].__setitem__("ani_50k_to_80k", 0.5), + "sum to", + ), + ( + lambda p: p["parameters"].__setitem__("share_base_2022", [0.0, 200_000.0]), + "taken within", + ), + (lambda p: p.__setitem__("schema_version", 1), "schema-2"), + ], +) +def test_the_loader_refuses_a_tampered_resource(tmp_path, mutate, message) -> None: + payload = _resource_payload() + mutate(payload) + with pytest.raises(ValueError, match=message): + load_uk_centax_childcare_parent_facts(_write(tmp_path, payload)) + + +def test_the_loader_refuses_a_value_off_its_share(tmp_path) -> None: + payload = _resource_payload() + payload["rows"][0]["value"] = round(payload["rows"][0]["value"] + 1.0, 3) + payload["rows_sha256"] = rows_sha256(payload["rows"]) + with pytest.raises(ValueError, match="share times the parent count"): + load_uk_centax_childcare_parent_facts(_write(tmp_path, payload)) + + +def test_the_loader_refuses_a_split_above_its_band(tmp_path) -> None: + payload = _resource_payload() + payload["parameters"]["shares"]["london_ani_80k_to_150k"] = payload["parameters"][ + "split_band_share" + ] + with pytest.raises(ValueError, match="exceeds"): + load_uk_centax_childcare_parent_facts(_write(tmp_path, payload)) + + +def test_the_loader_refuses_a_repeated_cell(tmp_path) -> None: + payload = _resource_payload() + payload["rows"][1] = copy.deepcopy(payload["rows"][0]) + payload["rows_sha256"] = rows_sha256(payload["rows"]) + with pytest.raises(ValueError, match="repeated"): + load_uk_centax_childcare_parent_facts(_write(tmp_path, payload)) + + +@settings(max_examples=40, deadline=None) +@given(st.permutations(range(len(centax_cell_ids())))) +def test_the_rows_digest_ignores_row_order(order) -> None: + rows = _resource_payload()["rows"] + assert rows_sha256([rows[i] for i in order]) == rows_sha256(rows) + + +# The aged edges. + + +@settings(max_examples=200, deadline=None) +@given(st.floats(1.0001, 1.9999, allow_nan=False), st.floats(0.0, 0.5)) +def test_aged_edges_stay_contiguous_and_rise_with_the_uprating(uprating, step): + edges = model_ani_edges(uprating) + higher = model_ani_edges(min(uprating + step, 1.9999)) + + for band, lower, upper in CENTAX_ANI_BANDS_2022: + assert edges[band] == [round(lower * uprating), round(upper * uprating)] + assert edges[band][0] < edges[band][1] + assert higher[band][0] >= edges[band][0] + assert higher[band][1] >= edges[band][1] + assert [edges[band][0] for band in _BANDS[1:]] == [ + edges[band][1] for band in _BANDS[:-1] + ] + assert [edges[_BANDS[0]][0], edges[_BANDS[-1]][1]] == aged_edges( + *CENTAX_SHARE_BASE_2022, uprating + ) + lower, upper = CENTAX_SPLIT_BAND_2022 + assert all( + edges[cell] == [round(lower * uprating), round(upper * uprating)] + for cell in _SPLIT_CELLS + ) + + +def test_cell_filters_carry_the_edges_and_one_split_each() -> None: + edges = model_ani_edges(1.25) + for cell in centax_cell_ids(): + filters = centax_cell_filters(cell, edges[cell]) + assert filters[0] == {"variable": CENTAX_PARENT_OF_ELIGIBLE_3_4, "equals": 1} + assert filters[1:3] == [ + {"variable": CENTAX_ANI_MEASURE, "operator": ">", "value": edges[cell][0]}, + { + "variable": CENTAX_ANI_MEASURE, + "operator": "<=", + "value": edges[cell][1], + }, + ] + assert len(filters) == (3 if cell in _BANDS else 4) + # The measurement filters are the binding filters with each variable + # named by its concept. + measured = centax_cell_measurement_filters(cell, edges[cell]) + assert measured == [ + { + "concept": CENTAX_FILTER_CONCEPTS[f["variable"]], + **{k: v for k, v in f.items() if k != "variable"}, + } + for f in filters + ] + assert centax_cell_filters("london_ani_80k_to_150k", [1, 2])[-1] == { + "variable": "region", + "in": ["LONDON"], + } + # The cells the review left as diagnostics are no cells of the resource. + for cell in _DIAGNOSTIC_CELLS: + with pytest.raises(KeyError): + centax_cell_filters(cell, [0, 1]) + + +@pytest.mark.parametrize("east_in", ["south_excl_london", "north_and_midlands"]) +def test_the_region_groups_partition_england_with_the_east_either_way(east_in): + groups = centax_region_codes(east_in=east_in) + codes = [code for group in groups.values() for code in group] + assert sorted(codes) == sorted(_ENGLISH_REGIONS) + assert CENTAX_EAST_OF_ENGLAND in groups[east_in] + assert groups["london"] == CENTAX_REGION_GROUP_CODES["london"] + assert CENTAX_BOUND_REGION_GROUPS == ("london",) + with pytest.raises(ValueError, match="cannot sit"): + centax_region_codes(east_in="london") + + +# The measures. + +_people = st.integers(1, 12) + + +@st.composite +def _population(draw): + n = draw(_people) + return { + "birth_year": np.asarray( + draw(st.lists(st.integers(1960, 2025), min_size=n, max_size=n)) + ), + "country": np.asarray( + draw( + st.lists( + st.sampled_from(["ENGLAND", "SCOTLAND", "WALES"]), + min_size=n, + max_size=n, + ) + ) + ), + "term_share_before_school": np.asarray( + draw(st.lists(st.sampled_from([0.0, 1 / 3, 1.0]), min_size=n, max_size=n)), + dtype=np.float32, + ), + "dependent_child": np.asarray( + draw(st.lists(st.booleans(), min_size=n, max_size=n)) + ), + "benunit_id": np.asarray( + draw(st.lists(st.integers(0, 3), min_size=n, max_size=n)) + ), + } + + +@settings(max_examples=200, deadline=None) +@given(_population(), st.randoms(use_true_random=False)) +def test_the_parent_measure_marks_whole_units_of_adults(population, rng) -> None: + parent = parent_of_eligible_3_4_year_old(**population, year=2025) + child = population["dependent_child"] + units = population["benunit_id"] + dfe_age = 2025 - population["birth_year"] + eligible = ( + child + & (population["country"] == "ENGLAND") + & np.isin(dfe_age, (3, 4, 5)) + & (population["term_share_before_school"] > 1 / 6) + ) + + assert set(np.unique(parent)) <= {0.0, 1.0} + assert not parent[child].any() + for unit in np.unique(units): + adults = (units == unit) & ~child + expected = 1.0 if eligible[units == unit].any() else 0.0 + assert (parent[adults] == expected).all() + + order = list(range(len(units))) + rng.shuffle(order) + shuffled = parent_of_eligible_3_4_year_old( + **{name: values[order] for name, values in population.items()}, year=2025 + ) + np.testing.assert_array_equal(shuffled, parent[order]) + + +def test_the_parent_measure_reads_the_dfe_age_and_term_share() -> None: + # A couple with a DfE-age-5 child before school in one term, a lone + # parent with a DfE-age-5 child already at school all year, a parent of a + # DfE-age-2 child, and a Welsh parent of a 3-year-old. + parent = parent_of_eligible_3_4_year_old( + birth_year=np.asarray([1990, 1991, 2020, 1985, 2020, 1992, 2023, 1993, 2022]), + country=np.asarray(["ENGLAND"] * 7 + ["WALES"] * 2), + term_share_before_school=np.asarray( + [1, 1, 1 / 3, 1, 0, 1, 1, 1, 1], dtype=np.float32 + ), + dependent_child=np.asarray([0, 0, 1, 0, 1, 0, 1, 0, 1], dtype=bool), + benunit_id=np.asarray([1, 1, 1, 2, 2, 3, 3, 4, 4]), + year=2025, + ) + assert parent.tolist() == [1, 1, 0, 0, 0, 0, 0, 0, 0] + + +def test_the_compared_sources_are_the_ani_components_employment_first() -> None: + assert CENTAX_EMPLOYEE_SOURCE_INPUTS == tuple( + name + for sources in CENTAX_EMPLOYEE_SOURCE_COMPONENTS.values() + for name in sources + ) + assert CENTAX_EMPLOYEE_SOURCE_COMPONENTS["taxable_employment_income"] == ( + CENTAX_EMPLOYEE_SOURCE_INPUTS[0], + ) + assert CENTAX_EMPLOYEE_SOURCE_INPUTS[0] == ( + "employment_income_with_benefits_in_kind_annual" + ) + assert len(set(CENTAX_EMPLOYEE_SOURCE_INPUTS)) == len(CENTAX_EMPLOYEE_SOURCE_INPUTS) + + +_sources = st.lists( + st.floats(-5_000.0, 300_000.0, allow_nan=False), + min_size=len(CENTAX_EMPLOYEE_SOURCE_INPUTS), + max_size=len(CENTAX_EMPLOYEE_SOURCE_INPUTS), +) + + +@settings(max_examples=300, deadline=None) +@given(st.lists(_sources, min_size=1, max_size=8), st.floats(0.0, 50_000.0)) +def test_the_main_source_measure_is_monotone_in_pay(rows, raise_pay) -> None: + matrix = np.asarray(rows, dtype=float) + sources = { + name: matrix[:, column] + for column, name in enumerate(CENTAX_EMPLOYEE_SOURCE_INPUTS) + } + employee = employment_main_income_source(sources) + pay = sources[CENTAX_EMPLOYEE_SOURCE_INPUTS[0]] + + assert set(np.unique(employee)) <= {0.0, 1.0} + assert not employee[pay <= 0].any() + raised = employment_main_income_source( + {**sources, CENTAX_EMPLOYEE_SOURCE_INPUTS[0]: pay + raise_pay} + ) + assert (raised >= employee).all() + scaled = employment_main_income_source( + {name: values * 3.0 for name, values in sources.items()} + ) + np.testing.assert_array_equal(scaled, employee) + + +@pytest.mark.parametrize("source", CENTAX_EMPLOYEE_SOURCE_INPUTS[1:]) +def test_every_other_source_can_outrank_employment(source) -> None: + # Pay of 30,000 against 100,000 from one other source: that source is the + # main one, whichever it is; at 100,000 each, the tie goes to employment. + zeros = {name: np.zeros(2) for name in CENTAX_EMPLOYEE_SOURCE_INPUTS} + sources = { + **zeros, + CENTAX_EMPLOYEE_SOURCE_INPUTS[0]: np.array([30_000.0, 100_000.0]), + source: np.array([100_000.0, 100_000.0]), + } + assert employment_main_income_source(sources).tolist() == [0.0, 1.0] + + +def test_the_main_source_measure_refuses_a_missing_source() -> None: + with pytest.raises(ValueError, match="needs"): + employment_main_income_source( + {"employment_income_with_benefits_in_kind_annual": np.ones(2)} + ) + + +# The diagnostic. + + +@st.composite +def _cell_people(draw): + """People of up to a dozen households, each a copy of one source household.""" + + households = draw(st.integers(1, 12)) + sized = {"min_size": households, "max_size": households} + source = np.asarray(draw(st.lists(st.integers(0, households - 1), **sized))) + weight = np.asarray(draw(st.lists(st.floats(0.5, 500.0), **sized))) + members = draw(st.lists(st.integers(1, 3), **sized)) + household = np.repeat(np.arange(households), members) + people = len(household) + in_cell = np.asarray( + draw(st.lists(st.booleans(), min_size=people, max_size=people)) + ) + return in_cell, weight[household], household, source[household] + + +@settings(max_examples=200, deadline=None) +@given(_cell_people()) +def test_source_support_never_exceeds_household_support(people) -> None: + in_cell, weight, household, source = people + support = _diagnostic._support(in_cell, weight, household, source) + if not in_cell.any(): + assert support["source_households"] == 0 + return + assert support["source_households"] <= support["households"] + assert support["kish_source_households"] <= support["kish_contributions"] * ( + 1 + 1e-12 + ) + assert support["top10_source_share"] >= support["top10_household_share"] - 1e-12 + own = _diagnostic._support(in_cell, weight, household, household) + assert own["source_households"] == own["households"] + assert own["kish_source_households"] == pytest.approx(own["kish_contributions"]) + assert own["top10_source_share"] == pytest.approx(own["top10_household_share"]) + + +def test_copies_of_one_source_household_count_once() -> None: + # Households 0 and 1 copy source 7; household 2 is source 8. Over households + # the cell's Kish count is 400^2 / (100^2 + 100^2 + 200^2) = 8/3; over + # sources it is 400^2 / (200^2 + 200^2) = 2. + support = _diagnostic._support( + np.ones(3, dtype=bool), + np.array([100.0, 100.0, 200.0]), + np.array([0, 1, 2]), + np.array([7, 7, 8]), + ) + assert support["households"] == 3 and support["source_households"] == 2 + assert support["kish_contributions"] == pytest.approx(8 / 3) + assert support["kish_source_households"] == pytest.approx(2.0) + assert support["top10_source_share"] == pytest.approx(1.0) + + +def test_the_top_ten_share_counts_sources_not_households() -> None: + # Twelve equal households, the first two copies of one source: the ten + # heaviest households hold 10/12 of the cell, the ten heaviest of the 11 + # sources (the doubled one and nine others) hold 11/12 (review r3). + support = _diagnostic._support( + np.ones(12, dtype=bool), + np.full(12, 50.0), + np.arange(12), + np.array([0, 0, *range(1, 11)]), + ) + assert support["source_households"] == 11 + assert support["top10_household_share"] == pytest.approx(10 / 12) + assert support["top10_source_share"] == pytest.approx(11 / 12) + + +@pytest.mark.parametrize( + ("count", "within"), + [(1_000.0, True), (1_019.0, True), (1_021.0, False), (979.0, False)], +) +def test_the_level_check_compares_the_parent_counts(count, within) -> None: + # Vahid's review, item 2: a baseline that has moved from the resource's + # count pulls the fit by the drift. + check = _diagnostic.level_check(count, 1_000.0, 0.02) + assert check["drift"] == pytest.approx(count / 1_000.0 - 1.0) + assert check["within_tolerance"] is within + with pytest.raises(ValueError, match="positive"): + _diagnostic.level_check(count, 0.0, 0.02) + + +# The contract and the compile. + + +def test_the_contract_binds_the_resource_cells_on_the_national_line() -> None: + facts = load_uk_centax_childcare_parent_facts() + targets = { + target_id: target + for target_id, target in _uk_contract_targets(national_only=False).items() + if target_id.startswith(_PREFIX) + } + specs = { + row["dimensions"]["microcosm.centax_cell"]: row["layout"]["record_set_spec_id"] + for row in facts.rows + } + + assert {target_id.removeprefix(_PREFIX) for target_id in targets} == set( + centax_cell_ids() + ) + assert not {_PREFIX + cell for cell in _DIAGNOSTIC_CELLS} & set(targets) + for target_id, target in targets.items(): + cell = target_id.removeprefix(_PREFIX) + edges = facts.model_edges(cell) + binding = target["bindings"]["policyengine"] + assert binding["filters"] == centax_cell_filters(cell, edges) + assert target["measurement"]["filters"] == centax_cell_measurement_filters( + cell, edges + ) + assert binding["value_variable"] == "person_count" + assert target["ledger_selector"] == { + "source_name": "microcosm", + "source_measure_id": "parents_of_eligible_3_4_year_olds", + "record_set_spec_id": specs[cell], + } + assert uk_contract_target_calibration_lines(target) == {"national"} + assert target["family"] == "centax_childcare_parents" + assert target["geography_levels"] == ["country"] + variables = {f["variable"] for f in binding["filters"]} + assert variables <= { + CENTAX_PARENT_OF_ELIGIBLE_3_4, + CENTAX_ANI_MEASURE, + CENTAX_EMPLOYEE_MAIN_SOURCE, + "gender", + "region", + } + + +def test_every_compile_reads_the_centax_resource_with_the_others() -> None: + centax = load_uk_centax_childcare_parent_facts() + resources = load_uk_derived_facts() + + assert resources["centax_childcare_parent_facts"].rows == centax.rows + rows = uk_derived_fact_rows() + assert rows[-len(centax.rows) :] == centax.rows + pins = uk_derived_fact_resource_pins() + assert pins[CENTAX_FACTS_RESOURCE]["rows_sha256"] == centax.rows_sha256 + keys = [row["aggregate_fact_key"] for row in rows] + assert len(keys) == len(set(keys)) + + +def test_the_compile_sites_read_the_merged_rows() -> None: + sites = ( + "packages/microcosm-build/src/microcosm/build/uk_runtime/full_targets.py", + "tools/build_uk_ledger_compile_parity_signed_differences.py", + "tools/certify_uk_release_cut.py", + "tools/diagnose_uk_uc_matrix.py", + "tools/evaluate_uk_incumbent_surface.py", + ) + for site in sites: + text = (ROOT / site).read_text() + assert "uk_derived_fact_rows(" in text, site + assert "load_uk_high_value_home_stock_facts().rows" not in text, site + generator = (ROOT / "tools/generate_uk_target_references.py").read_text() + assert "load_uk_centax_childcare_parent_facts(args.centax_facts)" in generator + + +# The builder: the registration, the baseline and the arithmetic. + + +def _registration(tmp_path: Path, content: bytes, **overrides) -> tuple[Path, Path]: + """A manifest registering ``content`` the way Chronicle's does, and the file.""" + + workbook = tmp_path / CENTAX_WORKBOOK_FILENAME + workbook.write_bytes(content) + entry = { + "filename": CENTAX_WORKBOOK_FILENAME, + "source_url": f"https://arunadvani.com/data/{CENTAX_WORKBOOK_FILENAME}", + "sha256": hashlib.sha256(content).hexdigest(), + "size_bytes": len(content), + "vintage": "centax_2026_09", + "storage": {"local": False, "r2": {"key": "raw/uk/centax/x"}}, + } + manifest = { + "source_id": "centax", + "package_id": CENTAX_CHRONICLE_PACKAGE_ID, + "registration_kind": "raw_only", + "license": "None stated", + "files": {2026: entry}, + **overrides, + } + path = tmp_path / "manifest.yaml" + path.write_text(yaml.safe_dump(manifest)) + return path, workbook + + +def test_the_builder_refuses_another_package(tmp_path) -> None: + manifest, workbook = _registration( + tmp_path, b"x", package_id="ons-nspl-august-2026" + ) + with pytest.raises(ValueError, match="is not the centax-childcare"): + _builder.open_registered_workbook(manifest, workbook) + + +def test_the_builder_refuses_bytes_the_manifest_does_not_pin(tmp_path) -> None: + manifest, workbook = _registration(tmp_path, b"registered") + workbook.write_bytes(b"something else") + with pytest.raises(ValueError, match="size"): + _builder.open_registered_workbook(manifest, workbook) + + +def test_the_builder_refuses_a_registration_of_other_bytes(tmp_path) -> None: + # The manifest and the file agree, but not with the module's pin. + manifest, workbook = _registration(tmp_path, b"not the CenTax workbook") + with pytest.raises(ValueError, match="this module pins"): + _builder.open_registered_workbook(manifest, workbook) + + +def _baseline(uprating: float, **overrides) -> dict: + return { + "schema": _builder.DIAGNOSTICS_SCHEMA, + "year": 2025, + "ani_uprating": uprating, + "model_ani_edges": model_ani_edges(uprating), + "parent_count_range": aged_edges(*CENTAX_SHARE_BASE_2022, uprating), + "resolver": {"policyengine_uk_version": "9.9.9"}, + **overrides, + } + + +@pytest.mark.parametrize( + ("overrides", "message"), + [ + ({"schema": "microcosm.uk.centax_parent_diagnostics.v1"}, "not"), + ({"year": 2024}, "at 2024"), + ({"parent_count_range": [0, 249_543]}, "another ANI range"), + ({"resolver": {"policyengine_uk_version": "1.0.0"}}, "installed"), + ], +) +def test_the_builder_refuses_another_baseline(monkeypatch, overrides, message) -> None: + monkeypatch.setattr(_builder.importlib.metadata, "version", lambda name: "9.9.9") + _builder.check_baseline(_baseline(1.25), calibration_year=2025, uprating=1.25) + with pytest.raises(ValueError, match=message): + _builder.check_baseline( + _baseline(1.25, **overrides), calibration_year=2025, uprating=1.25 + ) + + +def test_a_fact_row_covers_the_tax_year_the_engine_dates_2025() -> None: + row = _builder.fact_row( + cell="london_ani_80k_to_150k", + value=1234.5, + period="2025", + edges=[99_817, 187_158], + inputs_sha256="0" * 64, + vintage="centax_2026_09", + ) + assert row["period"] == {"type": "calendar_year", "value": "2025"} + assert row["period_coverage"]["start_date"] == "2025-04-06" + assert row["period_coverage"]["end_date"] == "2026-04-05" + assert "2025-26 tax year" in row["period_coverage"]["notes"] + assert row["source"]["vintage"] == "centax_2026_09" + + +class _Sheet: + def __init__(self, rows): + self._rows = rows + + def iter_rows(self, *, values_only): + assert values_only + return iter(self._rows) + + +def _sheet(name: str, columns: list[list[float]]) -> _Sheet: + header, step = _builder.SHEETS[name] + rows = [(None, *header)] + for index, values in enumerate(zip(*columns, strict=True), start=1): + rows.append((None, index * step, *values)) + return _Sheet(rows) + + +@settings(max_examples=40, deadline=None) +@given(st.integers(0, 2**32 - 1), st.floats(1.0, 1e4), st.floats(1.0, 1e4)) +def test_shares_partition_on_any_positive_workbook(seed, low, spread) -> None: + rng = np.random.default_rng(seed) + + def column(length): + # Positive bin counts; a lognormal draw gives spiky and flat shapes. + return (low * rng.lognormal(0.0, np.log1p(spread) / 4, size=length)).tolist() + + workbook = { + "Fig. 3.1": _sheet("Fig. 3.1", [column(400)]), + "Fig. 3.3": _sheet("Fig. 3.3", [column(150), column(150)]), + "Fig. 3.6": _sheet("Fig. 3.6", [column(300), column(300)]), + "Fig. 3.7": _sheet("Fig. 3.7", [column(150) for _ in range(4)]), + } + shares, split_share = _builder.centax_shares(workbook) + + assert set(shares) == set(centax_cell_ids()) + assert sum(shares[band] for band in _BANDS) == pytest.approx(1.0, abs=1e-12) + assert 0.0 < split_share < 1.0 + assert all(0.0 < share < 1.0 for share in shares.values()) + assert all(shares[cell] < split_share for cell in _SPLIT_CELLS) + + +def test_band_sums_take_bins_by_their_upper_edge() -> None: + series = {500: 1.0, 1000: 2.0, 1500: 4.0} + assert _builder.band_sum(series, 0.0, 1000.0) == 3.0 + assert _builder.band_sum(series, 500.0, 1500.0) == 6.0 + assert _builder.band_sum(series, 1000.0, 1000.0) == 0.0 + + +def test_the_series_reader_refuses_a_gap_in_the_bins() -> None: + header, _ = _builder.SHEETS["Fig. 3.1"] + sheet = _Sheet([(None, *header), (None, 500, 1.0), (None, 1500, 1.0)]) + with pytest.raises(ValueError, match="bins are not every"): + _builder.read_series({"Fig. 3.1": sheet}, "Fig. 3.1") diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_high_value_homes_region_control.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_high_value_homes_region_control.py index 2daa83c49d..36835391c4 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_high_value_homes_region_control.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_high_value_homes_region_control.py @@ -137,10 +137,13 @@ def test_a_malformed_calibration_lines_declaration_is_refused(declared, message) def test_only_the_region_rows_narrow_their_lines_in_the_committed_contract(): + # CenTax's England parent cells (microcosm#1399) are the one other family + # that narrows its lines, to the national line. narrowed = { target_id: uk_contract_target_calibration_lines(target) for target_id, target in _targets().items() if "calibration_lines" in target + and not target_id.startswith("microcosm.centax_childcare_parents.") } assert narrowed == {target_id: {"local"} for target_id in REGION_TARGET_IDS} diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_measure_simulation.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_measure_simulation.py index ff4c6608a5..13e086b734 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_measure_simulation.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_measure_simulation.py @@ -2527,6 +2527,7 @@ def __init__(self, *, dataset): "carer_support_payment", "scottish_carer_supplement", "total_income", + "adjusted_net_income", "income_tax", "income_tax_before_winter_fuel_payment_charge", "basic_rate_savings_income", @@ -2601,6 +2602,9 @@ def calculate(self, variable, year, map_to=None): ) if variable == "total_income": return total + if variable == "adjusted_net_income": + # No pension contributions or Gift Aid in the stub: ANI is total. + return total # No stub person passes the Winter Fuel Payment charge's income test. if variable in ("income_tax", "income_tax_before_winter_fuel_payment_charge"): return 0.2 * np.maximum(total - 12_570.0, 0.0) @@ -2677,6 +2681,9 @@ def test_annual_measures_read_each_persons_year(monkeypatch, tmp_path): np.testing.assert_allclose(total, annual_total) tax, _ = resolver.compute("person", "income_tax_annual") np.testing.assert_allclose(tax, 0.2 * np.maximum(annual_total - 12_570.0, 0.0)) + # CenTax's parent cells read the year's ANI (microcosm#1399). + ani, _ = resolver.compute("person", "adjusted_net_income_annual") + np.testing.assert_allclose(ani, annual_total) band, _ = resolver.compute("person", "tax_band_annual") assert list(band) == ["BASIC", "BASIC", "BASIC"] # The current measures are untouched, and one annual simulation serves all. @@ -2827,3 +2834,204 @@ def test_no_committed_exclusion_is_about_to_lapse(): f"{earliest.isoformat()}, in {days_left} day(s); every UK national " "refuses them from the next day." ) + + +# CenTax's parent cells (microcosm#1399): the parent of an age-eligible 3- or +# 4-year-old, and employment as the year's main income source. + + +def _centax_parent_simulation() -> SimulationStub: + # Person 1 is an adult in unit 10 with person 2, a DfE-age-3 child before + # school all year; person 3 is a DfE-age-4 child in reception for two + # terms, alone in unit 20, so it has no adult to mark. + simulation = _spring_term_simulation() + simulation.values["is_hbai_dependent_child"] = ( + "person", + np.array([False, True, True]), + ) + # The engine declares country on the household; the stub serves it at + # person grain, which the resolver reads natively. + simulation.values["country"] = ("person", np.array(["ENGLAND"] * 3)) + return SimulationStub(simulation.values) + + +def test_the_centax_parent_measure_marks_the_adults_of_eligible_units(): + from microcosm.build.uk_runtime.centax_childcare_parents import ( + CENTAX_EMPLOYEE_MAIN_SOURCE, + CENTAX_PARENT_OF_ELIGIBLE_3_4, + ) + + frame, simulation = FrameStub(), _centax_parent_simulation() + values, route = compute_uk_measure_input( + frame, simulation, "person", CENTAX_PARENT_OF_ELIGIBLE_3_4, 2025 + ) + assert values.tolist() == [1.0, 0.0, 0.0] + assert route == f"engine_terms_and_benunit_roles:{CENTAX_PARENT_OF_ELIGIBLE_3_4}" + with pytest.raises(KeyError, match="person-only"): + compute_uk_measure_input( + frame, simulation, "household", CENTAX_PARENT_OF_ELIGIBLE_3_4, 2025 + ) + # The main-source measure needs the annual measures, so only the resolver + # computes it. + with pytest.raises(KeyError, match="UKMeasureResolver"): + compute_uk_measure_input( + frame, simulation, "person", CENTAX_EMPLOYEE_MAIN_SOURCE, 2025 + ) + + +def test_the_resolver_routes_the_centax_parent_measure_to_people( + monkeypatch, tmp_path: Path +): + from microcosm.build.uk_runtime.centax_childcare_parents import ( + CENTAX_PARENT_OF_ELIGIBLE_3_4, + ) + + resolver = _resolver_over(_centax_parent_simulation(), monkeypatch, tmp_path) + assert resolver.entity_for(CENTAX_PARENT_OF_ELIGIBLE_3_4) == "person" + assert resolver.knows("person", CENTAX_PARENT_OF_ELIGIBLE_3_4) + assert not resolver.knows("household", CENTAX_PARENT_OF_ELIGIBLE_3_4) + partial = _centax_parent_simulation() + del partial.tax_benefit_system.variables["is_hbai_dependent_child"] + resolver = _resolver_over(partial, monkeypatch, tmp_path) + assert not resolver.knows("person", CENTAX_PARENT_OF_ELIGIBLE_3_4) + + +@pytest.mark.parametrize( + "column", + ["centax_parent_of_eligible_3_4_year_old", "centax_employment_main_income_source"], +) +def test_a_persisted_centax_column_is_refused(monkeypatch, tmp_path: Path, column): + frame = FrameStub() + frame._tables["person"][column] = [1.0, 0.0, 0.0] + monkeypatch.setitem( + sys.modules, + "policyengine_uk", + SimpleNamespace(__version__="9.9.9", Microsimulation=lambda *, dataset: None), + ) + with pytest.raises(ValueError, match="must not be persisted"): + UKMeasureResolver( + simulation_source=tmp_path / "input.h5", + scratch_dir=tmp_path, + year=2025, + frame=frame, + ) + + +class _CenTaxAnnualSimulation(_AnnualSimulation): + """The annual stub with the year's unearned income and remaining benefits.""" + + unearned = { + "property_income": np.array([0.0, 0.0, 20_000.0]), + "dividend_income": np.array([1_000.0, 12_000.0, 0.0]), + "savings_interest_income": np.array([0.0, 0.0, 0.0]), + "other_investment_income": np.array([0.0, 0.0, 0.0]), + "taxable_miscellaneous_income": np.array([0.0, 0.0, 0.0]), + "incapacity_benefit": np.array([0.0, 0.0, 0.0]), + "widowed_parents_allowance": np.array([0.0, 0.0, 0.0]), + } + + def __init__(self, *, dataset): + super().__init__(dataset=dataset) + for name, values in self.unearned.items(): + self.stored[(name, 2025)] = values + self.tax_benefit_system.variables[name] = SimpleNamespace( + entity=SimpleNamespace(key="person"), value_type=float + ) + + +def test_the_main_source_measure_compares_the_years_sources(monkeypatch, tmp_path): + from microcosm.build.uk_runtime.centax_childcare_parents import ( + CENTAX_EMPLOYEE_MAIN_SOURCE, + ) + + monkeypatch.setitem( + sys.modules, + "policyengine_uk", + SimpleNamespace(__version__="9.9.9", Microsimulation=_CenTaxAnnualSimulation), + ) + resolver = UKMeasureResolver( + simulation_source=tmp_path / "input.h5", + scratch_dir=tmp_path, + year=2025, + frame=_AnnualFrameStub(), + ) + assert resolver.entity_for(CENTAX_EMPLOYEE_MAIN_SOURCE) == "person" + assert resolver.knows("person", CENTAX_EMPLOYEE_MAIN_SOURCE) + assert not resolver.knows("household", CENTAX_EMPLOYEE_MAIN_SOURCE) + employee, route = resolver.compute("person", CENTAX_EMPLOYEE_MAIN_SOURCE) + # Person 1's pay and company car benefit are the largest source; person 2's + # year's pay (9,450) is below its dividends, and person 3's pay and car + # benefit (12,500) below its rents. + assert employee.tolist() == [1.0, 0.0, 0.0] + assert route.startswith( + "annual_income_sources:employment_income_with_benefits_in_kind_annual," + ) + + +class _CenTaxInvestorSimulation(_CenTaxAnnualSimulation): + """Person 1's other investment income (SPI ``OTHERINV``) outranks its pay.""" + + unearned = { + **_CenTaxAnnualSimulation.unearned, + "other_investment_income": np.array([100_000.0, 0.0, 0.0]), + } + + +def test_the_main_source_measure_reads_other_investment_income(monkeypatch, tmp_path): + from microcosm.build.uk_runtime.centax_childcare_parents import ( + CENTAX_EMPLOYEE_MAIN_SOURCE, + ) + + monkeypatch.setitem( + sys.modules, + "policyengine_uk", + SimpleNamespace(__version__="9.9.9", Microsimulation=_CenTaxInvestorSimulation), + ) + resolver = UKMeasureResolver( + simulation_source=tmp_path / "input.h5", + scratch_dir=tmp_path, + year=2025, + frame=_AnnualFrameStub(), + ) + employee, route = resolver.compute("person", CENTAX_EMPLOYEE_MAIN_SOURCE) + # Person 1's year's pay and car benefit (34,500) are below its 100,000 of + # other investment income, so it is not an employee. + assert employee.tolist() == [0.0, 0.0, 0.0] + assert "other_investment_income" in route.split(":", 1)[1].split(",") + + +class _CenTaxClaimantSimulation(_CenTaxAnnualSimulation): + """Person 2 drew contributory ESA for a quarter of the year, and has no dividends.""" + + unearned = { + **_CenTaxAnnualSimulation.unearned, + "dividend_income": np.array([1_000.0, 0.0, 0.0]), + } + + def __init__(self, *, dataset): + super().__init__(dataset=dataset) + self.stored[("esa_contrib_reported", 2024)] = np.array([0.0, 9_500.0, 0.0]) + + +def test_the_main_source_measure_reads_the_years_contributory_benefits( + monkeypatch, tmp_path +): + from microcosm.build.uk_runtime.centax_childcare_parents import ( + CENTAX_EMPLOYEE_MAIN_SOURCE, + ) + + monkeypatch.setitem( + sys.modules, + "policyengine_uk", + SimpleNamespace(__version__="9.9.9", Microsimulation=_CenTaxClaimantSimulation), + ) + resolver = UKMeasureResolver( + simulation_source=tmp_path / "input.h5", + scratch_dir=tmp_path, + year=2025, + frame=_AnnualFrameStub(), + ) + employee, _route = resolver.compute("person", CENTAX_EMPLOYEE_MAIN_SOURCE) + # Person 2's current ESA (9,690) is above its year's pay (9,450), but it was + # paid for a quarter of the year (2,422.50), so pay is its main source. + assert employee.tolist() == [1.0, 1.0, 0.0] diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_measurement_period.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_measurement_period.py index 7beebf180b..6b78a0e12d 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_measurement_period.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_measurement_period.py @@ -35,6 +35,7 @@ resolve_target_measures, ) from microcosm.build.uk_runtime import measure_simulation +from microcosm.build.uk_runtime.centax_childcare_parents import CENTAX_PARENT_MEASURES from microcosm.build.uk_runtime.hmrc_income import ( LOSS_RELIEF_COLUMN, self_employment_income_after_loss_relief, @@ -947,6 +948,11 @@ def test_a_frame_without_a_period_label_keeps_the_frame_route(): # resolver computes each on its annual simulation at the calibration # period. *measure_simulation.UK_ANNUAL_INCOME_MEASURES, + # The CenTax parent measures: the frame may not store them (the + # resolver refuses them as inputs). The resolver computes the parent + # flag from the engine's term shares at the calibration period and the + # main income source from the annual measures. + *CENTAX_PARENT_MEASURES, } ) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_population_targets.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_population_targets.py index e1b911df5b..2aa9414198 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_population_targets.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_population_targets.py @@ -290,8 +290,10 @@ def test_uk_population_targets_shape_order_and_registry_accounting() -> None: # adds RTI's pay of employees aged 18 to 24 and England's PIP cases aged 16 # to 24 at each component's enhanced rate, three rows held out as checks # (María's go of 2026-11-18), and DWP's young people with the UC health - # element in England and Wales, bound (part 3 of #1663). - assert len(resource["targets"]) == 657 + # element in England and Wales, bound (part 3 of #1663). microcosm#1399 + # adds CenTax's five parent cells on the national line (its non-employee + # cell is a diagnostic, María's ruling of 2026-11-24). + assert len(resource["targets"]) == 662 providers = resource["hierarchy"]["providers"] categories = resource["hierarchy"]["categories"] @@ -305,10 +307,10 @@ def test_uk_population_targets_shape_order_and_registry_accounting() -> None: target_ids = [target["target_id"] for target in resource["targets"]] registry_scope = resource["registry_parity"]["scope_target_ids"] profile_scope = resource["profile_parity"]["scope_target_ids"] - assert len(registry_scope) == 595 + assert len(registry_scope) == 600 assert len(profile_scope) == 62 - assert target_ids[:595] == registry_scope - assert target_ids[595:] == profile_scope + assert target_ids[: len(registry_scope)] == registry_scope + assert target_ids[len(registry_scope) :] == profile_scope parity = resource["registry_parity"] assert parity["pinned_ref"] == "12a1e028afeef08d8b2d74ee03fd9de3a78b2dd3" @@ -347,9 +349,10 @@ def test_uk_population_targets_shape_order_and_registry_accounting() -> None: # years 16 to 24 have no uk-data metric, in place of the four 16-17 and # 18-19 rows (microcosm#1095). PolicyEngine/microcosm#1663's RTI pay row and # two England PIP award-by-age rows have no uk-data metric either, nor its - # young UC health element row. + # young UC health element row, nor microcosm#1399's five CenTax parent + # cells. assert len(mapped_target_ids) == 183 - assert len(unmapped_declarations) == 412 + assert len(unmapped_declarations) == 417 suppressed_ancestors = parity["suppressed_ancestors"] assert len(suppressed_ancestors) == 5 assert set(suppressed_ancestors).isdisjoint(parity["mapped"]) @@ -874,7 +877,7 @@ def test_uk_population_targets_have_unique_target_ids() -> None: resource = _load() target_ids = [target["target_id"] for target in resource["targets"]] - assert len(target_ids) == 657 + assert len(target_ids) == 662 assert len(target_ids) == len(set(target_ids)) @@ -1384,7 +1387,7 @@ def test_uc_payment_bands_share_administrative_family_but_keep_source_window() - def test_paid_joint_diagnostics_do_not_add_active_targets() -> None: targets = _load()["targets"] - assert len(targets) == 657 + assert len(targets) == 662 assert not any( f.get("variable") == "uc_calibration_child_entitlement" for target in targets diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_target_references.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_target_references.py index 46e5dca353..79232a181e 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_target_references.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_target_references.py @@ -144,8 +144,10 @@ # PolicyEngine/microcosm#1663: RTI's pay of employees aged 18 to 24 and # England's PIP cases aged 16 to 24 at each component's enhanced rate, three # checks held out of the solve, and DWP's young people with the UC health -# element in England and Wales (Table 28), bound -ACTIVE_REFERENCE_COUNT = 1714 +# element in England and Wales (Table 28), bound; microcosm#1399: + 5, CenTax's +# parent cells of age-eligible 3- and 4-year-olds in England (its non-employee +# cell is a diagnostic, María's ruling of 2026-11-24) +ACTIVE_REFERENCE_COUNT = 1719 REGION_TIER_LEVEL = {code: level for level, code in UK_REGION_TIER} diff --git a/tools/build_uk_centax_childcare_parent_facts.py b/tools/build_uk_centax_childcare_parent_facts.py new file mode 100644 index 0000000000..82ef75ee35 --- /dev/null +++ b/tools/build_uk_centax_childcare_parent_facts.py @@ -0,0 +1,550 @@ +#!/usr/bin/env python +"""Build uk/centax_childcare_parent_facts.json from CenTax's registered workbook. + +Advani, Flew, Pepin-Hall and Summers (CenTax, September 2026), *Removing the +£100,000 childcare cliff-edge*, publish their data for the charts as +``AdvaniFlewPepinhallSummers2026_ChildcareThreshold_data.xlsx``, which Chronicle +registers raw-only as ``centax-childcare-cliff-edge-2026``. This tool checks a +local copy of the workbook against that registration's pins +(``microcosm.build.pinned_inputs``), reads Figures 3.1, 3.6 and 3.7 from it and +writes five derived facts (see ``uk_runtime/centax_childcare_parents.py``): +three ANI band shares of the parents in (£50k, £200k], and two splits of the +parents in (£80k, £150k], each times ``parent_count``. + +``parent_count`` is the baseline build's own number of parents in the aged +(£50k, £200k] at the calibration year, read from the JSON +``tools/diagnose_uk_centax_parents.py`` writes on the baseline H5; the resource +records that build and its H5's SHA-256. The uprating that ages the 2021-22 +edges is the installed policyengine-uk's OBR average earnings index, which must +agree with the diagnostics'. + +Never read into the resource: CenTax's model outputs (Tables 3.1, 3.2 and 4.1, +the frictions, elasticities, marginal bunchers and every cost) and the figures +kept as diagnostics (Table A.1's levels, Figures 2.1 and 3.12, the band below +£50k, the region groups outside London and Figure 3.3's non-employees), which the +diagnostic reads from the registered workbook itself. + + uv run --no-sync python tools/build_uk_centax_childcare_parent_facts.py \\ + --manifest /db/data/centax/childcare_cliff_edge_2026/manifest.yaml \\ + --workbook AdvaniFlewPepinhallSummers2026_ChildcareThreshold_data.xlsx \\ + --baseline-diagnostics centax_parents__2025.json --built-on YYYY-MM-DD +""" + +from __future__ import annotations + +import argparse +import hashlib +import importlib.metadata +import json +from collections.abc import Mapping, Sequence +from pathlib import Path +from typing import Any + +import openpyxl + +from microcosm.build import pinned_inputs +from microcosm.build.uk_runtime.centax_childcare_parents import ( + CENTAX_ANI_BANDS_2022, + CENTAX_BOUND_REGION_GROUPS, + CENTAX_CHRONICLE_PACKAGE_ID, + CENTAX_CHRONICLE_SOURCE_ID, + CENTAX_DATA_TAX_YEAR, + CENTAX_DERIVED_FACT_KEY_PREFIX, + CENTAX_FACTS_RESOURCE, + CENTAX_REGION_GROUPS, + CENTAX_REPORT_URL, + CENTAX_SHARE_BASE_2022, + CENTAX_SPLIT_BAND_2022, + CENTAX_SPLITS, + CENTAX_WORKBOOK_FILENAME, + CENTAX_WORKBOOK_SHA256, + RESOURCE_KIND, + RESOURCE_SCHEMA_VERSION, + ROW_SCHEMA_VERSION, + aged_edges, + centax_ani_uprating, + centax_cell_ids, + load_uk_centax_childcare_parent_facts, + model_ani_edges, + rows_sha256, +) + +GENERATOR = { + "tool": "tools/build_uk_centax_childcare_parent_facts.py", + "version": "uk-centax-childcare-parents-v2", +} +#: The diagnostics schema whose ``parent_count`` this tool scales by. +DIAGNOSTICS_SCHEMA = "microcosm.uk.centax_parent_diagnostics.v2" +DEFAULT_OUT = ( + Path(__file__).resolve().parents[1] + / "packages/microcosm-build/src/microcosm/build/uk" + / CENTAX_FACTS_RESOURCE +) +#: Sheet, expected header row (from column B) and the bin step in pounds. The +#: bins are labelled by their upper edge: Figure 3.1's labels run from 500 to +#: 200,000, so its first bin is (0, £500] and its last ends at the figure's +#: top; the workbook does not say so in words. The report's notes give £1,000 +#: bins for Figures 3.1 and 3.6, but their sheets hold £500 bins and say the +#: report's charts aggregate them. Every band edge here falls on a bin edge of +#: every figure, so a cell sums whole bins; read by lower edges, each cell +#: would move by one bin at each end. +SHEETS: Mapping[str, tuple[tuple[str, ...], int]] = { + "Fig. 3.1": (("Income Bin (ANI)", "Number of Taxpayer in Income Bin"), 500), + "Fig. 3.3": ( + ( + "Income Bin (ANI)", + "Number of Taxpayers in Income Bin (Employees)", + "Number of Taxpayers in Income Bin (Non-Employees)", + ), + 1000, + ), + "Fig. 3.6": ( + ( + "Income Bin (ANI)", + "Number of Taxpayers in Income Bin (Males)", + "Number of Taxpayers in Income Bin (Females)", + ), + 500, + ), + "Fig. 3.7": ( + ( + "Income Bin (ANI)", + "Number of Taxpayers in Income Bin (London)", + "Number of Taxpayers in Income Bin (North and Midlands)", + "Number of Taxpayers in Income Bin (South excl. London)", + "Number of Taxpayers in Income Bin (Scotland)", + ), + 1000, + ), +} +#: Figure 3.7's English columns, by region group. +FIG_3_7_COLUMN = { + "london": "Number of Taxpayers in Income Bin (London)", + "north_and_midlands": "Number of Taxpayers in Income Bin (North and Midlands)", + "south_excl_london": "Number of Taxpayers in Income Bin (South excl. London)", +} +_CELL_LABELS = { + "ani_50k_to_80k": "ANI over £50,000 to £80,000", + "ani_80k_to_120k": "ANI over £80,000 to £120,000", + "ani_120k_to_200k": "ANI over £120,000 to £200,000", + "female_ani_80k_to_150k": "women, ANI over £80,000 to £150,000", + "london_ani_80k_to_150k": "London, ANI over £80,000 to £150,000", +} +_CELL_FIGURES = { + **{band: "Fig. 3.1" for band, _, _ in CENTAX_ANI_BANDS_2022}, + **{f"{split}_ani_80k_to_150k": figure for split, figure in CENTAX_SPLITS}, +} +SOURCE_MEASURE_ID = "parents_of_eligible_3_4_year_olds" +SOURCE_CONCEPT = "microcosm.centax_childcare_parents.count" +#: The tax year the cells count, which policyengine-uk dates 2025 (the period +#: value the compile matches at the calibration year). +_TAX_YEAR_START = "{year}-04-06" +_TAX_YEAR_END = "{next_year}-04-05" + + +def open_registered_workbook( + manifest_path: Path, workbook_path: Path +) -> tuple[Any, dict[str, Any], dict[str, str], dict[str, Any]]: + """The workbook, checked against its Chronicle registration. + + Returns the open workbook, the registration record a resource stores + (``pinned_inputs.registration``), the licence the manifest states and the + manifest itself. Refuses a manifest of another package or kind, or a file + whose bytes are not the registered ones. + """ + + manifest, files = pinned_inputs.manifest_files(manifest_path) + if ( + manifest.get("package_id") != CENTAX_CHRONICLE_PACKAGE_ID + or manifest.get("source_id") != CENTAX_CHRONICLE_SOURCE_ID + ): + raise ValueError( + f"{manifest_path} is not the {CENTAX_CHRONICLE_PACKAGE_ID} registration." + ) + if manifest.get("registration_kind") != "raw_only" or len(files) != 1: + raise ValueError(f"{manifest_path} must register one raw-only workbook.") + ((key, entry),) = files.items() + verified = pinned_inputs.verify_pinned_file(workbook_path, entry) + if ( + verified["sha256"] != CENTAX_WORKBOOK_SHA256 + or verified["filename"] != CENTAX_WORKBOOK_FILENAME + ): + raise ValueError( + f"{manifest_path} does not register the workbook this module pins." + ) + registration = pinned_inputs.registration(manifest, {key: verified}) + licence = pinned_inputs.licence_of(manifest) + workbook = openpyxl.load_workbook(workbook_path, read_only=True, data_only=True) + return workbook, registration, licence, manifest + + +def read_series(workbook: Any, sheet: str) -> dict[str, dict[int, float]]: + """A figure's columns by header, each a map from bin upper edge to count. + + Refuses a sheet whose header differs from the one this tool was written + against, a non-numeric cell inside the bins, or bins that are not one + step apart from the first step to the last. + """ + + header, step = SHEETS[sheet] + rows = list(workbook[sheet].iter_rows(values_only=True)) + try: + start = next( + index + for index, row in enumerate(rows) + if tuple(row[1 : 1 + len(header)]) == header + ) + except StopIteration: + raise ValueError(f"{sheet}: header {header!r} not found.") from None + series: dict[str, dict[int, float]] = {column: {} for column in header[1:]} + labels: list[int] = [] + for row in rows[start + 1 :]: + label = row[1] + if label is None: + continue + if not isinstance(label, (int, float)) or isinstance(label, bool): + raise ValueError(f"{sheet}: non-numeric bin label {label!r}.") + labels.append(int(label)) + for offset, column in enumerate(header[1:], start=2): + value = row[offset] + if not isinstance(value, (int, float)) or isinstance(value, bool): + raise ValueError(f"{sheet}: bin {label} {column} is {value!r}.") + series[column][int(label)] = float(value) + if labels != list(range(step, labels[-1] + step, step)): + raise ValueError(f"{sheet}: bins are not every £{step} from £{step}.") + return series + + +def band_sum(series: Mapping[int, float], lower: float, upper: float) -> float: + """Sum of the bins whose upper edge is in (lower, upper].""" + + return float( + sum(value for label, value in series.items() if lower < label <= upper) + ) + + +def within_split_band( + columns: Mapping[str, Mapping[int, float]], numerator: str +) -> float: + """``numerator``'s share of the columns' parents in (£80k, £150k].""" + + lower, upper = CENTAX_SPLIT_BAND_2022 + whole = sum(band_sum(column, lower, upper) for column in columns.values()) + return band_sum(columns[numerator], lower, upper) / whole + + +def england_region_columns(workbook: Any) -> dict[str, dict[int, float]]: + """Figure 3.7's English columns by region group (Scotland left out).""" + + fig37 = read_series(workbook, "Fig. 3.7") + columns = {group: fig37[column] for group, column in FIG_3_7_COLUMN.items()} + if set(columns) != set(CENTAX_REGION_GROUPS): + raise ValueError("Fig. 3.7 groups differ from the module's region groups.") + return columns + + +def centax_shares(workbook: Any) -> tuple[dict[str, float], float]: + """Each bound cell's share of the parents in (£50k, £200k], and the split band's.""" + + fig31 = read_series(workbook, "Fig. 3.1")["Number of Taxpayer in Income Bin"] + fig36 = read_series(workbook, "Fig. 3.6") + regions = england_region_columns(workbook) + base_lower, base_upper = CENTAX_SHARE_BASE_2022 + if max(fig31) != base_upper: + raise ValueError(f"Fig. 3.1 ends at £{max(fig31)}, not £{base_upper:,.0f}.") + base = band_sum(fig31, base_lower, base_upper) + shares = { + band: band_sum(fig31, lower, upper) / base + for band, lower, upper in CENTAX_ANI_BANDS_2022 + } + split_share = band_sum(fig31, *CENTAX_SPLIT_BAND_2022) / base + split_within = { + "female": within_split_band( + fig36, "Number of Taxpayers in Income Bin (Females)" + ), + **{ + group: within_split_band(regions, group) + for group in CENTAX_BOUND_REGION_GROUPS + }, + } + for split, _ in CENTAX_SPLITS: + shares[f"{split}_ani_80k_to_150k"] = split_share * split_within[split] + return shares, split_share + + +def fact_row( + *, + cell: str, + value: float, + period: str, + edges: Sequence[int], + inputs_sha256: str, + vintage: str, +) -> dict[str, Any]: + record_set_spec_id = f"uk.centax_childcare_parents.{cell}.v1" + identity = { + "record_set_spec_id": record_set_spec_id, + "period": period, + "inputs_sha256": inputs_sha256, + "method": GENERATOR["version"], + } + digest = hashlib.sha256( + json.dumps(identity, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest()[:24] + label = ( + "Parents of age-eligible 3- and 4-year-olds, " + f"{_CELL_LABELS[cell]} (2021-22 pounds), England" + ) + tax_year = f"{period}-{(int(period) + 1) % 100:02d}" + return { + "schema_version": ROW_SCHEMA_VERSION, + "aggregate_fact_key": CENTAX_DERIVED_FACT_KEY_PREFIX + digest, + "semantic_fact_key": ( + "microcosm.semantic_fact.centax_childcare_parents.v1:" + digest + ), + "value": float(round(value, 3)), + "value_type": "float", + "assertion": "observation", + "provenance_class": "derived_administrative", + "period": {"type": "calendar_year", "value": period}, + "period_coverage": { + "start_date": _TAX_YEAR_START.format(year=period), + "end_date": _TAX_YEAR_END.format(next_year=int(period) + 1), + "basis": "flow", + "notes": ( + f"The {tax_year} tax year's ANI, which policyengine-uk dates " + f"{period}, the period value. CenTax's share for tax year " + f"{CENTAX_DATA_TAX_YEAR} times the baseline build's parents at " + f"{period}; the ANI edges are aged to {period} pounds " + f"({edges[0]:,} to {edges[1]:,})." + ), + }, + "geography": { + "level": "country", + "id": "E92000001", + "vintage": "current", + "name": "England", + }, + "entity": {"name": "person", "role": "parent"}, + "aggregation": {"method": "sum"}, + "observed_measure": { + "source_concept": SOURCE_CONCEPT, + "source_measure_id": SOURCE_MEASURE_ID, + "unit": "count", + }, + "measure": {"unit": "count"}, + "concept_alignment": { + "source_concept": SOURCE_CONCEPT, + "canonical_concept": "uk.person.count", + "relation": "derived", + }, + "dimensions": {"microcosm.centax_cell": cell}, + "dimension_labels": { + "microcosm.centax_cell": "CenTax parent cell (2021-22 ANI pounds)" + }, + "dimension_value_labels": {"microcosm.centax_cell": {cell: _CELL_LABELS[cell]}}, + "source": { + "source_name": "microcosm", + "source_table": ( + f"CenTax, Removing the £100,000 childcare cliff-edge (2026), " + f"{_CELL_FIGURES[cell]} (Chronicle {CENTAX_CHRONICLE_PACKAGE_ID}); " + "Microcosm derivation" + ), + "source_file": CENTAX_FACTS_RESOURCE, + "vintage": vintage, + "source_sha256": inputs_sha256, + "url": CENTAX_REPORT_URL, + }, + "lineage": {"source_record_id": f"microcosm.centax_childcare_parents.{cell}"}, + "layout": { + "record_set_id": f"uk.centax_childcare_parents.{cell}", + "record_set_spec_id": record_set_spec_id, + "measure_id": SOURCE_MEASURE_ID, + }, + "label": label, + } + + +def check_baseline( + baseline: Mapping[str, Any], *, calibration_year: int, uprating: float +) -> None: + """Refuse diagnostics that are not this engine's, at this year and range.""" + + if baseline.get("schema") != DIAGNOSTICS_SCHEMA: + raise ValueError( + f"the baseline diagnostics are {baseline.get('schema')!r}, not " + f"{DIAGNOSTICS_SCHEMA!r}." + ) + if int(baseline["year"]) != calibration_year: + raise ValueError( + f"the baseline diagnostics are at {baseline['year']}, not {calibration_year}." + ) + if baseline["model_ani_edges"] != model_ani_edges(uprating): + raise ValueError("the baseline diagnostics were banded on other ANI edges.") + if abs(float(baseline["ani_uprating"]) - uprating) > 1e-12: + raise ValueError("the baseline diagnostics used another ANI uprating.") + if baseline["parent_count_range"] != aged_edges(*CENTAX_SHARE_BASE_2022, uprating): + raise ValueError( + "the baseline diagnostics counted parents over another ANI range." + ) + installed = importlib.metadata.version("policyengine-uk") + measured = (baseline.get("resolver") or {}).get("policyengine_uk_version") + if measured != installed: + raise ValueError( + f"the baseline diagnostics ran policyengine-uk {measured}, not the " + f"installed {installed}." + ) + + +def build_resource( + *, + manifest_path: Path, + workbook_path: Path, + baseline: Mapping[str, Any], + calibration_year: int, + uprating: float, + built_on: str, +) -> dict[str, Any]: + workbook, registration, licence, manifest = open_registered_workbook( + manifest_path, workbook_path + ) + check_baseline(baseline, calibration_year=calibration_year, uprating=uprating) + edges = model_ani_edges(uprating) + shares, split_share = centax_shares(workbook) + parent_count = float(baseline["parent_count"]) + vintage = _registered_vintage(manifest_path) + inputs = { + "workbook": { + **registration, + "source_page": manifest.get("source_page"), + "licence": licence, + "report_url": CENTAX_REPORT_URL, + "figures": ["Fig. 3.1", "Fig. 3.6", "Fig. 3.7"], + }, + "baseline": { + "dataset": baseline["dataset"], + "sha256": baseline["dataset_sha256"], + "diagnostics_schema": baseline["schema"], + "policyengine_uk_version": baseline["resolver"]["policyengine_uk_version"], + }, + "method": GENERATOR["version"], + } + inputs_sha256 = hashlib.sha256( + json.dumps(inputs, sort_keys=True).encode() + ).hexdigest() + period = str(calibration_year) + rows = [ + fact_row( + cell=cell, + value=shares[cell] * parent_count, + period=period, + edges=edges[cell], + inputs_sha256=inputs_sha256, + vintage=vintage, + ) + for cell in centax_cell_ids() + ] + rows.sort(key=lambda row: row["aggregate_fact_key"]) + base_edges = aged_edges(*CENTAX_SHARE_BASE_2022, uprating) + return { + "kind": RESOURCE_KIND, + "schema_version": RESOURCE_SCHEMA_VERSION, + "resource": CENTAX_FACTS_RESOURCE, + "description": ( + "Microcosm-derived counts of parents of age-eligible 3- and 4-year-olds in " + "England by adjusted net income, from CenTax's HMRC tabulations for " + f"{CENTAX_DATA_TAX_YEAR} (Advani, Flew, Pepin-Hall and Summers 2026, " + "Figures 3.1, 3.3, 3.6 and 3.7, from the workbook Chronicle registers as " + f"{CENTAX_CHRONICLE_PACKAGE_ID}): each published share of the parents " + "in (£50k, £200k] times the baseline build's own parents in that range. " + "No CenTax model output, and none of the figures kept as diagnostics." + ), + "built_on": built_on, + "generator": GENERATOR, + "licence": {"attribution": [str(licence.get("attribution", ""))]}, + "inputs": inputs, + "inputs_sha256": inputs_sha256, + "parameters": { + "calibration_year": calibration_year, + "ani_uprating": uprating, + "ani_uprating_basis": ( + "policyengine-uk gov.economic_assumptions.indices.obr.average_earnings, " + f"{calibration_year} over 2021" + ), + "share_base_2022": list(CENTAX_SHARE_BASE_2022), + "ani_bands_2022": { + band: [lower, upper] for band, lower, upper in CENTAX_ANI_BANDS_2022 + }, + "split_band_2022": list(CENTAX_SPLIT_BAND_2022), + "model_ani_edges": edges, + "parent_count": parent_count, + "parent_count_basis": ( + "baseline parents of age-eligible 3- and 4-year-olds with annual ANI in " + f"({base_edges[0]:,}, {base_edges[1]:,}] at {calibration_year}" + ), + "shares": shares, + "split_band_share": split_share, + "never_targets": [ + "Tables 3.1, 3.2 and 4.1 (bunching estimates)", + "friction parameters, elasticities and marginal bunchers", + "every fiscal cost", + ], + }, + "row_count": len(rows), + "rows_sha256": rows_sha256(rows), + "rows": rows, + } + + +def _registered_vintage(manifest_path: Path) -> str: + """The registered file's vintage (one file, checked by the opener).""" + + _, files = pinned_inputs.manifest_files(manifest_path) + return str(next(iter(files.values())).get("vintage") or "") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument( + "--manifest", + type=Path, + required=True, + help="Chronicle's manifest.yaml for centax-childcare-cliff-edge-2026", + ) + parser.add_argument( + "--workbook", + type=Path, + required=True, + help="a local copy of the registered workbook (checked against the manifest)", + ) + parser.add_argument("--baseline-diagnostics", type=Path, required=True) + parser.add_argument("--calibration-year", type=int, default=2025) + parser.add_argument("--out", type=Path, default=DEFAULT_OUT) + parser.add_argument( + "--built-on", + required=True, + help="build date recorded in the resource (YYYY-MM-DD), so a rerun reproduces it", + ) + args = parser.parse_args(argv) + baseline = json.loads(args.baseline_diagnostics.read_text(encoding="utf-8")) + resource = build_resource( + manifest_path=args.manifest, + workbook_path=args.workbook, + baseline=baseline, + calibration_year=args.calibration_year, + uprating=centax_ani_uprating(args.calibration_year), + built_on=args.built_on, + ) + rendered = json.dumps(resource, indent=2, sort_keys=True, ensure_ascii=True) + "\n" + args.out.write_text(rendered, encoding="utf-8") + facts = load_uk_centax_childcare_parent_facts(args.out) + print(f"wrote {args.out} ({len(facts.rows)} rows, {facts.rows_sha256[:12]})") + for cell in centax_cell_ids(): + print( + f"{cell:38s} share {facts.shares[cell]:.5f} value {facts.value(cell):>11,.0f}" + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/build_uk_ledger_compile_parity_signed_differences.py b/tools/build_uk_ledger_compile_parity_signed_differences.py index d04c0353f3..f7b61912b8 100644 --- a/tools/build_uk_ledger_compile_parity_signed_differences.py +++ b/tools/build_uk_ledger_compile_parity_signed_differences.py @@ -885,6 +885,21 @@ def _aligned_fixture(fixture: dict) -> dict: "(calibration_lines; microcosm#1301)." ) +#: microcosm#1399: CenTax's parent cells bind Microcosm-derived counts, each a +#: share CenTax published from HMRC's tabulations times the baseline build's +#: own parents, so the incumbent national register has no row to compare. +_CENTAX_PARENTS_PREFIX = "microcosm.centax_childcare_parents." +_CENTAX_PARENTS_LEDGER_ONLY_RATIONALE = ( + "ledger_only by construction: the row is a Microcosm-derived count of " + "parents of age-eligible 3- and 4-year-olds in England in one adjusted net " + "income cell: CenTax's share of HMRC's 2021-22 tabulation (Advani, Flew, " + "Pepin-Hall and Summers 2026, Figures 3.1, 3.3, 3.6 and 3.7) times the " + "baseline build's own parents (uk/centax_childcare_parent_facts.json), " + "compiled beside the Chronicle feed. The incumbent registry carries no " + "such row, so the difference is the derived target itself. The rows bind " + "on the national line only (calibration_lines; microcosm#1399)." +) + def _add_signed_rationale_notes( report: dict[str, object], @@ -907,6 +922,10 @@ def _add_signed_rationale_notes( and row.get("kind") == "ledger_only" ): row["reason"] = _HIGH_VALUE_HOMES_REGION_LEDGER_ONLY_RATIONALE + elif name.startswith(_CENTAX_PARENTS_PREFIX) and row.get("kind") == ( + "ledger_only" + ): + row["reason"] = _CENTAX_PARENTS_LEDGER_ONLY_RATIONALE elif name in _UC_PAID_WINDOW_NAMES: inherited_change = ( "PR #891 contract with #892 source-window averaging" @@ -1192,8 +1211,9 @@ def _add_local_signed_rationale_notes(report: dict[str, object]) -> None: def _compile_for_receipt(spec: ParityReceiptSpec, facts: list[dict]): if spec.surface == "national": - # The high-value homes region rows (microcosm#1301) select the - # derived facts too; the national compile carries every reference. + # The high-value homes region rows (microcosm#1301) and CenTax's parent + # cells (microcosm#1399) select the derived facts too; the national + # compile carries every reference. return compile_uk_target_registry( (*facts, *uk_derived_fact_rows()), target_period=spec.target_period, diff --git a/tools/certify_uk_release_cut.py b/tools/certify_uk_release_cut.py index 6739c5c85d..8ac1802706 100644 --- a/tools/certify_uk_release_cut.py +++ b/tools/certify_uk_release_cut.py @@ -278,8 +278,9 @@ def _run(args: argparse.Namespace, state: AttemptState) -> dict[str, object]: # producer keeps the partial registry and leaves the verdict to the gates. ledger_unsupported = {} # Microcosm-derived facts compile beside the feed: the high-value homes - # local cells (microcosm#1240) and region rows (microcosm#1301), and DESNZ's - # energy split onto constituencies (microcosm#1095). + # local cells (microcosm#1240) and region rows (microcosm#1301), DESNZ's + # energy split onto constituencies (microcosm#1095), and CenTax's parent + # cells (microcosm#1399). facts = (*artifact.facts, *uk_derived_fact_rows()) for period in _LEDGER_COMPILE_PARITY_PERIODS: compilation = compile_uk_target_registry(facts, target_period=period) diff --git a/tools/diagnose_uk_centax_parents.py b/tools/diagnose_uk_centax_parents.py new file mode 100644 index 0000000000..7180fe2c65 --- /dev/null +++ b/tools/diagnose_uk_centax_parents.py @@ -0,0 +1,489 @@ +#!/usr/bin/env python +"""Fit and support of the CenTax parent cells on a Microcosm UK national H5. + +Computes, through the production measure resolver at the calibration year, each +bound cell of ``uk/centax_childcare_parent_facts.json``: the model's weighted +parents, the records and households behind them, the Kish effective number of +households and the share of the cell's weight on its ten heaviest households, +each also over the FRS source households the Microcosm copies come from. +``parent_count`` (the parents in the aged (£50k, £200k]) is the number the facts +tool scales the CenTax shares by when this H5 is the baseline. + +It also reports what the targets leave unbound (Vahid's reviews of +microcosm#1399): + +- the parents at or below the aged £50k, and among them those with no + employment, self-employment or private pension income in the year, whom + HMRC's PAYE and Self Assessment data would not hold; +- the South excluding London and the North and Midlands, with the East of + England in either group, since Figure 3.7 does not say where it sits; +- the parents whose main income source is not employment (Figure 3.3), a cell + too thinly supported to bind (María's ruling of 24 November 2026). + +With ``--facts`` it reports each bound cell's target and relative error, and +the level check: this H5's ``parent_count`` against the resource's, within +``--level-tolerance``. With ``--manifest`` and ``--workbook`` (the Chronicle +registration and a local copy of the workbook) it reads CenTax's own figures +for those unbound cells and the comparators kept out of the resource: Table +A.1's levels and Figure 3.12's non-working partners. + +Writes aggregates only: no record-level values leave the H5. The output is a +local diagnostic: it carries support counts and concentration shares that are +not checked for publication. + + uv run --no-sync python tools/diagnose_uk_centax_parents.py \\ + --h5 microcosm_uk_2024_25.h5 --out diagnostics.json [--facts resource.json] \\ + [--manifest --workbook ] +""" + +from __future__ import annotations + +import argparse +import hashlib +import importlib.util +import json +import sys +import tempfile +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +import numpy as np + +from microcosm.build.uk_runtime.centax_childcare_parents import ( + CENTAX_ANI_MEASURE, + CENTAX_DIAGNOSTIC_BAND_2022, + CENTAX_EMPLOYEE_MAIN_SOURCE, + CENTAX_PARENT_OF_ELIGIBLE_3_4, + CENTAX_SHARE_BASE_2022, + CENTAX_SPLIT_BAND_2022, + aged_edges, + centax_ani_uprating, + centax_cell_filters, + centax_cell_ids, + centax_diagnostic_cell_ids, + centax_region_codes, + load_uk_centax_childcare_parent_facts, + model_ani_edges, +) +from microcosm.calibrate.geography_constants import UK_REGION_TIER_ENUM + +SCHEMA = "microcosm.uk.centax_parent_diagnostics.v2" +#: The nominal ANI the free hours and Tax-Free Childcare taper away above. +_CLIFF_GBP = 100_000.0 +_TOP_HOUSEHOLDS = 10 +#: The default level tolerance: a baseline whose parents in the share base +#: differ from the resource's by more than this needs the resource rebuilt. +DEFAULT_LEVEL_TOLERANCE = 0.02 +_REPO_ROOT = Path(__file__).resolve().parents[1] + + +def _builder(): + """The facts tool, for its registered-workbook reader.""" + + path = _REPO_ROOT / "tools/build_uk_centax_childcare_parent_facts.py" + spec = importlib.util.spec_from_file_location( + "build_uk_centax_childcare_parent_facts", path + ) + if spec is None or spec.loader is None: + raise RuntimeError(f"cannot import {path}") + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _support( + mask: np.ndarray, + person_weight: np.ndarray, + person_household: np.ndarray, + person_source: np.ndarray, +) -> dict[str, Any]: + """Weighted parents and the household support behind them. + + Microcosm copies an FRS household several times (the SPI, high-value-home + and CGT copies), and the copies of one source household are not + independent, so the support is also counted over source households: each + one's contribution is the weight of all its copies' parents in the cell. + """ + + households, members = np.unique(person_household[mask], return_counts=True) + count = float(person_weight[mask].sum()) + if not len(households): + return { + "model_count": 0.0, + "person_records": 0, + "households": 0, + "source_households": 0, + } + weight_by_household = dict( + zip(person_household[mask], person_weight[mask], strict=True) + ) + household_weight = np.asarray( + [weight_by_household[household] for household in households], dtype=float + ) + contribution = household_weight * members + heaviest = np.sort(contribution)[::-1][:_TOP_HOUSEHOLDS] + sources, source_of_person = np.unique(person_source[mask], return_inverse=True) + source_contribution = np.bincount(source_of_person, weights=person_weight[mask]) + heaviest_sources = np.sort(source_contribution)[::-1][:_TOP_HOUSEHOLDS] + return { + "model_count": count, + "person_records": int(mask.sum()), + "households": int(len(households)), + "kish_households": float( + household_weight.sum() ** 2 / (household_weight**2).sum() + ), + "kish_contributions": float(contribution.sum() ** 2 / (contribution**2).sum()), + "top10_household_share": float(heaviest.sum() / contribution.sum()), + "source_households": int(len(sources)), + "kish_source_households": float( + source_contribution.sum() ** 2 / (source_contribution**2).sum() + ), + "top10_source_share": float(heaviest_sources.sum() / source_contribution.sum()), + } + + +def _mask(columns: Mapping[str, np.ndarray], filters: list[Mapping[str, Any]]): + mask = np.ones(len(next(iter(columns.values()))), dtype=bool) + for predicate in filters: + values = columns[str(predicate["variable"])] + if "in" in predicate: + mask &= np.isin(values, predicate["in"]) + elif "equals" in predicate: + mask &= values == predicate["equals"] + elif predicate["operator"] == ">": + mask &= values.astype(float) > float(predicate["value"]) + elif predicate["operator"] == "<=": + mask &= values.astype(float) <= float(predicate["value"]) + else: + raise ValueError(f"unexpected predicate {dict(predicate)!r}") + return mask + + +def level_check( + parent_count: float, facts_parent_count: float, tolerance: float +) -> dict[str, Any]: + """This H5's parents in the share base against the resource's. + + The targets fix the bound bands' total at the resource's count, so a + baseline that has moved from it pulls the fit by the drift (Vahid's + review, item 2). Outside the tolerance, rebuild the resource on this H5. + """ + + if not facts_parent_count > 0 or not tolerance >= 0: + raise ValueError("the level check needs a positive count and tolerance.") + drift = parent_count / facts_parent_count - 1.0 + return { + "parent_count": parent_count, + "facts_parent_count": facts_parent_count, + "drift": drift, + "tolerance": tolerance, + "within_tolerance": bool(abs(drift) <= tolerance), + } + + +def workbook_comparators(workbook: Any) -> dict[str, Any]: + """CenTax's figures for the unbound cells and the diagnostics-only tables.""" + + builder = _builder() + fig31 = builder.read_series(workbook, "Fig. 3.1")[ + "Number of Taxpayer in Income Bin" + ] + fig33 = builder.read_series(workbook, "Fig. 3.3") + regions = builder.england_region_columns(workbook) + lower, upper = CENTAX_DIAGNOSTIC_BAND_2022[1:] + top = CENTAX_SHARE_BASE_2022[1] + table = list(workbook["Tab. A.1"].iter_rows(values_only=True)) + parents = next( + row + for row in table + if row[1] == "3- and 4-year-olds" and row[2] == "Number of Parents" + ) + female = next( + row + for row in table + if row[2] == "Share Female (%)" and table.index(row) < table.index(parents) + 5 + ) + fig312 = { + row[1]: row[2:5] + for row in workbook["Fig. 3.12"].iter_rows(values_only=True) + if isinstance(row[1], (int, float)) and not isinstance(row[1], bool) + } + split_lower, split_upper = CENTAX_SPLIT_BAND_2022 + in_band = [v for label, v in fig312.items() if split_lower < label <= split_upper] + return { + "fig_3_1_share_of_0_to_200k_at_or_below_50k": ( + builder.band_sum(fig31, lower, upper) / builder.band_sum(fig31, 0.0, top) + ), + "fig_3_3_non_employee_share_within_80k_to_150k": builder.within_split_band( + fig33, "Number of Taxpayers in Income Bin (Non-Employees)" + ), + "fig_3_7_shares_within_80k_to_150k": { + group: builder.within_split_band(regions, group) for group in regions + }, + "table_a1_3_4_year_olds": { + "parents_whole_population": parents[3], + "parents_80k_to_140k": parents[4], + "share_female_whole_population_pct": female[3], + "share_female_80k_to_140k_pct": female[4], + }, + "fig_3_12_non_working_partner_share_80k_to_150k_unweighted_bin_mean": { + # The figure gives shares, not counts, and its "Men & Women" column + # repeats "Men"; the denominator is parents with an identified partner. + "men": sum(values[1] for values in in_band) / len(in_band), + "women": sum(values[2] for values in in_band) / len(in_band), + }, + } + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--h5", type=Path, required=True) + parser.add_argument("--year", type=int, default=2025) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument( + "--facts", + type=Path, + default=None, + help="The derived-facts resource to compare against (default: none).", + ) + parser.add_argument("--label", default=None, help="Display name of the H5.") + parser.add_argument( + "--level-tolerance", type=float, default=DEFAULT_LEVEL_TOLERANCE + ) + parser.add_argument("--manifest", type=Path, default=None) + parser.add_argument("--workbook", type=Path, default=None) + args = parser.parse_args(argv) + if (args.manifest is None) != (args.workbook is None): + parser.error("--manifest and --workbook go together.") + + # The resolver modules load the engine; import them only to measure. + from microcosm.build.uk_runtime.measure_simulation import UKMeasureResolver + from microcosm.build.uk_runtime.national_frame import load_uk_national_frame + from microcosm.build.uk_runtime.support_floor import uk_household_source_ids + from microcosm.build.uk_runtime.weight_year import uk_engine_year_frame + + uprating = centax_ani_uprating(args.year) + edges = model_ani_edges(uprating) + facts = ( + None + if args.facts is None + else load_uk_centax_childcare_parent_facts(args.facts) + ) + if facts is not None and facts.parameters["model_ani_edges"] != edges: + raise SystemExit( + "the facts resource's edges are not this engine's at " + f"{args.year}: {facts.parameters['model_ani_edges']} vs {edges}" + ) + comparators = None + if args.manifest is not None: + workbook, registration, _licence, _manifest = ( + _builder().open_registered_workbook(args.manifest, args.workbook) + ) + comparators = { + "registration": registration, + **workbook_comparators(workbook), + } + + frame, _provenance = load_uk_national_frame(args.h5) + frame = uk_engine_year_frame(frame, simulation_year=args.year) + with tempfile.TemporaryDirectory() as scratch: + resolver = UKMeasureResolver( + simulation_source=args.h5, + scratch_dir=Path(scratch), + year=args.year, + frame=frame, + ) + + def person(name: str) -> np.ndarray: + return resolver.compute("person", name)[0] + + columns = { + CENTAX_PARENT_OF_ELIGIBLE_3_4: person(CENTAX_PARENT_OF_ELIGIBLE_3_4), + CENTAX_ANI_MEASURE: person(CENTAX_ANI_MEASURE).astype(float), + CENTAX_EMPLOYEE_MAIN_SOURCE: person(CENTAX_EMPLOYEE_MAIN_SOURCE), + "gender": person("gender").astype(str), + "region": person("region").astype(str), + } + current_ani = person("adjusted_net_income").astype(float) + work = person("employment_income_with_benefits_in_kind_annual").astype( + float + ) + person("self_employment_income_after_loss_relief_annual").astype(float) + pension = person("private_pension_income_annual").astype(float) + receipt = resolver.receipt() + + person_table = frame.table("person") + household_table = frame.table("household") + household_weight = dict( + zip( + household_table["household_id"].to_numpy(), + np.asarray(frame.weights_for("household").values, dtype=float), + strict=True, + ) + ) + person_household = person_table["person_household_id"].to_numpy() + source_of_household = dict( + zip( + household_table["household_id"].to_numpy(), + uk_household_source_ids(frame), + strict=True, + ) + ) + person_source = np.asarray( + [source_of_household[household] for household in person_household] + ) + person_benunit = person_table["person_benunit_id"].to_numpy() + person_weight = np.asarray( + [household_weight[household] for household in person_household], dtype=float + ) + + def support(mask: np.ndarray) -> dict[str, Any]: + return _support(mask, person_weight, person_household, person_source) + + parent = columns[CENTAX_PARENT_OF_ELIGIBLE_3_4] == 1 + ani = columns[CENTAX_ANI_MEASURE] + base_lower, base_upper = aged_edges(*CENTAX_SHARE_BASE_2022, uprating) + in_base = parent & (ani > base_lower) & (ani <= base_upper) + below_base = parent & (ani > 0) & (ani <= base_lower) + + cells: dict[str, Any] = {} + for cell in centax_cell_ids(): + entry = support(_mask(columns, centax_cell_filters(cell, edges[cell]))) + entry["model_ani_edges"] = edges[cell] + if facts is not None: + target = facts.value(cell) + entry["target"] = target + entry["relative_error"] = entry["model_count"] / target - 1.0 + cells[cell] = entry + + # The split cells the targets never bind, on the split band's edges. + diagnostic_cells: dict[str, Any] = {} + split_edges = aged_edges(*CENTAX_SPLIT_BAND_2022, uprating) + for cell in centax_diagnostic_cell_ids(): + diagnostic_cells[cell] = { + **support(_mask(columns, centax_cell_filters(cell, split_edges))), + "model_ani_edges": split_edges, + } + + # The region groups outside London, with the East of England in each. + split_lower, split_upper = aged_edges(*CENTAX_SPLIT_BAND_2022, uprating) + in_split = parent & (ani > split_lower) & (ani <= split_upper) + region_groups: dict[str, Any] = {} + for east_in in ("south_excl_london", "north_and_midlands"): + codes = centax_region_codes(east_in=east_in) + region_groups[f"east_in_{east_in}"] = { + group: { + "regions": list(group_codes), + **support( + in_split + & np.isin( + columns["region"], + [UK_REGION_TIER_ENUM[code] for code in group_codes], + ) + ), + } + for group, group_codes in codes.items() + } + + # Partners: the other adult of a two-adult benefit unit, non-working when + # the year's pay and profit are nil, as Figure 3.12 counts them. + partnered = np.zeros(len(parent), dtype=bool) + partner_not_working = np.zeros(len(parent), dtype=bool) + units: dict[Any, list[int]] = {} + for index in np.flatnonzero(parent): + units.setdefault(person_benunit[index], []).append(int(index)) + for members in units.values(): + if len(members) == 2: + first, second = members + partnered[members] = True + partner_not_working[first] = work[second] <= 0 + partner_not_working[second] = work[first] <= 0 + partner_shares = {} + for sex in ("MALE", "FEMALE"): + base = in_split & partnered & (columns["gender"] == sex) + partner_shares[sex.lower()] = { + "partnered_weight": float(person_weight[base].sum()), + "non_working_partner_share": float( + person_weight[base & partner_not_working].sum() + / max(person_weight[base].sum(), 1e-12) + ), + "person_records": int(base.sum()), + } + + parent_count = float(person_weight[in_base].sum()) + result: dict[str, Any] = { + "schema": SCHEMA, + "dataset": args.label or args.h5.name, + "dataset_sha256": _sha256(args.h5), + "year": args.year, + "ani_uprating": uprating, + "model_ani_edges": edges, + "parent_count_range": [base_lower, base_upper], + "parent_count": parent_count, + "parents": { + "all": support(parent), + "ani_not_positive": support(parent & (ani <= 0)), + "share_base": support(in_base), + "ani_0_to_50k": support(below_base), + # Vahid's review, item 1: parents HMRC's PAYE and Self Assessment + # data would not hold, with no earnings or private pension. + "ani_0_to_50k_without_pay_profit_or_private_pension": support( + below_base & (work <= 0) & (pension <= 0) + ), + "ani_above_top_edge": support(parent & (ani > base_upper)), + "annual_ani_over_100k": support(parent & (ani > _CLIFF_GBP)), + "current_ani_over_100k": support(parent & (current_ani > _CLIFF_GBP)), + }, + "cells": cells, + "diagnostic_cells": diagnostic_cells, + "region_groups": region_groups, + "partners_ani_80k_to_150k": partner_shares, + "resolver": { + "policyengine_uk_version": receipt.get("policyengine_uk_version"), + "annual_income_measures": receipt.get("annual_income_measures", {}).get( + "computed_measures" + ), + }, + } + if facts is not None: + result["facts_rows_sha256"] = facts.rows_sha256 + result["facts_baseline"] = dict(facts.baseline) + result["level_check"] = level_check( + parent_count, facts.parent_count, args.level_tolerance + ) + if comparators is not None: + result["centax_comparators"] = comparators + args.out.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n") + print(f"parent_count {parent_count:,.0f} in ({base_lower:,}, {base_upper:,}]") + for cell, entry in cells.items(): + line = ( + f"{cell:38s} {entry['model_count']:>11,.0f} rec {entry['person_records']:>5} " + f"kish {entry.get('kish_households', 0.0):7.1f} " + f"sources {entry['source_households']:>4} " + f"kish {entry.get('kish_source_households', 0.0):6.1f}" + ) + if "target" in entry: + line += ( + f" target {entry['target']:>11,.0f} err {entry['relative_error']:+.3f}" + ) + print(line) + if "level_check" in result: + check = result["level_check"] + print( + f"level drift {check['drift']:+.4f} (tolerance {check['tolerance']}): " + f"{'within' if check['within_tolerance'] else 'OUTSIDE'}" + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/evaluate_uk_incumbent_surface.py b/tools/evaluate_uk_incumbent_surface.py index 7ab650b1db..31bef10575 100644 --- a/tools/evaluate_uk_incumbent_surface.py +++ b/tools/evaluate_uk_incumbent_surface.py @@ -28,11 +28,9 @@ from microcosm.build.ledger_artifact import load_ledger_consumer_artifact from microcosm.build.uk_runtime import communal_residents +from microcosm.build.uk_runtime.derived_facts import uk_derived_fact_rows from microcosm.build.uk_runtime.frs_release import load_uk_frs_release from microcosm.build.uk_runtime.full_measure import resolve_uk_full_measures -from microcosm.build.uk_runtime.high_value_homes import ( - load_uk_high_value_home_stock_facts, -) from microcosm.build.uk_runtime.incumbent_surface_evaluation import ( GSS_REGION_CODES, classify_local_rows, @@ -146,9 +144,10 @@ def main(argv=None) -> int: ) period = int(load_uk_frs_release().calibration_year) # The dense candidate's own line binds the high-value homes region rows, - # which select the Microcosm-derived facts beside the feed (microcosm#1301). + # which select the Microcosm-derived facts beside the feed (microcosm#1301), + # and CenTax's parent cells, which select the second resource (microcosm#1399). compilation = compile_uk_target_registry( - (*artifact.facts, *load_uk_high_value_home_stock_facts().rows), + (*artifact.facts, *uk_derived_fact_rows()), target_period=period, ) if compilation.unsupported: diff --git a/tools/generate_uk_target_references.py b/tools/generate_uk_target_references.py index 0e0c4d308d..77fa0e084e 100644 --- a/tools/generate_uk_target_references.py +++ b/tools/generate_uk_target_references.py @@ -2,9 +2,9 @@ """Generate UK Ledger target references from the national contract. This is an offline authoring tool. It consumes an already-exported Ledger -consumer fact JSONL feed and the committed Microcosm-derived facts resource -(uk/high_value_home_stock_facts.json); it does not fetch data or contact -Chronicle. +consumer fact JSONL feed and the committed Microcosm-derived facts resources +(uk/high_value_home_stock_facts.json and uk/centax_childcare_parent_facts.json); +it does not fetch data or contact Chronicle. """ from __future__ import annotations @@ -24,6 +24,10 @@ author_target_references, target_references_resource, ) +from microcosm.build.uk_runtime.centax_childcare_parents import ( + CENTAX_FACTS_RESOURCE, + load_uk_centax_childcare_parent_facts, +) from microcosm.build.uk_runtime.chronicle_feed import ( require_uk_chronicle_feed_subset_row_contracts, ) @@ -115,11 +119,10 @@ def main() -> None: args = _parser().parse_args() - facts = [ - json.loads(line) - for line in args.ledger_facts.read_text().splitlines() - if line.strip() - ] + # Stream the lines: the feed is several GB, and reading it whole held its + # text and every line beside the parsed rows. + with args.ledger_facts.open(encoding="utf-8") as handle: + facts = [json.loads(line) for line in handle if line.strip()] # The rows of a subset of the pinned feed: each row contract must be one # the committed pin lists and chronicle_epoch declares. require_uk_chronicle_feed_subset_row_contracts( @@ -134,15 +137,22 @@ def main() -> None: # Microcosm-derived facts the local cells bind (microcosm#1240), carried in # the committed resource rather than the Chronicle feed. Their fan-out # refuses a missing cell, so the national surface always merges them. + # CenTax's parent cells (microcosm#1399) select the second resource. derived = load_uk_high_value_home_stock_facts(args.derived_facts) + centax = load_uk_centax_childcare_parent_facts(args.centax_facts) facts.extend(dict(row) for row in derived.rows) + facts.extend(dict(row) for row in centax.rows) derived_resources = [ { - "resource": "high_value_home_stock_facts.json", - "rows": len(derived.rows), - "rows_sha256": derived.rows_sha256, - "inputs_sha256": derived.inputs_sha256, + "resource": resource, + "rows": len(loaded.rows), + "rows_sha256": loaded.rows_sha256, + "inputs_sha256": loaded.inputs_sha256, } + for resource, loaded in ( + ("high_value_home_stock_facts.json", derived), + (CENTAX_FACTS_RESOURCE, centax), + ) ] inverse_mapping = _registry_inverse(contract) # The facts each family's fan-out leaves unnamed, counted rather than @@ -215,6 +225,15 @@ def _parser() -> argparse.ArgumentParser: "committed uk/high_value_home_stock_facts.json)." ), ) + parser.add_argument( + "--centax-facts", + type=Path, + default=None, + help=( + "CenTax parent facts resource merged beside the feed (default: the " + "committed uk/centax_childcare_parent_facts.json)." + ), + ) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--membership-report", type=Path, required=True) return parser @@ -552,6 +571,9 @@ def _geography_composition( # Heating Payment from winter 2024-25, so DWP publishes the 2024-25 and # 2025-26 statistics for England and Wales (K04000001) only (microcosm#1069). ("dwp.winter_fuel_payment.", "england_and_wales"), + # CenTax tabulates parents in England only, and the derived facts are + # stamped E92000001 (microcosm#1399); the substring rule sees no nation. + ("microcosm.centax_childcare_parents.", "england"), ) # DfT BUS05i rows name their area in the selector; the geography follows the # declared area, never a prefix, so a London or UK row can never be stamped