From 69adc1ad383d1093e0d9e904ea00624373d7239f Mon Sep 17 00:00:00 2001 From: David Trimmer Date: Thu, 12 Nov 2026 20:23:55 -0500 Subject: [PATCH 1/5] Draw district maps from ui-kit boundaries for the analysis's Congress The Districts tab fetched ArcGIS's 118th Congress layer, but every analysis runs on the policyengine-us-data state files, which assign households to 119th Congress districts. In the five states that redrew between the two (AL, GA, LA, NC, NY), results were drawn on the wrong boundaries. The map now loads ui-kit's district file for the Congress the results were computed on: model_notes.district_congress, or a year's own districtCongress in multi-year analyses, defaulting to 119 when untagged. The header names the Congress. The 120th Congress can be drawn once ui-kit ships PolicyEngine/policyengine-ui-kit#41; until then a 120 tag falls back to the card view instead of drawing 119th boundaries. Also removes the unused hard-coded 118th Utah map. Co-Authored-By: Claude Opus 5.5 --- src/components/reform/DistrictMap.jsx | 531 ++-------------------- src/components/reform/ReformAnalyzer.jsx | 24 +- src/components/reform/districtGeo.js | 93 ++++ src/components/reform/districtGeo.test.js | 105 +++++ 4 files changed, 247 insertions(+), 506 deletions(-) create mode 100644 src/components/reform/districtGeo.js create mode 100644 src/components/reform/districtGeo.test.js diff --git a/src/components/reform/DistrictMap.jsx b/src/components/reform/DistrictMap.jsx index ab5e3d6..1f52acc 100644 --- a/src/components/reform/DistrictMap.jsx +++ b/src/components/reform/DistrictMap.jsx @@ -11,53 +11,13 @@ import { geoCentroid } from "d3-geo"; import { colors, typography, spacing } from "../../designTokens"; import { useData } from "../../context/DataContext"; import { track } from "../../lib/analytics"; - -// ArcGIS REST API for 118th Congressional Districts -const getCongressionalDistrictsUrl = (stateAbbr) => - `https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/USA_118th_Congressional_Districts/FeatureServer/0/query?where=${encodeURIComponent(`STATE_ABBR='${stateAbbr}'`)}&outFields=*&f=geojson`; - -// State FIPS codes for filtering -const STATE_FIPS = { - "AL": "01", "AK": "02", "AZ": "04", "AR": "05", "CA": "06", - "CO": "08", "CT": "09", "DE": "10", "FL": "12", "GA": "13", - "HI": "15", "ID": "16", "IL": "17", "IN": "18", "IA": "19", - "KS": "20", "KY": "21", "LA": "22", "ME": "23", "MD": "24", - "MA": "25", "MI": "26", "MN": "27", "MS": "28", "MO": "29", - "MT": "30", "NE": "31", "NV": "32", "NH": "33", "NJ": "34", - "NM": "35", "NY": "36", "NC": "37", "ND": "38", "OH": "39", - "OK": "40", "OR": "41", "PA": "42", "RI": "44", "SC": "45", - "SD": "46", "TN": "47", "TX": "48", "UT": "49", "VT": "50", - "VA": "51", "WA": "53", "WV": "54", "WI": "55", "WY": "56", -}; - -// Real geographic SVG paths for Utah congressional districts (118th Congress) -// Generated from Census Bureau TIGER/Line shapefiles -const UTAH_DISTRICT_PATHS = { - "1": { - path: "M20.7,102.1 L20.9,81.9 L20.9,73.1 L20.9,72.4 L20.8,56.1 L21.0,53.7 L24.2,45.9 L36.6,46.2 L40.7,46.2 L59.7,45.9 L64.6,45.9 L67.2,45.8 L71.2,45.8 L77.7,45.7 L95.6,45.5 L102.1,45.5 L104.2,45.5 L107.6,45.5 L116.5,45.4 L135.1,45.3 L139.7,45.3 L150.3,45.3 L155.0,45.7 L155.7,45.6 L159.6,45.6 L172.2,45.5 L173.5,45.5 L176.3,45.5 L186.2,45.5 L202.8,45.4 L205.4,45.4 L209.1,45.4 L217.7,45.3 L236.0,75.6 L236.0,79.8 L235.9,91.3 L235.9,99.2 L235.9,117.4 L248.5,117.4 L248.4,123.2 L244.9,127.2 L241.3,129.0 L238.9,128.4 L234.7,128.4 L227.7,129.9 L225.1,130.7 L219.4,131.0 L217.7,131.6 L210.5,130.7 L212.3,135.0 L208.1,136.0 L207.9,140.2 L206.1,140.0 L205.3,140.0 L202.6,140.0 L201.2,140.3 L200.7,140.0 L199.2,140.4 L197.1,139.5 L196.7,138.9 L184.8,138.0 L183.5,139.5 L182.0,139.7 L179.6,139.7 L179.4,138.3 L179.4,137.6 L179.4,137.0 L179.6,136.4 L179.7,135.5 L178.8,135.2 L177.4,135.2 L176.7,135.2 L176.1,135.2 L175.3,135.2 L175.2,133.3 L174.4,132.0 L173.3,130.8 L174.6,130.2 L176.6,129.6 L178.2,128.6 L179.4,127.6 L180.7,125.5 L178.7,124.8 L177.6,124.2 L177.3,123.4 L176.9,122.1 L176.1,120.7 L176.6,119.7 L176.0,117.4 L174.9,116.1 L174.2,116.1 L174.1,116.2 L173.8,116.3 L173.3,116.3 L172.4,116.8 L172.8,117.1 L172.7,117.3 L172.0,117.5 L167.6,117.9 L164.1,117.9 L160.5,114.7 L158.4,110.8 L132.0,111.7 L110.0,117.2 L20.8,117.2 L20.8,102.3 Z", - center: { x: 162, y: 82 }, - name: "District 1", - region: "Northern Utah", - }, - "2": { - path: "M20.0,362.0 L20.1,351.0 L20.1,350.9 L20.2,349.6 L20.2,345.4 L20.2,341.2 L20.2,322.1 L20.2,314.8 L20.2,303.7 L20.2,296.8 L20.2,293.4 L20.2,291.6 L20.2,280.3 L20.3,269.9 L20.4,269.6 L20.4,225.0 L20.4,206.3 L20.4,201.9 L20.4,195.8 L20.4,186.9 L20.4,181.6 L20.5,172.4 L20.5,158.6 L20.5,153.6 L20.6,152.7 L20.7,134.6 L20.7,133.6 L81.1,117.2 L119.8,114.8 L135.0,111.0 L158.9,112.6 L162.7,115.7 L166.9,118.3 L169.6,118.2 L172.4,117.5 L172.8,117.3 L172.8,117.1 L173.3,116.3 L173.7,116.4 L173.9,116.3 L174.2,116.1 L174.4,116.1 L175.6,117.3 L176.6,119.1 L176.1,119.8 L176.8,122.2 L177.0,122.8 L177.3,124.0 L178.1,124.2 L178.7,125.7 L179.3,126.5 L178.0,127.6 L176.6,129.1 L175.3,130.0 L173.5,130.0 L173.4,131.2 L174.7,132.6 L175.3,133.8 L175.5,135.2 L176.6,135.2 L176.7,135.2 L178.0,135.2 L178.9,135.2 L179.6,135.8 L179.4,137.0 L179.4,137.4 L179.4,137.9 L179.4,138.8 L179.0,139.7 L177.9,139.7 L176.7,139.7 L175.5,139.7 L173.1,139.8 L171.9,140.1 L170.5,140.1 L169.1,140.1 L167.1,140.1 L165.7,140.1 L165.7,141.1 L165.6,141.6 L165.5,141.9 L165.5,142.0 L165.7,142.1 L165.7,143.2 L164.9,143.7 L163.6,143.7 L153.8,144.0 L154.9,145.7 L154.3,148.7 L154.0,152.1 L155.1,155.2 L153.8,155.4 L152.4,158.0 L153.2,161.6 L153.5,163.2 L153.4,165.7 L154.0,168.1 L154.6,171.2 L155.3,173.3 L156.0,174.9 L156.4,176.0 L155.0,177.9 L154.8,179.6 L156.2,182.0 L155.1,186.2 L156.0,188.6 L159.6,191.0 L160.0,194.2 L161.6,195.3 L163.2,197.7 L162.1,200.6 L162.0,203.4 L159.2,206.5 L153.1,209.3 L149.1,212.2 L143.8,218.3 L152.2,221.1 L153.6,223.1 L152.9,225.7 L153.9,234.1 L157.6,237.2 L162.3,238.3 L166.5,257.6 L178.0,258.5 L217.8,258.6 L217.8,276.0 L217.2,284.4 L217.3,296.8 L309.3,296.8 L310.2,300.6 L307.9,300.1 L310.6,302.3 L308.7,304.7 L312.0,305.0 L313.0,305.8 L313.7,308.3 L315.4,307.4 L313.6,309.0 L315.0,310.6 L316.3,312.8 L316.2,314.1 L318.2,314.3 L318.2,315.3 L317.1,316.4 L318.4,317.9 L318.1,318.7 L316.0,321.4 L316.3,321.9 L316.2,322.4 L315.8,323.0 L315.2,323.0 L314.5,323.3 L314.0,323.7 L313.9,324.0 L313.7,324.3 L313.4,324.6 L312.9,324.7 L312.4,325.0 L312.2,325.4 L311.7,325.5 L311.2,325.3 L310.5,324.8 L309.9,325.2 L309.5,325.6 L309.0,326.2 L308.6,326.7 L308.1,327.1 L307.8,327.6 L308.0,328.2 L308.0,328.7 L307.8,329.2 L307.2,329.2 L306.6,329.6 L306.2,330.1 L305.9,330.7 L305.6,331.2 L305.8,331.8 L305.7,332.5 L305.2,333.0 L304.4,333.1 L303.8,332.7 L303.4,332.3 L302.7,332.1 L302.0,332.2 L301.1,332.6 L300.7,333.4 L299.9,333.8 L299.4,334.4 L298.9,335.4 L298.1,335.8 L297.1,336.3 L296.3,337.1 L296.7,338.2 L296.7,339.0 L296.4,339.8 L295.7,340.4 L294.1,340.2 L292.7,340.0 L291.4,340.4 L291.1,341.5 L291.2,342.1 L290.5,342.3 L290.1,341.8 L289.9,340.8 L288.8,340.6 L287.3,340.6 L285.6,340.4 L284.0,340.6 L282.6,341.0 L282.0,341.8 L282.2,342.6 L282.0,343.5 L280.6,344.0 L279.9,345.1 L279.8,346.1 L279.4,346.7 L278.4,346.4 L277.2,346.5 L276.8,347.3 L277.2,348.0 L277.6,348.8 L278.6,349.1 L279.8,348.8 L280.5,348.7 L280.2,349.3 L279.2,349.9 L279.0,350.9 L278.3,352.1 L277.4,353.1 L276.5,353.9 L276.3,354.4 L276.3,355.6 L275.6,356.6 L275.4,357.6 L274.8,357.7 L273.9,357.6 L273.2,358.4 L272.2,359.0 L271.3,358.4 L270.6,358.8 L270.5,360.1 L269.3,360.9 L268.0,361.1 L267.8,361.9 L268.1,363.3 L266.7,364.1 L265.3,364.9 L264.7,365.7 L263.1,368.9 L263.4,370.2 L258.7,371.6 L258.9,373.2 L260.2,375.2 L257.6,375.3 L259.2,377.9 L258.2,379.7 L256.8,380.4 L253.3,381.5 L248.4,379.7 L250.1,381.3 L250.7,383.3 L249.3,385.6 L247.4,387.0 L246.9,388.8 L246.3,391.4 L244.7,391.8 L243.8,393.9 L242.8,394.9 L240.8,395.4 L238.4,396.2 L235.8,397.4 L232.0,397.2 L229.6,398.1 L227.4,397.0 L225.8,398.2 L222.3,399.5 L222.8,401.8 L220.0,400.7 L217.7,401.4 L217.2,402.9 L215.6,403.1 L210.2,404.4 L209.7,404.4 L141.8,404.5 L140.3,404.5 L128.6,404.5 L127.3,404.5 L107.9,404.5 L102.9,404.5 L98.0,404.5 L89.9,404.5 L73.6,404.5 L62.8,404.5 L26.3,404.6 L20.2,404.5 L20.1,398.0 L20.1,394.9 L20.1,392.2 L20.1,384.2 L20.1,383.5 L20.1,377.9 L20.1,374.5 L20.0,370.6 L20.0,368.5 L20.0,367.4 L20.0,366.4 Z", - center: { x: 120, y: 280 }, - name: "District 2", - region: "Western & Rural Utah", - }, - "3": { - path: "M173.6,155.9 L174.9,154.1 L175.3,152.8 L175.2,150.8 L174.7,148.1 L174.5,146.5 L174.4,144.5 L176.6,144.5 L177.1,143.8 L177.1,142.4 L177.2,141.2 L177.1,139.7 L178.6,139.7 L179.6,139.7 L182.0,139.7 L183.5,139.5 L184.8,138.0 L196.7,138.9 L197.1,139.5 L199.2,140.4 L200.7,140.0 L201.2,140.3 L202.6,140.0 L205.3,140.0 L206.1,140.0 L207.9,140.2 L208.1,136.0 L212.3,135.0 L210.5,130.7 L217.7,131.6 L219.4,131.0 L225.1,130.7 L227.7,129.9 L234.7,128.4 L238.9,128.4 L241.3,129.0 L244.9,127.2 L248.4,123.2 L248.5,117.4 L259.8,117.5 L272.3,117.5 L284.1,117.6 L294.0,117.6 L302.4,117.4 L310.7,117.4 L311.1,117.4 L321.5,117.4 L331.6,117.4 L334.4,117.4 L344.5,117.4 L364.9,117.2 L370.5,117.2 L379.5,129.7 L379.5,141.5 L379.5,144.6 L379.4,150.3 L379.3,153.5 L379.3,173.1 L379.3,176.1 L379.3,184.8 L379.3,198.0 L379.3,225.1 L379.3,234.6 L379.2,252.5 L379.1,265.0 L379.1,267.7 L379.1,269.9 L378.7,281.0 L378.6,296.8 L378.6,312.9 L379.9,320.9 L379.9,332.8 L379.9,334.6 L380.0,341.3 L380.0,344.1 L380.0,347.1 L380.0,351.4 L380.0,353.5 L379.9,359.7 L379.9,361.2 L379.9,366.4 L379.8,369.7 L379.7,378.7 L379.7,386.6 L379.7,389.4 L379.6,391.8 L379.7,396.5 L379.7,397.6 L379.7,399.2 L379.7,404.6 L366.2,404.6 L364.0,404.6 L363.5,404.6 L355.6,404.6 L338.0,404.7 L332.0,404.7 L311.1,404.7 L311.1,404.7 L277.6,404.7 L275.9,404.3 L268.1,404.3 L266.2,404.3 L234.5,404.4 L221.0,404.5 L214.8,404.5 L217.3,403.6 L219.1,401.6 L217.6,399.8 L221.7,403.0 L221.5,400.8 L223.6,400.5 L226.4,397.3 L228.3,397.9 L230.5,396.8 L234.3,396.9 L236.2,396.8 L240.0,396.5 L242.0,395.7 L242.5,393.8 L244.4,393.4 L246.4,392.0 L247.2,390.7 L248.2,388.2 L247.8,386.3 L248.4,383.9 L250.9,382.1 L248.8,381.0 L249.6,379.5 L255.3,381.4 L256.9,379.4 L258.3,378.8 L257.0,375.9 L259.5,375.8 L260.9,373.5 L257.6,372.0 L259.4,370.0 L265.2,369.5 L263.7,366.8 L264.8,365.6 L266.1,364.4 L267.7,363.9 L268.0,362.6 L267.7,361.5 L268.4,361.1 L270.1,360.6 L270.6,359.4 L270.8,358.5 L271.6,358.6 L272.9,358.9 L273.6,357.8 L274.5,357.4 L275.0,357.8 L275.4,357.2 L276.2,356.1 L276.3,354.9 L276.1,354.2 L276.9,353.7 L277.5,352.5 L278.9,351.6 L279.0,350.3 L279.8,349.5 L280.5,348.9 L280.2,348.6 L279.3,349.0 L278.1,349.2 L277.3,348.5 L277.1,347.5 L277.0,346.9 L277.7,346.5 L279.1,346.5 L279.8,346.4 L279.8,345.6 L280.1,344.4 L281.2,343.8 L282.2,343.0 L282.1,342.2 L282.0,341.5 L283.2,340.8 L284.8,340.5 L286.6,340.6 L288.0,340.6 L289.3,340.6 L290.0,341.4 L290.3,342.2 L290.9,342.3 L291.2,341.8 L291.1,341.0 L292.0,340.0 L293.2,340.1 L294.9,340.3 L296.2,340.2 L296.5,339.4 L296.9,338.6 L296.4,337.7 L296.6,336.6 L297.6,336.2 L298.5,335.6 L299.3,334.9 L299.6,333.9 L300.3,333.6 L300.9,333.0 L301.4,332.3 L302.4,332.1 L303.1,332.2 L303.6,332.5 L304.1,332.9 L304.7,333.1 L305.6,332.8 L305.8,332.2 L305.6,331.5 L305.8,331.0 L306.0,330.5 L306.3,329.8 L306.9,329.4 L307.5,329.2 L307.9,328.9 L308.0,328.5 L307.8,327.9 L308.0,327.3 L308.3,326.9 L308.8,326.5 L309.1,325.9 L309.6,325.4 L310.1,325.0 L311.1,325.1 L311.5,325.5 L312.0,325.5 L312.3,325.2 L312.7,324.8 L313.2,324.7 L313.7,324.5 L313.8,324.1 L314.0,323.8 L314.2,323.4 L314.9,323.1 L315.5,323.0 L316.1,322.7 L316.3,322.2 L316.3,321.8 L319.3,319.1 L319.2,317.8 L317.0,317.2 L319.1,316.2 L317.0,315.0 L317.7,313.3 L315.7,313.7 L314.7,311.6 L313.9,309.9 L314.8,308.5 L314.5,307.3 L312.0,307.0 L313.0,305.0 L311.0,306.1 L310.8,303.1 L309.2,300.6 L308.5,299.7 L310.9,298.1 L249.3,296.8 L217.3,296.1 L217.8,284.4 L217.9,259.6 L217.8,245.7 L217.7,227.3 L221.5,227.3 L221.5,210.3 L233.6,202.4 L249.5,196.3 L233.3,196.2 L230.8,193.1 L230.7,191.4 L229.0,190.0 L226.6,187.9 L224.6,185.5 L221.6,185.7 L222.3,184.1 L223.4,180.1 L223.1,177.0 L220.7,174.8 L220.3,171.7 L213.4,168.3 L207.4,168.2 L205.4,168.1 L200.3,170.3 L201.5,171.3 L203.2,173.7 L203.8,175.1 L200.1,178.1 L198.4,177.9 L197.3,177.1 L196.3,177.1 L195.4,177.5 L194.9,177.5 L186.8,177.6 L186.6,175.9 L187.4,175.6 L186.2,172.2 L186.2,172.1 L186.1,171.9 L186.2,171.8 L186.4,171.9 L186.5,171.6 L186.4,170.4 L184.8,169.0 L183.8,165.1 L181.7,164.4 L180.5,162.0 L179.6,161.4 L178.9,160.6 L176.5,159.1 L173.8,156.8 L173.6,155.9 Z", - center: { x: 300, y: 260 }, - name: "District 3", - region: "Central & Eastern Utah", - }, - "4": { - path: "M143.8,218.3 L149.1,212.2 L153.1,209.3 L159.2,206.5 L162.0,203.4 L162.1,200.6 L163.2,197.7 L161.6,195.3 L160.0,194.2 L159.6,191.0 L156.0,188.6 L155.1,186.2 L156.2,182.0 L154.8,179.6 L155.0,177.9 L156.4,176.0 L156.0,174.9 L155.3,173.3 L154.6,171.2 L154.0,168.1 L153.4,165.7 L153.5,163.2 L153.2,161.6 L152.4,158.0 L153.8,155.4 L155.1,155.2 L154.0,152.1 L154.3,148.7 L154.9,145.7 L153.8,144.0 L163.6,143.7 L164.9,143.7 L165.7,143.2 L165.7,142.1 L165.5,142.0 L165.5,141.9 L165.6,141.6 L165.7,141.1 L165.7,140.1 L167.1,140.1 L169.1,140.1 L170.5,140.1 L171.9,140.1 L173.1,139.8 L175.5,139.7 L176.7,139.7 L177.1,140.6 L177.2,141.5 L177.1,142.9 L177.1,144.4 L175.3,144.5 L174.2,145.2 L174.6,146.8 L174.6,148.1 L175.3,151.2 L175.3,153.2 L174.7,154.3 L173.7,156.6 L175.3,158.1 L176.9,159.3 L179.3,160.9 L180.5,162.0 L181.7,162.4 L182.7,164.8 L183.8,168.9 L185.2,169.6 L186.6,171.4 L186.5,171.7 L186.3,171.8 L186.2,171.8 L186.3,172.1 L186.3,172.2 L187.1,175.5 L187.7,176.2 L185.5,177.1 L192.8,177.5 L194.9,177.5 L196.2,177.1 L196.6,176.8 L198.0,177.3 L200.1,178.1 L203.9,177.1 L203.2,175.0 L202.6,172.3 L200.3,171.3 L202.7,168.6 L206.4,167.5 L212.4,167.7 L216.9,168.5 L219.7,173.1 L221.5,175.2 L222.7,178.5 L221.9,182.9 L221.4,185.1 L223.0,186.5 L225.1,186.8 L227.4,189.8 L230.0,191.2 L229.9,192.8 L233.3,193.1 L247.1,196.3 L249.5,202.5 L221.5,202.5 L221.5,219.1 L219.0,227.3 L217.7,232.9 L217.8,258.6 L178.0,258.5 L166.5,257.6 L162.3,238.3 L157.6,237.2 L153.9,234.1 L152.9,225.7 L153.6,223.1 L152.2,221.1 L143.8,218.3 Z", - center: { x: 190, y: 195 }, - name: "District 4", - region: "Salt Lake Suburbs", - }, -}; +import { + congressLabel, + districtCongressOf, + districtNumberOf, + isAtLarge, + loadStateDistrictsGeo, +} from "./districtGeo"; // Generic district visualization for other states (card-based grid) const STATE_DISTRICTS = { @@ -187,393 +147,6 @@ function ImpactLegend({ maxBenefit, allPositive, allNegative }) { ); } -function UtahDistrictMap({ reformId }) { - const [selectedDistrict, setSelectedDistrict] = useState(null); - const { getImpact } = useData(); - const reformImpacts = getImpact(reformId); - const hasDistrictData = reformImpacts?.districtImpacts; - - // Calculate max benefit and direction for color scaling - const districtValues = hasDistrictData - ? Object.values(UTAH_DISTRICT_PATHS).map((_, idx) => - yearImpacts.districtImpacts[`UT-${idx + 1}`]?.avgBenefit || 0) - : []; - const maxBenefit = districtValues.length > 0 - ? Math.max(...districtValues.map(Math.abs)) - : 150; - const allPositive = districtValues.every(v => v >= 0); - const allNegative = districtValues.every(v => v <= 0); - - const activeDistrict = selectedDistrict; - const activeImpact = activeDistrict && hasDistrictData - ? yearImpacts.districtImpacts[`UT-${activeDistrict}`] - : null; - - return ( -
- {/* Map Container */} -
-

- Utah Congressional Districts -

- -
- - {/* District shapes - real geographic boundaries */} - {Object.entries(UTAH_DISTRICT_PATHS).map(([districtId, data]) => { - const impact = hasDistrictData - ? yearImpacts.districtImpacts[`UT-${districtId}`] - : null; - const avgBenefit = impact?.avgBenefit || 0; - const isSelected = selectedDistrict === districtId; - - const fillColor = isSelected - ? getImpactHoverColor(avgBenefit, maxBenefit) - : getImpactColor(avgBenefit, maxBenefit); - - return ( - - { - const next = selectedDistrict === districtId ? null : districtId; - setSelectedDistrict(next); - if (next) track("district_selected", { state_abbr: "UT", district_id: `UT-${districtId}` }); - }} - /> - {/* District label */} - - {districtId} - - - ); - })} - -
- - -
- - {/* Detail Panel */} -
- {activeDistrict && activeImpact ? ( - - ) : ( -
-
- - - -
-

- Click on a district
to see detailed impact data -

-
- )} - - {/* District Summary Cards */} -
- {Object.entries(UTAH_DISTRICT_PATHS).map(([districtId, data]) => { - const impact = hasDistrictData - ? yearImpacts.districtImpacts[`UT-${districtId}`] - : null; - const avgBenefit = impact?.avgBenefit || 0; - const isActive = activeDistrict === districtId; - - return ( - - ); - })} -
-
-
- ); -} - -function DistrictDetailCard({ districtId, districtInfo, impact, maxBenefit }) { - const avgBenefit = impact?.avgBenefit || 0; - const isPositive = avgBenefit > 0; - const isNeutral = avgBenefit === 0; - - return ( -
- {/* Header */} -
- - {districtId} - -
-

- {districtInfo.name} -

-

- {districtInfo.region} -

-
-
- - {/* Impact Value */} -
- - {isNeutral ? null : (isPositive ? : )} - - - {isPositive ? "+" : ""}{avgBenefit === 0 ? "$0" : `$${Math.abs(avgBenefit).toLocaleString()}`} - - - average household impact - -
- - {/* Stats Grid */} -
- {/* Winners / Losers unified */} -
-

- Winners / Losers -

-

- {impact.winnersShare ? `${(impact.winnersShare * 100).toFixed(0)}%` : "0%"} - {" / "} - {impact.losersShare ? `${(impact.losersShare * 100).toFixed(0)}%` : "0%"} -

-
- 0 ? "+" : ""}${impact.povertyPctChange.toFixed(1)}%`} - color={impact.povertyPctChange < 0 ? colors.primary[600] : (impact.povertyPctChange > 0 ? colors.red[600] : colors.gray[500])} - /> - 0 ? "+" : ""}${impact.childPovertyPctChange.toFixed(1)}%`} - color={impact.childPovertyPctChange < 0 ? colors.primary[600] : (impact.childPovertyPctChange > 0 ? colors.red[600] : colors.gray[500])} - /> -
-
- ); -} - function StatBox({ label, value, color }) { return (
{ - if (prefetchedGeoData && !geoData) { - // eslint-disable-next-line react-hooks/set-state-in-effect - setGeoData(prefetchedGeoData); - setLoading(false); - } - }, [prefetchedGeoData]); - - // Only fetch if no prefetched data available - useEffect(() => { - if (prefetchedGeoData) return; let cancelled = false; - - const fetchDistricts = async () => { - try { - const res = await fetch(getCongressionalDistrictsUrl(stateAbbr)); - if (!res.ok) throw new Error(`HTTP ${res.status}`); - const data = await res.json(); - + loadStateDistrictsGeo(stateAbbr, congress) + .then((data) => { if (cancelled) return; - - if (data.features && data.features.length > 0) { - setGeoData(data); - setError(null); - } else { - setGeoData(null); - setError("No districts found"); - } - setLoading(false); - } catch (err) { + setGeoState( + data.features.length > 0 + ? { key: geoKey, data, error: null } + : { key: geoKey, data: null, error: "No districts found" } + ); + }) + .catch((err) => { if (cancelled) return; console.error("Failed to load congressional districts:", err); - setGeoData(null); - setError(err.message); - setLoading(false); - } - }; - - fetchDistricts(); - + setGeoState({ key: geoKey, data: null, error: err.message }); + }); return () => { cancelled = true; }; - }, [stateAbbr, prefetchedGeoData]); + }, [stateAbbr, congress, geoKey]); + const loading = geoState.key !== geoKey; + const geoData = loading ? null : geoState.data; + const error = loading ? null : geoState.error; // Calculate centroids for district labels const districtCentroids = useMemo(() => { @@ -1302,14 +852,12 @@ function GenericStateDistrictMap({ stateAbbr, reformId, prefetchedGeoData, selec const centroids = {}; geoData.features.forEach(feature => { const props = feature.properties; - // ArcGIS uses CDFIPS for district number (e.g., "01", "02") - const districtFp = props.CDFIPS || props.CD118FP || props.CDFP; - const districtNum = parseInt(districtFp, 10); + const districtNum = districtNumberOf(props); const districtId = `${stateAbbr}-${districtNum || 1}`; const centroid = geoCentroid(feature); centroids[districtId] = { coords: centroid, - num: districtNum === 0 ? "AL" : districtNum, + num: isAtLarge(props) || districtNum === 0 ? "AL" : districtNum, }; }); return centroids; @@ -1344,16 +892,14 @@ function GenericStateDistrictMap({ stateAbbr, reformId, prefetchedGeoData, selec return ; } - // Parse district number from ArcGIS GeoJSON properties + // District number from ui-kit's DISTRICT_ID ("TX-05") const getDistrictInfo = (geo) => { const props = geo.properties; if (!props) return null; - // ArcGIS uses CDFIPS for district number (e.g., "01", "02") - const districtFp = props.CDFIPS || props.CD118FP || props.CDFP; - const districtNum = parseInt(districtFp, 10); + const districtNum = districtNumberOf(props); return { districtId: `${stateAbbr}-${districtNum || 1}`, - districtNum: districtNum === 0 ? "AL" : districtNum, + districtNum: isAtLarge(props) || districtNum === 0 ? "AL" : districtNum, name: props.NAMELSAD || props.NAME || `District ${districtNum}`, }; }; @@ -1593,7 +1139,7 @@ function GenericStateDistrictMap({ stateAbbr, reformId, prefetchedGeoData, selec // States with only one congressional district (at-large) const SINGLE_DISTRICT_STATES = ["AK", "DE", "ND", "SD", "VT", "WY", "DC"]; -export default function DistrictMap({ stateAbbr, reformId, prefetchedGeoData }) { +export default function DistrictMap({ stateAbbr, reformId }) { const { getImpact } = useData(); const impacts = getImpact(reformId); @@ -1602,6 +1148,7 @@ export default function DistrictMap({ stateAbbr, reformId, prefetchedGeoData }) const hasMultipleYears = availableYears.length > 1; const defaultYear = hasMultipleYears ? availableYears[0] : null; const [selectedYear, setSelectedYear] = useState(defaultYear); + const congress = districtCongressOf(impacts, selectedYear); // Check if this is a single-district state const isSingleDistrict = SINGLE_DISTRICT_STATES.includes(stateAbbr); @@ -1668,7 +1215,7 @@ export default function DistrictMap({ stateAbbr, reformId, prefetchedGeoData }) fontFamily: typography.fontFamily.body, color: colors.text.secondary, }}> - Click on a district to see detailed impact analysis + {congressLabel(congress)}. Click on a district to see detailed impact analysis

@@ -1705,8 +1252,8 @@ export default function DistrictMap({ stateAbbr, reformId, prefetchedGeoData }) diff --git a/src/components/reform/ReformAnalyzer.jsx b/src/components/reform/ReformAnalyzer.jsx index 9e3ff05..67493cc 100644 --- a/src/components/reform/ReformAnalyzer.jsx +++ b/src/components/reform/ReformAnalyzer.jsx @@ -8,6 +8,7 @@ import HouseholdForm from "./HouseholdForm"; import ResultsDisplay from "./ResultsDisplay"; import AggregateImpacts from "./AggregateImpacts"; import DistrictMap from "./DistrictMap"; +import { districtCongressOf, loadStateDistrictsGeo } from "./districtGeo"; import BillOverview from "./BillOverview"; const ChartIcon = () => ( @@ -107,20 +108,16 @@ export default function ReformAnalyzer({ reformConfig, stateAbbr, bill }) { ) : TABS; - // Pre-fetch district GeoJSON so it's ready when user clicks Districts tab - const [cachedGeoData, setCachedGeoData] = useState(null); + // Load the district boundaries early so the Districts tab opens quickly. + // DistrictMap opens on the first year of a multi-year analysis, so warm + // that year's Congress. + const analysisYears = Object.keys(aggregateImpacts?.impactsByYear || {}).sort(); + const firstYear = analysisYears.length > 1 ? analysisYears[0] : null; + const districtCongress = districtCongressOf(aggregateImpacts, firstYear); useEffect(() => { - if (isFederal) return undefined; - const url = `https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/USA_118th_Congressional_Districts/FeatureServer/0/query?where=${encodeURIComponent(`STATE_ABBR='${stateAbbr}'`)}&outFields=*&f=geojson`; - let cancelled = false; - fetch(url) - .then(res => res.ok ? res.json() : null) - .then(data => { - if (!cancelled && data?.features?.length > 0) setCachedGeoData(data); - }) - .catch(() => {}); - return () => { cancelled = true; }; - }, [stateAbbr, isFederal]); + if (isFederal) return; + loadStateDistrictsGeo(stateAbbr, districtCongress).catch(() => {}); + }, [stateAbbr, isFederal, districtCongress]); const [householdInputs, setHouseholdInputs] = useState({ headAge: 35, @@ -265,7 +262,6 @@ export default function ReformAnalyzer({ reformConfig, stateAbbr, bill }) { )} diff --git a/src/components/reform/districtGeo.js b/src/components/reform/districtGeo.js new file mode 100644 index 0000000..44fa058 --- /dev/null +++ b/src/components/reform/districtGeo.js @@ -0,0 +1,93 @@ +import { loadCongressionalDistrictsGeo } from "@policyengine/ui-kit/visualization"; + +// The Congress whose districts an analysis without a tag was computed on. +// Every analysis before tagging used the policyengine-us-data state files, +// which assign households to 119th Congress districts +// (make_block_cd_distributions.py: fetch_block_to_district_map(119)). +export const DEFAULT_DISTRICT_CONGRESS = 119; + +// Congresses whose boundaries the installed ui-kit can draw. ui-kit 0.9's +// loader takes no argument and always returns the 119th file, so add 120 only +// after upgrading to the release with PolicyEngine/policyengine-ui-kit#41. +export const DRAWABLE_CONGRESSES = [119]; + +function toCongress(value) { + const n = Number(value); + return Number.isInteger(n) && n > 0 ? n : DEFAULT_DISTRICT_CONGRESS; +} + +/** + * The Congress whose districts the shown district results were computed on. + * A multi-year analysis tags each year; only the root fields fall back to + * model_notes.district_congress, which describes the latest write. + */ +export function districtCongressOf(impacts, selectedYear) { + const yearEntry = selectedYear ? impacts?.impactsByYear?.[selectedYear] : null; + if (yearEntry) return toCongress(yearEntry.districtCongress); + return toCongress(impacts?.modelNotes?.district_congress); +} + +export function ordinal(n) { + const mod100 = n % 100; + if (mod100 >= 11 && mod100 <= 13) return `${n}th`; + const suffix = { 1: "st", 2: "nd", 3: "rd" }[n % 10] || "th"; + return `${n}${suffix}`; +} + +export function congressLabel(congress) { + if (congress === 120) return "120th Congress districts (from January 3, 2027)"; + return `${ordinal(congress)} Congress districts`; +} + +/** District number from a ui-kit boundary feature's properties ("TX-05" -> 5). */ +export function districtNumberOf(properties) { + const id = properties?.DISTRICT_ID; + if (typeof id === "string" && id.includes("-")) { + const n = parseInt(id.split("-")[1], 10); + if (!Number.isNaN(n)) return n; + } + const fp = properties?.CD120FP ?? properties?.CD119FP ?? properties?.CDFP; + const n = parseInt(fp, 10); + return Number.isNaN(n) ? null : n; +} + +export function isAtLarge(properties) { + return /at large/i.test(properties?.NAMELSAD || ""); +} + +/** Keep one state's districts from a national boundary file. */ +export function filterStateDistricts(geo, stateAbbr, congress) { + const prefix = `${stateAbbr}-`; + const features = (geo?.features || []).filter((f) => + f.properties?.DISTRICT_ID?.startsWith(prefix) + ); + // The file must be the Congress we asked for: an older ui-kit ignores the + // argument and returns the 119th file. + const session = features[0]?.properties?.CDSESSN; + if (session && Number(session) !== congress) { + throw new Error( + `Asked for ${ordinal(congress)} Congress districts but got the ${ordinal(Number(session))}` + ); + } + return { type: "FeatureCollection", features }; +} + +const cache = new Map(); + +/** One state's district boundaries for the given Congress, from ui-kit. */ +export function loadStateDistrictsGeo(stateAbbr, congress) { + if (!DRAWABLE_CONGRESSES.includes(congress)) { + return Promise.reject( + new Error(`This ui-kit version has no ${ordinal(congress)} Congress district boundaries`) + ); + } + const key = `${stateAbbr}:${congress}`; + if (!cache.has(key)) { + const promise = loadCongressionalDistrictsGeo(congress).then((geo) => + filterStateDistricts(geo, stateAbbr, congress) + ); + promise.catch(() => cache.delete(key)); + cache.set(key, promise); + } + return cache.get(key); +} diff --git a/src/components/reform/districtGeo.test.js b/src/components/reform/districtGeo.test.js new file mode 100644 index 0000000..58eb9b2 --- /dev/null +++ b/src/components/reform/districtGeo.test.js @@ -0,0 +1,105 @@ +import { describe, it, expect, vi } from "vitest"; + +vi.mock("@policyengine/ui-kit/visualization", () => ({ + loadCongressionalDistrictsGeo: vi.fn(async () => ({ + type: "FeatureCollection", + features: [ + { properties: { DISTRICT_ID: "TX-01", CDSESSN: "119" } }, + { properties: { DISTRICT_ID: "TX-35", CDSESSN: "119" } }, + { properties: { DISTRICT_ID: "TN-09", CDSESSN: "119" } }, + ], + })), +})); + +import { + DEFAULT_DISTRICT_CONGRESS, + congressLabel, + districtCongressOf, + districtNumberOf, + filterStateDistricts, + isAtLarge, + loadStateDistrictsGeo, + ordinal, +} from "./districtGeo"; + +describe("districtCongressOf", () => { + it("defaults untagged analyses to the 119th Congress", () => { + expect(DEFAULT_DISTRICT_CONGRESS).toBe(119); + expect(districtCongressOf(undefined, null)).toBe(119); + expect(districtCongressOf({ modelNotes: {} }, null)).toBe(119); + }); + + it("reads the root tag from model_notes", () => { + expect(districtCongressOf({ modelNotes: { district_congress: 120 } }, null)).toBe(120); + }); + + it("reads a year's own tag and does not borrow the root tag", () => { + const impacts = { + modelNotes: { district_congress: 120 }, + impactsByYear: { 2026: {}, 2027: { districtCongress: 120 } }, + }; + expect(districtCongressOf(impacts, "2026")).toBe(119); + expect(districtCongressOf(impacts, "2027")).toBe(120); + }); +}); + +describe("labels", () => { + it("writes ordinals", () => { + expect(ordinal(119)).toBe("119th"); + expect(ordinal(120)).toBe("120th"); + expect(ordinal(121)).toBe("121st"); + expect(ordinal(111)).toBe("111th"); + }); + + it("dates the 120th Congress label", () => { + expect(congressLabel(119)).toBe("119th Congress districts"); + expect(congressLabel(120)).toBe("120th Congress districts (from January 3, 2027)"); + }); +}); + +describe("districtNumberOf", () => { + it("parses ui-kit DISTRICT_IDs", () => { + expect(districtNumberOf({ DISTRICT_ID: "TX-05" })).toBe(5); + expect(districtNumberOf({ DISTRICT_ID: "CA-52" })).toBe(52); + }); + + it("falls back to the Census district code", () => { + expect(districtNumberOf({ CD119FP: "07" })).toBe(7); + expect(districtNumberOf({ CD120FP: "00" })).toBe(0); + expect(districtNumberOf({})).toBeNull(); + }); + + it("spots at-large districts", () => { + expect(isAtLarge({ NAMELSAD: "Congressional District (at Large)" })).toBe(true); + expect(isAtLarge({ NAMELSAD: "Congressional District 4" })).toBe(false); + }); +}); + +describe("filterStateDistricts", () => { + const geo = { + features: [ + { properties: { DISTRICT_ID: "TN-01", CDSESSN: "120" } }, + { properties: { DISTRICT_ID: "TX-01", CDSESSN: "120" } }, + ], + }; + + it("keeps only the state's districts", () => { + const out = filterStateDistricts(geo, "TN", 120); + expect(out.features.map((f) => f.properties.DISTRICT_ID)).toEqual(["TN-01"]); + }); + + it("rejects a file from a different Congress", () => { + expect(() => filterStateDistricts(geo, "TN", 119)).toThrow(/119th.*120th/); + }); +}); + +describe("loadStateDistrictsGeo", () => { + it("loads one state's 119th districts", async () => { + const out = await loadStateDistrictsGeo("TX", 119); + expect(out.features.map((f) => f.properties.DISTRICT_ID)).toEqual(["TX-01", "TX-35"]); + }); + + it("refuses a Congress the installed ui-kit cannot draw", async () => { + await expect(loadStateDistrictsGeo("TX", 120)).rejects.toThrow(/no 120th Congress/); + }); +}); From 9e722f3a1d838b7797e4cc3fd247813cba116c8d Mon Sep 17 00:00:00 2001 From: David Trimmer Date: Thu, 12 Nov 2026 20:26:47 -0500 Subject: [PATCH 2/5] Tag district results with their Congress and make the state dataset swappable compute_impacts.py downloaded the policyengine-us-data state files with no record of which district plan they use. State datasets are now named sources (STATE_DATASETS) chosen with --state-dataset or TRACKER_STATE_DATASET; each says which Congress's districts it assigns households to. The default, us-data-cd119, is the current files (119th Congress block assignments), so nothing changes for existing runs. Each analysis with district results stores model_notes.district_congress, and multi-year analyses also tag each year (districtCongress), so the map can draw matching boundaries. Moving the tracker to the 120th Congress is then one new source entry plus a recompute, once the microcosm release with 120th district assignments exists (microcosm #1526). Also: - warn when a state's district GEOIDs don't match state_fips * 100 + 1..n, which catches a dataset with a different encoding or plan; - Supabase writes take the dataset name from the source, so federal runs record populace-us as the offline path already did. Co-Authored-By: Claude Opus 5.5 --- scripts/compute_impacts.py | 149 ++++++++++++++++--- scripts/test_compute_impacts_datasets.py | 173 +++++++++++++++++++++++ 2 files changed, 302 insertions(+), 20 deletions(-) create mode 100644 scripts/test_compute_impacts_datasets.py diff --git a/scripts/compute_impacts.py b/scripts/compute_impacts.py index f8e322c..ff35d0f 100644 --- a/scripts/compute_impacts.py +++ b/scripts/compute_impacts.py @@ -139,8 +139,46 @@ def load_reforms_from_db(supabase, reform_id=None): # MICROSIMULATION # ============================================================================= -def get_state_dataset(state: str) -> str: - """Download state-specific dataset from Hugging Face.""" +# Per-state datasets with congressional-district geocoding. Each source says +# which Congress's districts it assigns households to; every analysis stores +# that as model_notes.district_congress so the map draws matching boundaries. +# Choose a source with --state-dataset or the TRACKER_STATE_DATASET variable. +STATE_DATASETS = { + # The archived policyengine-us-data files, built from 119th Congress block + # assignments (make_block_cd_distributions.py: + # fetch_block_to_district_map(119)). + "us-data-cd119": { + "dataset_name": "policyengine-us-data", + "repo_id": "policyengine/policyengine-us-data", + "filename": "states/{state}.h5", + "revision": None, + "district_congress": 119, + }, + # Add the 120th Congress source here once the microcosm release that + # assigns households to 120th districts exists (microcosm #1526). +} +DEFAULT_STATE_DATASET = "us-data-cd119" + + +def state_dataset_source(name: str | None = None) -> dict: + """The state dataset source to use: the argument, then + TRACKER_STATE_DATASET, then the default.""" + name = name or os.environ.get("TRACKER_STATE_DATASET") or DEFAULT_STATE_DATASET + if name not in STATE_DATASETS: + raise ValueError( + f"Unknown state dataset {name!r}; choose from {sorted(STATE_DATASETS)}" + ) + return {"name": name, **STATE_DATASETS[name]} + + +def state_dataset_version(source: dict) -> str: + """Version string stored with the analysis. Sources without a pinned + version keep the old behavior: the installed policyengine-us-data.""" + return source.get("dataset_version") or get_installed_version("policyengine-us-data") + + +def get_state_dataset(state: str, source: dict | None = None) -> str: + """Download a state's dataset from Hugging Face.""" try: from huggingface_hub import hf_hub_download except ImportError: @@ -148,14 +186,16 @@ def get_state_dataset(state: str) -> str: "huggingface_hub not installed. Run: pip install huggingface_hub" ) + source = source or state_dataset_source() state_upper = state.upper() - filename = f"states/{state_upper}.h5" + filename = source["filename"].format(state=state_upper) - print(f" Downloading {state_upper} dataset from Hugging Face...") + print(f" Downloading {state_upper} dataset ({source['name']}) from Hugging Face...") dataset_path = hf_hub_download( - repo_id="policyengine/policyengine-us-data", + repo_id=source["repo_id"], filename=filename, repo_type="model", + revision=source.get("revision"), ) print(f" Dataset ready: {dataset_path}") return dataset_path @@ -347,7 +387,13 @@ def apply(self): return DynamicReform -def run_simulations(state: str, reform_params: dict, year: int = 2026, baseline_params: dict | None = None): +def run_simulations( + state: str, + reform_params: dict, + year: int = 2026, + baseline_params: dict | None = None, + state_dataset: dict | None = None, +): """ Run baseline and reform microsimulations. @@ -365,7 +411,7 @@ def run_simulations(state: str, reform_params: dict, year: int = 2026, baseline_ # dataset (populace-us); state reforms use the geocoded state dataset for # district impacts. get_national_dataset() returns None so Microsimulation # uses its default. - dataset = get_national_dataset() if state == "us" else get_state_dataset(state) + dataset = get_national_dataset() if state == "us" else get_state_dataset(state, state_dataset) ReformClass = create_reform_class(reform_params) print(" Running baseline simulation...") @@ -596,6 +642,19 @@ def compute_district_impacts(baseline, reformed, state: str, year: int = 2026) - print(" Warning: Congressional district data not available") return {} + # Every household should sit in one of the state's districts + # (state_fips * 100 + 1..n). Anything else means the dataset uses a + # different encoding or district plan than this script expects. + expected_geoids = {state_fips * 100 + n for n in range(1, num_districts + 1)} + found_geoids = {int(g) for g in unique_geoids} + unexpected = sorted(found_geoids - expected_geoids) + missing = sorted(expected_geoids - found_geoids) + if unexpected or missing: + print( + f" Warning: district GEOIDs don't match {state_upper}'s {num_districts} " + f"districts (unexpected {unexpected[:10]}, missing {missing[:10]})" + ) + # Compute relative change for winners calculation (matching API fix in policyengine-api#3283) absolute_change = reform_income - baseline_income capped_baseline = np.maximum(baseline_income, 1) @@ -760,13 +819,26 @@ def _resolve_pe_us_version(supabase, reform_id: str, reform_params: dict) -> str return current_version -def write_to_supabase(supabase, reform_id: str, impacts: dict, reform_params: dict, analysis_year: int, multi_year: bool = False, baseline_params: dict | None = None): +def district_congress_notes(impacts: dict) -> dict: + """model_notes fields that say which Congress's districts the district + results use. Empty when there are no district results.""" + congress = impacts.get("districtCongress") + if not impacts.get("districtImpacts") or congress is None: + return {} + return {"district_congress": congress} + + +def write_to_supabase(supabase, reform_id: str, impacts: dict, reform_params: dict, analysis_year: int, multi_year: bool = False, baseline_params: dict | None = None, dataset: dict | None = None): """Write impacts to Supabase reform_impacts table. If multi_year=True, stores impacts in model_notes.impacts_by_year[year] instead of overwriting the main impact fields. This allows storing multiple years of impacts. """ pe_us_version = _resolve_pe_us_version(supabase, reform_id, reform_params) + dataset = dataset or { + "name": "policyengine-us-data", + "version": get_installed_version("policyengine-us-data"), + } if multi_year: import json @@ -800,6 +872,9 @@ def write_to_supabase(supabase, reform_id: str, impacts: dict, reform_params: di "districtImpacts": impacts.get("districtImpacts"), "computedAt": impacts["computedAt"], } + congress_notes = district_congress_notes(impacts) + if congress_notes: + impacts_by_year[year_str]["districtCongress"] = congress_notes["district_congress"] # Merge model_notes model_notes = { @@ -807,6 +882,9 @@ def write_to_supabase(supabase, reform_id: str, impacts: dict, reform_params: di "analysis_year": analysis_year, # Most recent year computed "impacts_by_year": impacts_by_year, } + # The root district results are this write's, so the root tag must be too + model_notes.pop("district_congress", None) + model_notes.update(district_congress_notes(impacts)) record = { "id": reform_id, @@ -823,12 +901,13 @@ def write_to_supabase(supabase, reform_id: str, impacts: dict, reform_params: di "baseline_params": baseline_params, "model_notes": model_notes, "policyengine_us_version": pe_us_version, - "dataset_name": "policyengine-us-data", - "dataset_version": get_installed_version("policyengine-us-data"), + "dataset_name": dataset["name"], + "dataset_version": dataset["version"], } else: model_notes = { "analysis_year": analysis_year, + **district_congress_notes(impacts), } record = { @@ -845,8 +924,8 @@ def write_to_supabase(supabase, reform_id: str, impacts: dict, reform_params: di "baseline_params": baseline_params, "model_notes": model_notes, "policyengine_us_version": pe_us_version, - "dataset_name": "policyengine-us-data", - "dataset_version": get_installed_version("policyengine-us-data"), + "dataset_name": dataset["name"], + "dataset_version": dataset["version"], } result = supabase.table("reform_impacts").upsert(record).execute() @@ -926,6 +1005,15 @@ def main(): help="Load a single reform config from a JSON file ({id, state, label, reform}) " "instead of the database. Requires --output; no Supabase needed." ) + parser.add_argument( + "--state-dataset", + type=str, + choices=sorted(STATE_DATASETS), + default=None, + help="State dataset source (default: TRACKER_STATE_DATASET, else " + f"{DEFAULT_STATE_DATASET}). Sets which Congress's districts the " + "district results use." + ) parser.add_argument( "--output", type=str, @@ -982,7 +1070,12 @@ def main(): print(f" {r['id']:30} [{r['state'].upper()}] ({status})") return 0 - print(f"\nProcessing {len(reforms)} reform(s)...") + state_dataset = state_dataset_source(args.state_dataset) + print( + f"\nState dataset: {state_dataset['name']} " + f"({state_dataset['district_congress']}th Congress districts)" + ) + print(f"Processing {len(reforms)} reform(s)...") results = {} @@ -1012,7 +1105,8 @@ def main(): # Run simulations print(" [1/6] Running microsimulations...") baseline, reformed = run_simulations( - state, reform["reform"], sim_year, baseline_params=reform.get("baseline") + state, reform["reform"], sim_year, baseline_params=reform.get("baseline"), + state_dataset=state_dataset, ) # What the bill changes each parameter FROM, under the baseline used. baseline_params = baseline_parameter_values(baseline, reform["reform"]) @@ -1057,6 +1151,20 @@ def main(): } if district_impacts: impacts["districtImpacts"] = district_impacts + impacts["districtCongress"] = state_dataset["district_congress"] + + # Federal runs on the national default (populace-us); state runs + # on the chosen geocoded state dataset. + if state == "us": + dataset = { + "name": "populace-us", + "version": get_installed_version("policyengine-us-data"), + } + else: + dataset = { + "name": state_dataset["dataset_name"], + "version": state_dataset_version(state_dataset), + } if offline: # Build the same record write_to_supabase would upsert, but save @@ -1074,12 +1182,13 @@ def main(): "district_impacts": impacts.get("districtImpacts"), "reform_params": reform["reform"], "baseline_params": baseline_params, - "model_notes": {"analysis_year": sim_year}, + "model_notes": { + "analysis_year": sim_year, + **district_congress_notes(impacts), + }, "policyengine_us_version": get_installed_version("policyengine-us"), - # Federal runs on the national default (populace-us); state - # runs on the geocoded policyengine-us-data state files. - "dataset_name": "populace-us" if state == "us" else "policyengine-us-data", - "dataset_version": get_installed_version("policyengine-us-data"), + "dataset_name": dataset["name"], + "dataset_version": dataset["version"], } print(f" Writing record to {args.output}...") with open(args.output, "w") as f: @@ -1089,7 +1198,7 @@ def main(): print(" Writing to Supabase...") write_to_supabase( supabase, reform_id, impacts, reform["reform"], sim_year, args.multi_year, - baseline_params=baseline_params, + baseline_params=baseline_params, dataset=dataset, ) # Set status to in_review (skip if already published to avoid taking bills offline) diff --git a/scripts/test_compute_impacts_datasets.py b/scripts/test_compute_impacts_datasets.py new file mode 100644 index 0000000..64d0c98 --- /dev/null +++ b/scripts/test_compute_impacts_datasets.py @@ -0,0 +1,173 @@ +"""Tests for the state dataset sources and the district Congress tag in +compute_impacts.py. No network, Supabase or microsimulation. Run with: + + uv run --with numpy --with pyyaml --with python-dotenv --with pytest \ + pytest scripts/test_compute_impacts_datasets.py +""" + +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).parent)) + +import compute_impacts as ci # noqa: E402 + + +class _Result: + def __init__(self, data): + self.data = data + + +class _Query: + def __init__(self, table, op, payload=None): + self.table, self.op, self.payload = table, op, payload + + def eq(self, column, value): + return self + + def execute(self): + if self.op == "upsert": + self.table.upserts.append(self.payload) + return _Result([self.payload]) + return _Result([self.table.existing] if self.table.existing else []) + + +class _Table: + def __init__(self, existing): + self.existing = existing + self.upserts = [] + + def select(self, columns): + return _Query(self, "select") + + def upsert(self, record): + return _Query(self, "upsert", record) + + +class FakeSupabase: + def __init__(self, existing=None): + self.reform_impacts = _Table(existing) + + def table(self, name): + assert name == "reform_impacts" + return self.reform_impacts + + +def _impacts(congress=120, districts=True): + impacts = { + "computedAt": "2026-11-12T00:00:00+00:00", + "budgetaryImpact": {}, + "povertyImpact": {}, + "childPovertyImpact": {}, + "winnersLosers": {}, + "decileImpact": {}, + } + if districts: + impacts["districtImpacts"] = {"TX-1": {"avgBenefit": 10}} + impacts["districtCongress"] = congress + return impacts + + +@pytest.fixture(autouse=True) +def _no_env(monkeypatch): + monkeypatch.delenv("TRACKER_STATE_DATASET", raising=False) + monkeypatch.setattr(ci, "get_installed_version", lambda package: "9.9.9") + + +@pytest.fixture +def cd120_source(monkeypatch): + monkeypatch.setitem( + ci.STATE_DATASETS, + "test-cd120", + { + "dataset_name": "test-data", + "repo_id": "example/test-data", + "filename": "states/{state}.h5", + "revision": "abc123", + "district_congress": 120, + "dataset_version": "2026.12.1", + }, + ) + + +def test_default_source_is_the_119th_congress_us_data_files(): + source = ci.state_dataset_source() + assert source["name"] == "us-data-cd119" + assert source["district_congress"] == 119 + assert source["repo_id"] == "policyengine/policyengine-us-data" + assert source["filename"].format(state="TX") == "states/TX.h5" + assert ci.state_dataset_version(source) == "9.9.9" + + +def test_environment_variable_and_argument_choose_the_source(monkeypatch, cd120_source): + monkeypatch.setenv("TRACKER_STATE_DATASET", "test-cd120") + source = ci.state_dataset_source() + assert source["district_congress"] == 120 + assert ci.state_dataset_version(source) == "2026.12.1" + assert ci.state_dataset_source("us-data-cd119")["district_congress"] == 119 + + +def test_unknown_source_is_an_error(): + with pytest.raises(ValueError, match="Unknown state dataset"): + ci.state_dataset_source("no-such-dataset") + + +def test_district_congress_notes_need_district_results_and_a_tag(): + assert ci.district_congress_notes(_impacts(120)) == {"district_congress": 120} + assert ci.district_congress_notes(_impacts(districts=False)) == {} + untagged = _impacts() + del untagged["districtCongress"] + assert ci.district_congress_notes(untagged) == {} + + +def test_single_year_write_tags_the_congress_and_dataset(): + supabase = FakeSupabase() + ci.write_to_supabase( + supabase, "tx-test", _impacts(120), {"p": 1}, 2027, + dataset={"name": "test-data", "version": "2026.12.1"}, + ) + record = supabase.reform_impacts.upserts[-1] + assert record["model_notes"] == {"analysis_year": 2027, "district_congress": 120} + assert record["dataset_name"] == "test-data" + assert record["dataset_version"] == "2026.12.1" + + +def test_write_without_dataset_keeps_the_old_dataset_fields(): + supabase = FakeSupabase() + ci.write_to_supabase(supabase, "tx-test", _impacts(119), {"p": 1}, 2026) + record = supabase.reform_impacts.upserts[-1] + assert record["dataset_name"] == "policyengine-us-data" + assert record["dataset_version"] == "9.9.9" + + +def test_multi_year_write_tags_the_new_year_and_leaves_old_years_alone(): + existing = { + "policyengine_us_version": "1.0.0", + "reform_params": {"p": 1}, + "model_notes": { + "analysis_year": 2026, + "district_congress": 119, + "impacts_by_year": {"2026": {"districtImpacts": {"TX-1": {}}}}, + }, + } + supabase = FakeSupabase(existing) + ci.write_to_supabase(supabase, "tx-test", _impacts(120), {"p": 1}, 2027, multi_year=True) + notes = supabase.reform_impacts.upserts[-1]["model_notes"] + assert notes["district_congress"] == 120 + assert notes["impacts_by_year"]["2027"]["districtCongress"] == 120 + assert "districtCongress" not in notes["impacts_by_year"]["2026"] + + +def test_multi_year_write_without_districts_drops_the_root_tag(): + existing = { + "model_notes": {"analysis_year": 2026, "district_congress": 119, "impacts_by_year": {}}, + } + supabase = FakeSupabase(existing) + ci.write_to_supabase( + supabase, "tx-test", _impacts(districts=False), {"p": 1}, 2027, multi_year=True + ) + notes = supabase.reform_impacts.upserts[-1]["model_notes"] + assert "district_congress" not in notes + assert "districtCongress" not in notes["impacts_by_year"]["2027"] From 52756fcce16205911d8782b9b60b038bd95debf1 Mon Sep 17 00:00:00 2001 From: David Trimmer <178813244+DTrim99@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:14:00 -0500 Subject: [PATCH 3/5] List district results when boundaries can't be drawn; guard ring winding; pin the state files - The card fallback read yearImpacts, which only GenericStateDistrictMap defines, so a 120-tagged analysis in AL, AZ, OK, SC or UT blanked the page, and other states said "District data not available". It now takes the shown year's results and Congress, lists every district in them, and says why there's no map. The fixed district list and its region names (from an older map) are gone. The header's click hint shows only when the map can be drawn. - filterStateDistricts rewinds any feature with an area over a hemisphere, so an inverted boundary file can't fill the map. - us-data-cd119 is pinned to the Hugging Face revision current today (last commit 2026-05-31), and model_notes records it as district_dataset_revision beside district_congress. Tests: render tests for the fallback (AL, NC, a selected year, a failed load, no results), rewind tests, and revision tests in Python. Co-Authored-By: Claude Opus 5.5 --- scripts/compute_impacts.py | 18 ++- scripts/test_compute_impacts_datasets.py | 38 +++++++ src/components/reform/DistrictMap.jsx | 123 +++++++-------------- src/components/reform/DistrictMap.test.jsx | 64 +++++++++++ src/components/reform/districtGeo.js | 24 +++- src/components/reform/districtGeo.test.js | 33 ++++++ 6 files changed, 215 insertions(+), 85 deletions(-) create mode 100644 src/components/reform/DistrictMap.test.jsx diff --git a/scripts/compute_impacts.py b/scripts/compute_impacts.py index ff35d0f..8fe4d20 100644 --- a/scripts/compute_impacts.py +++ b/scripts/compute_impacts.py @@ -146,12 +146,13 @@ def load_reforms_from_db(supabase, reform_id=None): STATE_DATASETS = { # The archived policyengine-us-data files, built from 119th Congress block # assignments (make_block_cd_distributions.py: - # fetch_block_to_district_map(119)). + # fetch_block_to_district_map(119)). Pinned to the repo's head on + # 2026-11-24 (last commit 2026-05-31), so every run reads the same files. "us-data-cd119": { "dataset_name": "policyengine-us-data", "repo_id": "policyengine/policyengine-us-data", "filename": "states/{state}.h5", - "revision": None, + "revision": "21280dca5995e978d706740a8a4b9b7860cfd7b6", "district_congress": 119, }, # Add the 120th Congress source here once the microcosm release that @@ -821,11 +822,15 @@ def _resolve_pe_us_version(supabase, reform_id: str, reform_params: dict) -> str def district_congress_notes(impacts: dict) -> dict: """model_notes fields that say which Congress's districts the district - results use. Empty when there are no district results.""" + results use, and the Hugging Face revision of the state file they came + from. Empty when there are no district results.""" congress = impacts.get("districtCongress") if not impacts.get("districtImpacts") or congress is None: return {} - return {"district_congress": congress} + notes = {"district_congress": congress} + if impacts.get("districtDatasetRevision"): + notes["district_dataset_revision"] = impacts["districtDatasetRevision"] + return notes def write_to_supabase(supabase, reform_id: str, impacts: dict, reform_params: dict, analysis_year: int, multi_year: bool = False, baseline_params: dict | None = None, dataset: dict | None = None): @@ -875,6 +880,8 @@ def write_to_supabase(supabase, reform_id: str, impacts: dict, reform_params: di congress_notes = district_congress_notes(impacts) if congress_notes: impacts_by_year[year_str]["districtCongress"] = congress_notes["district_congress"] + if "district_dataset_revision" in congress_notes: + impacts_by_year[year_str]["districtDatasetRevision"] = congress_notes["district_dataset_revision"] # Merge model_notes model_notes = { @@ -884,6 +891,7 @@ def write_to_supabase(supabase, reform_id: str, impacts: dict, reform_params: di } # The root district results are this write's, so the root tag must be too model_notes.pop("district_congress", None) + model_notes.pop("district_dataset_revision", None) model_notes.update(district_congress_notes(impacts)) record = { @@ -1152,6 +1160,8 @@ def main(): if district_impacts: impacts["districtImpacts"] = district_impacts impacts["districtCongress"] = state_dataset["district_congress"] + if state_dataset.get("revision"): + impacts["districtDatasetRevision"] = state_dataset["revision"] # Federal runs on the national default (populace-us); state runs # on the chosen geocoded state dataset. diff --git a/scripts/test_compute_impacts_datasets.py b/scripts/test_compute_impacts_datasets.py index 64d0c98..7a53c42 100644 --- a/scripts/test_compute_impacts_datasets.py +++ b/scripts/test_compute_impacts_datasets.py @@ -98,6 +98,7 @@ def test_default_source_is_the_119th_congress_us_data_files(): assert source["district_congress"] == 119 assert source["repo_id"] == "policyengine/policyengine-us-data" assert source["filename"].format(state="TX") == "states/TX.h5" + assert source["revision"] == "21280dca5995e978d706740a8a4b9b7860cfd7b6" assert ci.state_dataset_version(source) == "9.9.9" @@ -171,3 +172,40 @@ def test_multi_year_write_without_districts_drops_the_root_tag(): notes = supabase.reform_impacts.upserts[-1]["model_notes"] assert "district_congress" not in notes assert "districtCongress" not in notes["impacts_by_year"]["2027"] + + +def test_district_notes_record_the_state_file_revision(): + impacts = _impacts(119) + impacts["districtDatasetRevision"] = "abc123" + assert ci.district_congress_notes(impacts) == { + "district_congress": 119, + "district_dataset_revision": "abc123", + } + impacts_without_districts = _impacts(districts=False) + impacts_without_districts["districtDatasetRevision"] = "abc123" + assert ci.district_congress_notes(impacts_without_districts) == {} + + +def test_multi_year_write_replaces_the_root_revision_and_tags_the_year(): + existing = { + "model_notes": { + "analysis_year": 2026, + "district_congress": 119, + "district_dataset_revision": "old", + "impacts_by_year": {"2026": {"districtImpacts": {"TX-1": {}}, "districtDatasetRevision": "old"}}, + }, + } + supabase = FakeSupabase(existing) + untagged = _impacts(120) + ci.write_to_supabase(supabase, "tx-test", untagged, {"p": 1}, 2027, multi_year=True) + notes = supabase.reform_impacts.upserts[-1]["model_notes"] + assert "district_dataset_revision" not in notes + assert "districtDatasetRevision" not in notes["impacts_by_year"]["2027"] + assert notes["impacts_by_year"]["2026"]["districtDatasetRevision"] == "old" + + tagged = _impacts(120) + tagged["districtDatasetRevision"] = "new" + ci.write_to_supabase(supabase, "tx-test", tagged, {"p": 1}, 2028, multi_year=True) + notes = supabase.reform_impacts.upserts[-1]["model_notes"] + assert notes["district_dataset_revision"] == "new" + assert notes["impacts_by_year"]["2028"]["districtDatasetRevision"] == "new" diff --git a/src/components/reform/DistrictMap.jsx b/src/components/reform/DistrictMap.jsx index 1f52acc..932135c 100644 --- a/src/components/reform/DistrictMap.jsx +++ b/src/components/reform/DistrictMap.jsx @@ -12,61 +12,15 @@ import { colors, typography, spacing } from "../../designTokens"; import { useData } from "../../context/DataContext"; import { track } from "../../lib/analytics"; import { + DRAWABLE_CONGRESSES, congressLabel, districtCongressOf, districtNumberOf, isAtLarge, loadStateDistrictsGeo, + ordinal, } from "./districtGeo"; -// Generic district visualization for other states (card-based grid) -const STATE_DISTRICTS = { - AL: [ - { id: "1", name: "District 1", region: "Mobile & Southwest" }, - { id: "2", name: "District 2", region: "Dothan & Southeast" }, - { id: "3", name: "District 3", region: "East Alabama" }, - { id: "4", name: "District 4", region: "North Central" }, - { id: "5", name: "District 5", region: "Huntsville & North" }, - { id: "6", name: "District 6", region: "Birmingham Suburbs" }, - { id: "7", name: "District 7", region: "Birmingham & Black Belt" }, - ], - AK: [{ id: "AL", name: "At-Large", region: "Statewide" }], - AZ: [ - { id: "1", name: "District 1", region: "Northeast & Rural" }, - { id: "2", name: "District 2", region: "Southern Arizona" }, - { id: "3", name: "District 3", region: "West Phoenix" }, - { id: "4", name: "District 4", region: "North & West Phoenix" }, - { id: "5", name: "District 5", region: "East Valley" }, - { id: "6", name: "District 6", region: "Scottsdale & East" }, - { id: "7", name: "District 7", region: "South Phoenix" }, - { id: "8", name: "District 8", region: "Northwest Phoenix" }, - { id: "9", name: "District 9", region: "Central Phoenix" }, - ], - UT: [ - { id: "1", name: "District 1", region: "Northern Utah" }, - { id: "2", name: "District 2", region: "Western & Rural Utah" }, - { id: "3", name: "District 3", region: "Central & Eastern Utah" }, - { id: "4", name: "District 4", region: "Salt Lake Suburbs" }, - ], - SC: [ - { id: "1", name: "District 1", region: "Charleston & Coast" }, - { id: "2", name: "District 2", region: "Columbia & Midlands" }, - { id: "3", name: "District 3", region: "Upstate West" }, - { id: "4", name: "District 4", region: "Greenville-Spartanburg" }, - { id: "5", name: "District 5", region: "Rock Hill & North Central" }, - { id: "6", name: "District 6", region: "Pee Dee & Rural East" }, - { id: "7", name: "District 7", region: "Myrtle Beach & Northeast" }, - ], - OK: [ - { id: "1", name: "District 1", region: "Tulsa Area" }, - { id: "2", name: "District 2", region: "Eastern Oklahoma" }, - { id: "3", name: "District 3", region: "Western Oklahoma" }, - { id: "4", name: "District 4", region: "South Central Oklahoma" }, - { id: "5", name: "District 5", region: "Oklahoma City Area" }, - ], - // Add more states as needed... -}; - const ArrowUpIcon = () => ( @@ -178,14 +132,18 @@ function StatBox({ label, value, color }) { ); } -// Fallback card-based view for states without SVG maps -function CardBasedDistrictView({ stateAbbr, reformId }) { - const districts = STATE_DISTRICTS[stateAbbr]; - const { getImpact } = useData(); - const reformImpacts = getImpact(reformId); - const hasDistrictData = reformImpacts?.districtImpacts; - - if (!districts) { +// Fallback when the district boundaries can't be drawn: this app has no +// boundary file for the analysis's Congress, or the file failed to load. +// Lists the shown year's district results without a map. +export function CardBasedDistrictView({ stateAbbr, yearImpacts, congress }) { + const districtImpacts = yearImpacts?.districtImpacts || {}; + const prefix = `${stateAbbr}-`; + const districts = Object.keys(districtImpacts) + .filter((id) => id.startsWith(prefix)) + .map((id) => ({ id, num: id.slice(prefix.length) })) + .sort((a, b) => (parseInt(a.num, 10) || 0) - (parseInt(b.num, 10) || 0)); + + if (districts.length === 0) { return (
- District data not available for this state + District results are not available for this analysis

); } - const maxBenefit = hasDistrictData - ? Math.max(...districts.map(d => Math.abs(yearImpacts.districtImpacts[`${stateAbbr}-${d.id}`]?.avgBenefit || 0))) - : 100; + const note = DRAWABLE_CONGRESSES.includes(congress) + ? "The district map didn't load, so results are listed by district." + : `District boundaries for the ${ordinal(congress)} Congress aren't available in this app yet, so results are listed by district.`; + const maxBenefit = Math.max( + ...districts.map((d) => Math.abs(districtImpacts[d.id]?.avgBenefit || 0)), + 1 + ); return ( -
+
+

+ {note} +

+
{districts.map((district) => { - const impact = hasDistrictData - ? yearImpacts.districtImpacts[`${stateAbbr}-${district.id}`] - : null; + const impact = districtImpacts[district.id]; const avgBenefit = impact?.avgBenefit || 0; const isPositive = avgBenefit > 0; const barWidth = maxBenefit > 0 ? (Math.abs(avgBenefit) / maxBenefit) * 100 : 0; @@ -254,7 +223,7 @@ function CardBasedDistrictView({ stateAbbr, reformId }) { fontWeight: typography.fontWeight.bold, fontFamily: typography.fontFamily.primary, }}> - {district.id} + {district.num}
- {district.name} + District {district.num} -

- {district.region} -

@@ -328,6 +289,7 @@ function CardBasedDistrictView({ stateAbbr, reformId }) {
); })} +
); } @@ -889,7 +851,7 @@ function GenericStateDistrictMap({ stateAbbr, reformId, selectedYear, congress } } if (error || !geoData) { - return ; + return ; } // District number from ui-kit's DISTRICT_ID ("TX-05") @@ -1215,7 +1177,8 @@ export default function DistrictMap({ stateAbbr, reformId }) { fontFamily: typography.fontFamily.body, color: colors.text.secondary, }}> - {congressLabel(congress)}. Click on a district to see detailed impact analysis + {congressLabel(congress)} + {DRAWABLE_CONGRESSES.includes(congress) ? ". Click on a district to see detailed impact analysis" : ""}

diff --git a/src/components/reform/DistrictMap.test.jsx b/src/components/reform/DistrictMap.test.jsx new file mode 100644 index 0000000..df1e24d --- /dev/null +++ b/src/components/reform/DistrictMap.test.jsx @@ -0,0 +1,64 @@ +import { describe, it, expect, vi } from "vitest"; +import { render, screen } from "@testing-library/react"; + +let mockImpacts = null; +vi.mock("../../context/DataContext", () => ({ + useData: () => ({ getImpact: () => mockImpacts }), +})); +vi.mock("../../lib/analytics", () => ({ track: vi.fn() })); +vi.mock("@policyengine/ui-kit/visualization", () => ({ + loadCongressionalDistrictsGeo: vi.fn(async () => { + throw new Error("boundary file failed to load"); + }), +})); + +import DistrictMap, { CardBasedDistrictView } from "./DistrictMap"; + +const results = (state, count) => + Object.fromEntries( + Array.from({ length: count }, (_, i) => [`${state}-${i + 1}`, { avgBenefit: (i + 1) * 10 }]) + ); + +describe("district results without a drawable map", () => { + it("lists Alabama's districts when the analysis is tagged with the 120th Congress", async () => { + mockImpacts = { districtImpacts: results("AL", 7), modelNotes: { district_congress: 120 } }; + render(); + expect(await screen.findByText("District 7")).toBeInTheDocument(); + expect(screen.getByText(/120th Congress aren't available in this app yet/)).toBeInTheDocument(); + expect(screen.queryByText(/Click on a district/)).not.toBeInTheDocument(); + }); + + it("lists every North Carolina district instead of saying data is missing", async () => { + mockImpacts = { districtImpacts: results("NC", 14), modelNotes: { district_congress: 120 } }; + render(); + expect(await screen.findByText("District 14")).toBeInTheDocument(); + expect(screen.queryByText(/not available for this/)).not.toBeInTheDocument(); + }); + + it("uses the selected year's results and that year's tag", async () => { + mockImpacts = { + districtImpacts: results("UT", 4), + modelNotes: { district_congress: 120 }, + impactsByYear: { + 2026: { districtImpacts: results("UT", 4) }, + 2027: { districtImpacts: { "UT-1": { avgBenefit: 99 } }, districtCongress: 120 }, + }, + }; + render(); + expect(screen.getByText("District 1")).toBeInTheDocument(); + expect(screen.getByText("+$99")).toBeInTheDocument(); + expect(screen.queryByText("District 2")).not.toBeInTheDocument(); + }); + + it("explains a failed load of a drawable Congress's boundaries", async () => { + mockImpacts = { districtImpacts: results("SC", 7) }; + render(); + expect(await screen.findByText(/The district map didn't load/)).toBeInTheDocument(); + expect(screen.getByText("District 7")).toBeInTheDocument(); + }); + + it("says when an analysis has no district results", () => { + render(); + expect(screen.getByText("District results are not available for this analysis")).toBeInTheDocument(); + }); +}); diff --git a/src/components/reform/districtGeo.js b/src/components/reform/districtGeo.js index 44fa058..e06bb92 100644 --- a/src/components/reform/districtGeo.js +++ b/src/components/reform/districtGeo.js @@ -1,3 +1,4 @@ +import { geoArea } from "d3-geo"; import { loadCongressionalDistrictsGeo } from "@policyengine/ui-kit/visualization"; // The Congress whose districts an analysis without a tag was computed on. @@ -55,6 +56,27 @@ export function isAtLarge(properties) { return /at large/i.test(properties?.NAMELSAD || ""); } +/** + * A feature whose rings run the wrong way for d3-geo, rewound. + * + * d3-geo reads a ring wound the other way as the whole globe minus the + * district, so the feature has an area over a hemisphere, fills the map as a + * rectangle and gets a misplaced centroid. Reversing every ring fixes it. + * Correctly wound features come back unchanged. + */ +export function rewindIfInverted(feature) { + const geometry = feature?.geometry; + if (!geometry || geoArea(feature) <= 2 * Math.PI) return feature; + const reverseRings = (rings) => rings.map((ring) => [...ring].reverse()); + if (geometry.type === "Polygon") { + return { ...feature, geometry: { ...geometry, coordinates: reverseRings(geometry.coordinates) } }; + } + if (geometry.type === "MultiPolygon") { + return { ...feature, geometry: { ...geometry, coordinates: geometry.coordinates.map(reverseRings) } }; + } + return feature; +} + /** Keep one state's districts from a national boundary file. */ export function filterStateDistricts(geo, stateAbbr, congress) { const prefix = `${stateAbbr}-`; @@ -69,7 +91,7 @@ export function filterStateDistricts(geo, stateAbbr, congress) { `Asked for ${ordinal(congress)} Congress districts but got the ${ordinal(Number(session))}` ); } - return { type: "FeatureCollection", features }; + return { type: "FeatureCollection", features: features.map(rewindIfInverted) }; } const cache = new Map(); diff --git a/src/components/reform/districtGeo.test.js b/src/components/reform/districtGeo.test.js index 58eb9b2..ec85e84 100644 --- a/src/components/reform/districtGeo.test.js +++ b/src/components/reform/districtGeo.test.js @@ -20,7 +20,9 @@ import { isAtLarge, loadStateDistrictsGeo, ordinal, + rewindIfInverted, } from "./districtGeo"; +import { geoArea } from "d3-geo"; describe("districtCongressOf", () => { it("defaults untagged analyses to the 119th Congress", () => { @@ -103,3 +105,34 @@ describe("loadStateDistrictsGeo", () => { await expect(loadStateDistrictsGeo("TX", 120)).rejects.toThrow(/no 120th Congress/); }); }); + +describe("rewindIfInverted", () => { + // A one-degree square near Austin, wound clockwise as d3-geo expects. + const ring = [[-98, 30], [-98, 31], [-97, 31], [-97, 30], [-98, 30]]; + const feature = (coordinates, type = "Polygon") => ({ + type: "Feature", + properties: { DISTRICT_ID: "TX-10", CDSESSN: "120" }, + geometry: { type, coordinates }, + }); + + it("leaves a correctly wound feature unchanged", () => { + const ok = feature([ring]); + expect(geoArea(ok)).toBeLessThan(2 * Math.PI); + expect(rewindIfInverted(ok)).toBe(ok); + }); + + it("rewinds inverted polygons and multipolygons", () => { + const inverted = feature([[...ring].reverse()]); + expect(geoArea(inverted)).toBeGreaterThan(2 * Math.PI); + expect(geoArea(rewindIfInverted(inverted))).toBeLessThan(2 * Math.PI); + + const invertedMulti = feature([[[...ring].reverse()]], "MultiPolygon"); + expect(geoArea(rewindIfInverted(invertedMulti))).toBeLessThan(2 * Math.PI); + }); + + it("is applied when a state's districts are filtered", () => { + const geo = { type: "FeatureCollection", features: [feature([[...ring].reverse()])] }; + const { features } = filterStateDistricts(geo, "TX", 120); + expect(geoArea(features[0])).toBeLessThan(2 * Math.PI); + }); +}); From c89066991ed7c978afe5040ad83dc0ee94c1c41a Mon Sep 17 00:00:00 2001 From: David Trimmer <178813244+DTrim99@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:32:54 -0500 Subject: [PATCH 4/5] Bump ui-kit to 0.15.0 and draw 120th Congress districts ui-kit 0.15.0 (PolicyEngine/policyengine-ui-kit#41) ships the 120th Congress boundaries, so analyses tagged 120 now draw on them instead of falling back to the district list. Other Congresses still fall back. Co-Authored-By: Claude Opus 5.5 --- bun.lock | 4 +- package.json | 2 +- src/components/reform/DistrictMap.test.jsx | 59 +++++++++++++++++++--- src/components/reform/districtGeo.js | 13 ++--- src/components/reform/districtGeo.test.js | 28 ++++++---- 5 files changed, 81 insertions(+), 25 deletions(-) diff --git a/bun.lock b/bun.lock index 48e72d6..d796ee8 100644 --- a/bun.lock +++ b/bun.lock @@ -6,7 +6,7 @@ "name": "state-legislative-tracker", "dependencies": { "@policyengine/api-client": "^0.1.1", - "@policyengine/ui-kit": "^0.9.0", + "@policyengine/ui-kit": "^0.15.0", "@supabase/supabase-js": "^2.95.3", "d3-geo": "^3.1.1", "html-to-image": "^1.11.13", @@ -285,7 +285,7 @@ "@policyengine/api-client": ["@policyengine/api-client@0.1.1", "", {}, "sha512-zomphBy4FC+3FJHU5eL1BH14IgnwGIAm0r1DoZUgNz/MTLTI4jgUtY8DdK+vVuHlQrWWkb7+1BifWm7HMxYhfQ=="], - "@policyengine/ui-kit": ["@policyengine/ui-kit@0.9.0", "", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "cmdk": "^1.1.1", "d3-geo": "^3.1.0", "dayjs": "^1.11.13", "lucide-react": "^0.577.0", "radix-ui": "^1.4.3", "tailwind-merge": "^3.5.0", "tw-animate-css": "^1.4.0" }, "peerDependencies": { "react": ">=19", "react-dom": ">=19", "recharts": ">=2.12" } }, "sha512-oPqMSr+qSdY/63xZ8b7dO3q5Bhceg5UQCiZ/m4tOqcywviQk5VO8FKzkUR8pzmFIv8Q4TB3b2OB0ZKfo6UzHQw=="], + "@policyengine/ui-kit": ["@policyengine/ui-kit@0.15.0", "", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "cmdk": "^1.1.1", "d3-geo": "^3.1.0", "dayjs": "^1.11.13", "lucide-react": "^0.577.0", "radix-ui": "^1.4.3", "tailwind-merge": "^3.5.0", "tw-animate-css": "^1.4.0" }, "peerDependencies": { "react": ">=19", "react-dom": ">=19", "recharts": ">=2.12" } }, "sha512-jX9spwrZcsFNzLJZcFngqqe86irOKCwoy7plLTQsPS1JRFddoj+WBHyv2iu2mC6So0qlHwVwApyymbq4JJFz5Q=="], "@posthog/core": ["@posthog/core@1.28.4", "", { "dependencies": { "@posthog/types": "1.372.10" } }, "sha512-wmtUYHYqA3zIAKDKvYWRNWAQsWOIBwxV08e+bWzVy0wQQzpaS/LzzRupXWRMRrLOk+1x3JKFxbqA3n0QGvpqsQ=="], diff --git a/package.json b/package.json index c43da56..17a8efc 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ }, "dependencies": { "@policyengine/api-client": "^0.1.1", - "@policyengine/ui-kit": "^0.9.0", + "@policyengine/ui-kit": "^0.15.0", "@supabase/supabase-js": "^2.95.3", "d3-geo": "^3.1.1", "html-to-image": "^1.11.13", diff --git a/src/components/reform/DistrictMap.test.jsx b/src/components/reform/DistrictMap.test.jsx index df1e24d..4b63c77 100644 --- a/src/components/reform/DistrictMap.test.jsx +++ b/src/components/reform/DistrictMap.test.jsx @@ -1,37 +1,82 @@ -import { describe, it, expect, vi } from "vitest"; -import { render, screen } from "@testing-library/react"; +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { render, screen, waitFor } from "@testing-library/react"; let mockImpacts = null; +// The boundary file the loader returns; null makes the load fail. +let mockGeo = null; vi.mock("../../context/DataContext", () => ({ useData: () => ({ getImpact: () => mockImpacts }), })); vi.mock("../../lib/analytics", () => ({ track: vi.fn() })); vi.mock("@policyengine/ui-kit/visualization", () => ({ loadCongressionalDistrictsGeo: vi.fn(async () => { - throw new Error("boundary file failed to load"); + if (!mockGeo) throw new Error("boundary file failed to load"); + return mockGeo; }), })); +import { loadCongressionalDistrictsGeo } from "@policyengine/ui-kit/visualization"; import DistrictMap, { CardBasedDistrictView } from "./DistrictMap"; +beforeEach(() => { + mockGeo = null; + loadCongressionalDistrictsGeo.mockClear(); +}); + const results = (state, count) => Object.fromEntries( Array.from({ length: count }, (_, i) => [`${state}-${i + 1}`, { avgBenefit: (i + 1) * 10 }]) ); -describe("district results without a drawable map", () => { - it("lists Alabama's districts when the analysis is tagged with the 120th Congress", async () => { +// One-degree squares in a row, wound clockwise as d3-geo expects. +const boundaries = (state, count, session) => ({ + type: "FeatureCollection", + features: Array.from({ length: count }, (_, i) => { + const x = -88 + i; + return { + type: "Feature", + properties: { + DISTRICT_ID: `${state}-${String(i + 1).padStart(2, "0")}`, + CDSESSN: session, + NAMELSAD: `Congressional District ${i + 1}`, + }, + geometry: { + type: "Polygon", + coordinates: [[[x, 32], [x, 33], [x + 1, 33], [x + 1, 32], [x, 32]]], + }, + }; + }), +}); + +describe("district map for the 120th Congress", () => { + it("draws the 120th boundaries for an analysis tagged 120", async () => { + mockGeo = boundaries("AL", 7, "120"); mockImpacts = { districtImpacts: results("AL", 7), modelNotes: { district_congress: 120 } }; render(); + await waitFor(() => expect(screen.queryByText("Loading map...")).not.toBeInTheDocument()); + expect(loadCongressionalDistrictsGeo).toHaveBeenCalledWith(120); + expect(screen.queryByText(/listed by district/)).not.toBeInTheDocument(); + expect(screen.getByText(/120th Congress districts \(from January 3, 2027\)/)).toBeInTheDocument(); + expect(screen.getByText(/Click on a district/)).toBeInTheDocument(); + }); +}); + +describe("district results without a drawable map", () => { + it("lists Alabama's districts when the analysis is tagged with a Congress the app can't draw", async () => { + mockGeo = boundaries("AL", 7, "119"); + mockImpacts = { districtImpacts: results("AL", 7), modelNotes: { district_congress: 121 } }; + render(); expect(await screen.findByText("District 7")).toBeInTheDocument(); - expect(screen.getByText(/120th Congress aren't available in this app yet/)).toBeInTheDocument(); + expect(screen.getByText(/121st Congress aren't available in this app yet/)).toBeInTheDocument(); expect(screen.queryByText(/Click on a district/)).not.toBeInTheDocument(); + expect(loadCongressionalDistrictsGeo).not.toHaveBeenCalled(); }); - it("lists every North Carolina district instead of saying data is missing", async () => { + it("lists every North Carolina district when the 120th map fails to load", async () => { mockImpacts = { districtImpacts: results("NC", 14), modelNotes: { district_congress: 120 } }; render(); expect(await screen.findByText("District 14")).toBeInTheDocument(); + expect(screen.getByText(/The district map didn't load/)).toBeInTheDocument(); expect(screen.queryByText(/not available for this/)).not.toBeInTheDocument(); }); diff --git a/src/components/reform/districtGeo.js b/src/components/reform/districtGeo.js index e06bb92..1d4bc95 100644 --- a/src/components/reform/districtGeo.js +++ b/src/components/reform/districtGeo.js @@ -7,10 +7,10 @@ import { loadCongressionalDistrictsGeo } from "@policyengine/ui-kit/visualizatio // (make_block_cd_distributions.py: fetch_block_to_district_map(119)). export const DEFAULT_DISTRICT_CONGRESS = 119; -// Congresses whose boundaries the installed ui-kit can draw. ui-kit 0.9's -// loader takes no argument and always returns the 119th file, so add 120 only -// after upgrading to the release with PolicyEngine/policyengine-ui-kit#41. -export const DRAWABLE_CONGRESSES = [119]; +// Congresses whose boundaries the installed ui-kit can draw. ui-kit 0.15 +// (PolicyEngine/policyengine-ui-kit#41) added the 120th; its loader warns and +// returns the 119th file for any other Congress. +export const DRAWABLE_CONGRESSES = [119, 120]; function toCongress(value) { const n = Number(value); @@ -83,8 +83,9 @@ export function filterStateDistricts(geo, stateAbbr, congress) { const features = (geo?.features || []).filter((f) => f.properties?.DISTRICT_ID?.startsWith(prefix) ); - // The file must be the Congress we asked for: an older ui-kit ignores the - // argument and returns the 119th file. + // The file must be the Congress we asked for: ui-kit falls back to the + // 119th file for a Congress it doesn't have, and before 0.15 it ignored the + // argument. const session = features[0]?.properties?.CDSESSN; if (session && Number(session) !== congress) { throw new Error( diff --git a/src/components/reform/districtGeo.test.js b/src/components/reform/districtGeo.test.js index ec85e84..e8a8e6d 100644 --- a/src/components/reform/districtGeo.test.js +++ b/src/components/reform/districtGeo.test.js @@ -1,14 +1,19 @@ import { describe, it, expect, vi } from "vitest"; +// Like ui-kit 0.15: 119 or 120 returns that Congress's file, and anything else +// falls back to the 119th. vi.mock("@policyengine/ui-kit/visualization", () => ({ - loadCongressionalDistrictsGeo: vi.fn(async () => ({ - type: "FeatureCollection", - features: [ - { properties: { DISTRICT_ID: "TX-01", CDSESSN: "119" } }, - { properties: { DISTRICT_ID: "TX-35", CDSESSN: "119" } }, - { properties: { DISTRICT_ID: "TN-09", CDSESSN: "119" } }, - ], - })), + loadCongressionalDistrictsGeo: vi.fn(async (congress = 119) => { + const session = String(congress) === "120" ? "120" : "119"; + return { + type: "FeatureCollection", + features: [ + { properties: { DISTRICT_ID: "TX-01", CDSESSN: session } }, + { properties: { DISTRICT_ID: "TX-35", CDSESSN: session } }, + { properties: { DISTRICT_ID: "TN-09", CDSESSN: session } }, + ], + }; + }), })); import { @@ -101,8 +106,13 @@ describe("loadStateDistrictsGeo", () => { expect(out.features.map((f) => f.properties.DISTRICT_ID)).toEqual(["TX-01", "TX-35"]); }); + it("loads one state's 120th districts", async () => { + const out = await loadStateDistrictsGeo("TX", 120); + expect(out.features.map((f) => f.properties.CDSESSN)).toEqual(["120", "120"]); + }); + it("refuses a Congress the installed ui-kit cannot draw", async () => { - await expect(loadStateDistrictsGeo("TX", 120)).rejects.toThrow(/no 120th Congress/); + await expect(loadStateDistrictsGeo("TX", 118)).rejects.toThrow(/no 118th Congress/); }); }); From 65837677bc9a1cac02c349f7672930959085104b Mon Sep 17 00:00:00 2001 From: David Trimmer <178813244+DTrim99@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:18:12 -0500 Subject: [PATCH 5/5] Show the district click hint only when the map is drawn The header showed "Click on a district" for any drawable Congress, even while the boundaries loaded or after they failed to load. The map now reports whether it drew, and the header shows the hint only then. Co-Authored-By: Claude Opus 5.5 --- src/components/reform/DistrictMap.jsx | 15 +++++++++++++-- src/components/reform/DistrictMap.test.jsx | 5 ++++- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/components/reform/DistrictMap.jsx b/src/components/reform/DistrictMap.jsx index 932135c..7c0feab 100644 --- a/src/components/reform/DistrictMap.jsx +++ b/src/components/reform/DistrictMap.jsx @@ -768,7 +768,7 @@ function DistrictDropdown({ geoData, getDistrictInfo, hasDistrictData, reformImp ); } -function GenericStateDistrictMap({ stateAbbr, reformId, selectedYear, congress }) { +function GenericStateDistrictMap({ stateAbbr, reformId, selectedYear, congress, onMapStatus }) { const [selectedDistrict, setSelectedDistrict] = useState(null); const [geoState, setGeoState] = useState({ key: null, data: null, error: null }); const [zoomLevel, setZoomLevel] = useState(1); @@ -808,6 +808,13 @@ function GenericStateDistrictMap({ stateAbbr, reformId, selectedYear, congress } const geoData = loading ? null : geoState.data; const error = loading ? null : geoState.error; + // Tell the header whether the map is drawn, so its click hint doesn't show + // while loading or after the boundaries fail to load. + const drawn = !loading && !error && Boolean(geoData); + useEffect(() => { + onMapStatus?.({ key: geoKey, drawn }); + }, [onMapStatus, geoKey, drawn]); + // Calculate centroids for district labels const districtCentroids = useMemo(() => { if (!geoData) return {}; @@ -1111,6 +1118,9 @@ export default function DistrictMap({ stateAbbr, reformId }) { const defaultYear = hasMultipleYears ? availableYears[0] : null; const [selectedYear, setSelectedYear] = useState(defaultYear); const congress = districtCongressOf(impacts, selectedYear); + // Whether GenericStateDistrictMap drew this state and Congress's map. + const [mapStatus, setMapStatus] = useState({ key: null, drawn: false }); + const mapDrawn = mapStatus.key === `${stateAbbr}:${congress}` && mapStatus.drawn; // Check if this is a single-district state const isSingleDistrict = SINGLE_DISTRICT_STATES.includes(stateAbbr); @@ -1178,7 +1188,7 @@ export default function DistrictMap({ stateAbbr, reformId }) { color: colors.text.secondary, }}> {congressLabel(congress)} - {DRAWABLE_CONGRESSES.includes(congress) ? ". Click on a district to see detailed impact analysis" : ""} + {mapDrawn ? ". Click on a district to see detailed impact analysis" : ""}

@@ -1217,6 +1227,7 @@ export default function DistrictMap({ stateAbbr, reformId }) { reformId={reformId} selectedYear={selectedYear} congress={congress} + onMapStatus={setMapStatus} /> diff --git a/src/components/reform/DistrictMap.test.jsx b/src/components/reform/DistrictMap.test.jsx index 4b63c77..1bda480 100644 --- a/src/components/reform/DistrictMap.test.jsx +++ b/src/components/reform/DistrictMap.test.jsx @@ -57,7 +57,7 @@ describe("district map for the 120th Congress", () => { expect(loadCongressionalDistrictsGeo).toHaveBeenCalledWith(120); expect(screen.queryByText(/listed by district/)).not.toBeInTheDocument(); expect(screen.getByText(/120th Congress districts \(from January 3, 2027\)/)).toBeInTheDocument(); - expect(screen.getByText(/Click on a district/)).toBeInTheDocument(); + expect(await screen.findByText(/Click on a district/)).toBeInTheDocument(); }); }); @@ -78,6 +78,8 @@ describe("district results without a drawable map", () => { expect(await screen.findByText("District 14")).toBeInTheDocument(); expect(screen.getByText(/The district map didn't load/)).toBeInTheDocument(); expect(screen.queryByText(/not available for this/)).not.toBeInTheDocument(); + expect(screen.getByText(/120th Congress districts/)).toBeInTheDocument(); + expect(screen.queryByText(/Click on a district/)).not.toBeInTheDocument(); }); it("uses the selected year's results and that year's tag", async () => { @@ -100,6 +102,7 @@ describe("district results without a drawable map", () => { render(); expect(await screen.findByText(/The district map didn't load/)).toBeInTheDocument(); expect(screen.getByText("District 7")).toBeInTheDocument(); + expect(screen.queryByText(/Click on a district/)).not.toBeInTheDocument(); }); it("says when an analysis has no district results", () => {