diff --git a/CasualLab/.github/workflows/ci.yml b/CasualLab/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..6f11939d855aa020ed7f74831722e39e7d216200 --- /dev/null +++ b/CasualLab/.github/workflows/ci.yml @@ -0,0 +1,37 @@ +# Synced from open-economic-quant/CasualLab/.github/workflows/ci.yml by +# scripts/sync_ecosystem.py; edit it in the monorepo, not here. +name: CI + +on: + push: + branches: ["main"] + pull_request: + branches: ["main"] + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Python 3.12 + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.12" + cache: pip + cache-dependency-path: pyproject.toml + + - name: Install project with test dependencies + run: | + python -m pip install --upgrade pip + python -m pip install -e ".[dev,dashboard]" + + - name: Run tests + run: python -m pytest diff --git a/CasualLab/.gitignore b/CasualLab/.gitignore index a292ed5fe9c3c793d7fce3e786f01ce805fc3acf..28b027b4354eb35c3d150365e306266968daf948 100644 --- a/CasualLab/.gitignore +++ b/CasualLab/.gitignore @@ -1,25 +1,10 @@ +# upload constraints for casuallab +artifacts/ +raw/ +tmp/ +data/generated/ +.git/ .venv/ __pycache__/ -*.py[cod] -.pytest_cache/ .ruff_cache/ -.coverage -htmlcov/ -.DS_Store -data/raw/* -!data/raw/.gitkeep -data/clean/* -!data/clean/.gitkeep -data/panel/* -!data/panel/.gitkeep -data/nyc_sample/ -data/nyc_full/ -data/manifest*.json -data/diagnostics*.json -artifacts/benchmarks/* -!artifacts/benchmarks/.gitkeep -artifacts/reports/* -!artifacts/reports/.gitkeep -artifacts/simulation/ -artifacts/policy/ -artifacts/nyc_full/ +.pytest_cache/ diff --git a/CasualLab/AGENTS.md b/CasualLab/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..bd7b99b60c6f5089bc504825804fbbb0c87cfd10 --- /dev/null +++ b/CasualLab/AGENTS.md @@ -0,0 +1,27 @@ +# Repository Working Agreement + +This repository evaluates marketplace pricing and incentive experiments under interference. Treat this file as persistent implementation guidance. + +## Non-negotiable research rules + +- Define the estimand and assignment mechanism before choosing an estimator. +- Never call an observational association causal without a defensible identification argument. +- Label every result as empirical/descriptive, semi-synthetic, or theoretical. +- Never hard-code simulated findings, treatment effects, uncertainty, power, or coverage. +- Preserve privacy suppression and measurement-rounding indicators; do not silently treat them as exact values. +- Use deterministic seeds in configs and record them in output metadata. +- Evaluate learned policies on data or simulation draws not used for training. + +## Engineering rules + +- Support a laptop-safe sample mode before full-data mode. +- Keep notebooks thin; reusable logic belongs in `src/casuallab`. +- Put small immutable fixtures in `data/fixtures`; generated data belongs in ignored directories. +- Every generated artifact must include enough metadata to reproduce its inputs and configuration. +- Add or update tests with each behavioral change. Run focused tests during development and the full suite before handoff. +- Update `docs/DECISION_LOG.md` for consequential modeling or identification choices and `STATUS.md` for milestone changes. + +## Completion checks + +Run `make lint`, `make test`, and `make reproduce-sample`. Confirm the dashboard identifies the estimand and distinguishes descriptive real-data moments from simulated causal effects. + diff --git a/CasualLab/LICENSE b/CasualLab/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..93d9c4ee297e613c630043346bd1b5e98c1b28bb --- /dev/null +++ b/CasualLab/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Yang Xiao + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/CasualLab/Makefile b/CasualLab/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..c8c2cc480b484ac54fc00904a3710d8dbefb790a --- /dev/null +++ b/CasualLab/Makefile @@ -0,0 +1,71 @@ +BASE_PYTHON ?= python3 +PYTHON ?= .venv/bin/python +SAMPLE_CONFIG ?= configs/sample.yaml +NYC_SAMPLE_CONFIG ?= configs/nyc_sample.yaml +NYC_FULL_CONFIG ?= configs/full.yaml +SIM_CONFIG ?= configs/simulation.yaml +BENCHMARK_CONFIG ?= configs/benchmark.yaml +POLICY_CONFIG ?= configs/policy.yaml + +.PHONY: setup download-sample validate-nyc-sample validate-nyc-full nyc-simulation-anchor nyc-weather nyc-events nyc-income nyc-benchmark nyc-graph-benchmark equilibrium-benchmark build-panel simulate benchmark interference-benchmark test lint reproduce-sample report dashboard + +setup: + test -x .venv/bin/python || $(BASE_PYTHON) -m venv .venv + .venv/bin/python -m pip install -c constraints.txt -e ".[dev,dashboard]" + +download-sample: + $(PYTHON) -m casuallab download-sample --config $(SAMPLE_CONFIG) + +validate-nyc-sample: + $(PYTHON) -m casuallab build-panel --config $(NYC_SAMPLE_CONFIG) --refresh + +validate-nyc-full: + $(PYTHON) -m casuallab validate-nyc-full --config $(NYC_FULL_CONFIG) --allow-full-download + +nyc-simulation-anchor: + $(PYTHON) -m casuallab nyc-simulation-anchor --simulation-config $(SIM_CONFIG) + +nyc-weather: + $(PYTHON) -m casuallab nyc-weather + +nyc-events: + $(PYTHON) -m casuallab nyc-events + +nyc-income: + $(PYTHON) -m casuallab nyc-income + +nyc-benchmark: + $(PYTHON) -m casuallab nyc-benchmark + +nyc-graph-benchmark: + $(PYTHON) -m casuallab nyc-graph-benchmark + +equilibrium-benchmark: + $(PYTHON) -m casuallab equilibrium-benchmark + +build-panel: + $(PYTHON) -m casuallab build-panel --config $(SAMPLE_CONFIG) + +simulate: + $(PYTHON) -m casuallab simulate --config $(SIM_CONFIG) + +benchmark: + $(PYTHON) -m casuallab benchmark --config $(BENCHMARK_CONFIG) + +interference-benchmark: + $(PYTHON) -m casuallab interference-benchmark + +test: + $(PYTHON) -m pytest + +lint: + $(PYTHON) -m ruff check . + +reproduce-sample: + $(PYTHON) -m casuallab reproduce-sample --config $(SAMPLE_CONFIG) --simulation-config $(SIM_CONFIG) --benchmark-config $(BENCHMARK_CONFIG) --policy-config $(POLICY_CONFIG) + +report: + $(PYTHON) -m casuallab report --benchmark artifacts/benchmarks/benchmark_results.csv + +dashboard: + $(PYTHON) -m streamlit run src/casuallab/dashboard.py diff --git a/CasualLab/STATUS.md b/CasualLab/STATUS.md index 226b1796b92c1e7ea302ac53ebda800056747462..ba46bab085f1f09ae6e55586b8084e574839d5e0 100644 --- a/CasualLab/STATUS.md +++ b/CasualLab/STATUS.md @@ -34,7 +34,8 @@ and any live-market causal conclusion remain future work. 3,839,901,696 bytes (3.58 GiB) and peak footprint 6,313,925,232 bytes (5.88 GiB). - Two single-threaded full-month reruns produced identical bytes for all 201 data files. The data and analysis manifests independently validate 201/201 and 13/13 entries. -- `make test`: 246 tests passed. +- `make test`: 246 tests passed when this record was made; the suite now collects 247 tests + (`pytest --collect-only`, 2026-10-26). - `make lint`: Ruff passed. - `pip check`: no broken requirements. - Streamlit's test runner completed the initial render and an on-demand scenario without an diff --git a/CasualLab/configs/benchmark.yaml b/CasualLab/configs/benchmark.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8542a18df6e42669c6f0aa1c63867fbe1592491c --- /dev/null +++ b/CasualLab/configs/benchmark.yaml @@ -0,0 +1,24 @@ +benchmark: + # Laptop-safe default. Monte Carlo standard errors are reported with every metric. + # Eleven common-seed sensitivity cells remain laptop-safe at this count, including + # rider-only and driver-only intervention-version checks. Exact + # common-random-number pairing applies when geometry is equal; the G=8 cell changes + # panel shape. Every reported Monte Carlo metric includes its simulation standard error. + replications: 24 + seed: 314159 + confidence_level: 0.95 + designs: + - individual + - geo_cluster + - time_block + - switchback + - geo_time + estimators: + - difference_in_means + - regression_adjusted + - cluster_robust + - two_way_cluster_robust + - difference_in_differences + - doubly_robust + target_estimand: market_total_effect + cost_per_market_period: 1.0 diff --git a/CasualLab/configs/full.yaml b/CasualLab/configs/full.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b832abb71fd1544d526d76c790295a19d3d82252 --- /dev/null +++ b/CasualLab/configs/full.yaml @@ -0,0 +1,26 @@ +data: + source: nyc_hvfhv + mode: full + project_root: .. + raw_dir: data/nyc_full/raw + clean_dir: data/nyc_full/clean + panel_dir: data/nyc_full/panel + manifest_path: data/nyc_full/manifest.json + diagnostics_path: data/nyc_full/diagnostics.json + start_datetime: null + end_datetime: null + nyc_year: 2024 + nyc_months: + - 1 + nyc_batch_rows: 100000 + nyc_expected_rows: 19663930 + nyc_expected_bytes: 472757547 + nyc_expected_sha256: 9897de352aa52cea36b70348cc6721b8d4494327ce39c85f0dba83d86ecaa098 + panel_frequency: 1h + complete_panel_grid: true + partition_by: + - source + - service_year + - service_month + page_size: 50000 + timeout_seconds: 300 diff --git a/CasualLab/configs/nyc_sample.yaml b/CasualLab/configs/nyc_sample.yaml new file mode 100644 index 0000000000000000000000000000000000000000..53e6c42cc697f738a78a48a21c063925c391002b --- /dev/null +++ b/CasualLab/configs/nyc_sample.yaml @@ -0,0 +1,27 @@ +data: + source: nyc_hvfhv + mode: sample + project_root: .. + raw_dir: data/nyc_sample/raw + clean_dir: data/nyc_sample/clean + panel_dir: data/nyc_sample/panel + manifest_path: data/nyc_sample/manifest.json + diagnostics_path: data/nyc_sample/diagnostics.json + sample_rows: 10000 + start_datetime: null + end_datetime: null + nyc_year: 2024 + nyc_months: + - 1 + nyc_sample_days: + - 1 + - 10 + - 19 + - 28 + panel_frequency: 1h + complete_panel_grid: false + partition_by: + - source + - service_year + - service_month + timeout_seconds: 300 diff --git a/CasualLab/configs/policy.yaml b/CasualLab/configs/policy.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eabf1890d30b4c2f01fd2f1e8722c8f5e131bda3 --- /dev/null +++ b/CasualLab/configs/policy.yaml @@ -0,0 +1,10 @@ +policy: + # Binding under the calibrated sample market, so allocation rules differ. + budget: 1000.0 + instability_penalty: 0.25 + model_trees: 120 + model_replicates: 4 + seed: 202503 + # Counts are independent simulated markets, not rows. Larger runs are opt-in. + n_train: 12 + n_holdout: 8 diff --git a/CasualLab/configs/sample.yaml b/CasualLab/configs/sample.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a8fa951012af89278f05028dbb9a2f99081b39ae --- /dev/null +++ b/CasualLab/configs/sample.yaml @@ -0,0 +1,24 @@ +data: + source: chicago_tnp + mode: sample + project_root: .. + fixture_path: data/fixtures/chicago_tnp_2022-01-01_300.csv + raw_dir: data/raw + clean_dir: data/clean + panel_dir: data/panel + manifest_path: data/manifest.json + diagnostics_path: data/diagnostics.json + sample_rows: 300 + start_datetime: "2022-01-01T00:00:00" + end_datetime: "2022-01-01T22:59:59" + chicago_dataset_id: m6dm-c72p + panel_frequency: 1h + complete_panel_grid: false + partition_by: + - source + - service_year + - service_month + page_size: 50000 + max_pages: 1 + timeout_seconds: 120 + diff --git a/CasualLab/configs/simulation.yaml b/CasualLab/configs/simulation.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c328b1f83afc291d1830a7ab8c5340fb79403071 --- /dev/null +++ b/CasualLab/configs/simulation.yaml @@ -0,0 +1,41 @@ +simulation: + n_zones: 4 + n_periods: 48 + periods_per_day: 24 + individuals_per_cell: 100 + base_demand: 80.0 + base_supply: 62.0 + capacity_per_driver: 1.35 + matching_efficiency: 0.94 + base_fare: 18.0 + rider_value: 28.0 + operating_cost_per_trip: 8.0 + base_wait_minutes: 5.0 + wait_disutility_per_minute: 0.25 + treatment_version: bundled + discount_rate: 0.10 + incentive_per_driver: 1.50 + # direct_supply_effect is the log supply response at this reference dose. + reference_incentive_per_driver: 1.50 + direct_demand_effect: 0.16 + direct_supply_effect: 0.10 + spillover_strength: 0.15 + persistence: 0.25 + rider_substitution: 0.04 + driver_mobility: 0.06 + zone_heterogeneity_sd: 0.12 + demand_noise_sd: 0.06 + supply_noise_sd: 0.05 + time_pattern_strength: 0.22 + budget: 5000.0 + seed: 202503 + design: + name: geo_cluster + treatment_probability: 0.5 + treatment_saturation: 1.0 + n_clusters: 2 + cluster_size: 2 + treatment_duration: 4 + washout_periods: 0 + budget: 5000.0 + seed: 202503 diff --git a/CasualLab/constraints.txt b/CasualLab/constraints.txt new file mode 100644 index 0000000000000000000000000000000000000000..955fd7e07590c6c23d5446efd1cfe6c355267fdd --- /dev/null +++ b/CasualLab/constraints.txt @@ -0,0 +1,59 @@ +# Reproduction environment captured 2026-08-07 with Python 3.12.13. +# `make setup` applies these constraints to the project and dashboard extras. +altair==6.2.2 +anyio==4.14.2 +attrs==26.1.0 +blinker==1.9.0 +certifi==2026.7.22 +charset-normalizer==3.4.9 +click==8.4.2 +coverage==7.15.4 +duckdb==1.5.5 +h11==0.16.0 +httptools==0.8.0 +idna==3.18 +iniconfig==2.3.0 +itsdangerous==2.2.0 +Jinja2==3.1.6 +joblib==1.5.3 +jsonschema==4.26.0 +jsonschema-specifications==2025.9.1 +MarkupSafe==3.0.3 +narwhals==2.24.0 +numpy==2.5.1 +packaging==26.3 +pandas==3.0.5 +patsy==1.0.2 +pillow==12.3.0 +pluggy==1.6.0 +polars==1.43.2 +polars-runtime-32==1.43.2 +protobuf==7.35.1 +pyarrow==24.0.0 +pydeck==0.9.3 +pyproj==3.7.2 +pyshp==3.1.6 +Pygments==2.20.0 +pytest==9.1.1 +pytest-cov==7.1.0 +python-dateutil==2.9.0.post0 +python-multipart==0.0.32 +PyYAML==6.0.3 +referencing==0.37.0 +requests==2.34.2 +rpds-py==2026.6.3 +ruff==0.16.2 +scikit-learn==1.9.0 +scipy==1.18.0 +six==1.17.0 +shapely==2.1.2 +starlette==1.3.1 +statsmodels==0.14.6 +streamlit==1.61.1 +tenacity==9.1.4 +threadpoolctl==3.6.0 +toml==0.10.2 +typing_extensions==4.16.0 +urllib3==2.7.0 +uvicorn==0.52.1 +websockets==16.1.1 diff --git a/CasualLab/fixtures/README.md b/CasualLab/fixtures/README.md new file mode 100644 index 0000000000000000000000000000000000000000..88899efa21c567bd7c99ce64927684660bea0045 --- /dev/null +++ b/CasualLab/fixtures/README.md @@ -0,0 +1,55 @@ +# Committed public-data fixture + +`chicago_tnp_2022-01-01_300.csv` is an authentic 300-row extract from the City of +Chicago's **Transportation Network Providers – Trips (2018–2022)** dataset. +No trip values are simulated. The API's CSV bytes are concatenated without changing +field values; one common header is retained. + +## Provenance + +- Publisher: City of Chicago +- Socrata dataset ID: `m6dm-c72p` +- Official dataset page: +- API resource: +- Retrieved: 2026-08-07 +- Rows: 300 plus one header row +- Bytes: 70,621 +- SHA-256: `84177e5a72548cc4346df99f0a6b671adb50d7762e23abe041f01b2958b85ad7` + +The extract takes the first 25 records in lexical `trip_id` order at each of 12 +reported timestamps on 2022-01-01: 00:00, 02:00, ..., 22:00 Chicago local time. +Each request uses this Socrata query shape: + +```text +$select=trip_id,trip_start_timestamp,trip_end_timestamp,trip_seconds,trip_miles, +pickup_census_tract,dropoff_census_tract,pickup_community_area, +dropoff_community_area,fare,tip,additional_charges,trip_total, +shared_trip_authorized,trips_pooled,pickup_centroid_latitude, +pickup_centroid_longitude,dropoff_centroid_latitude,dropoff_centroid_longitude +$where=trip_start_timestamp = '2022-01-01T{HH}:00:00' +$order=trip_id +$limit=25 +``` + +The exact URL construction and concatenation are implemented by +`chicago_sample_urls()` and `download_sample(..., refresh=True)` in +`src/casuallab/data.py`. Normal sample runs use this committed file without network +access. A refresh is explicit because the upstream publisher can revise public data; +the checksum makes any revision visible rather than silently replacing the fixture. + +## Measurement and use limitations + +Per the publisher, trip timestamps are rounded to the nearest 15 minutes, fares to +the nearest $2.50, and tips to the nearest $1.00. Some census tracts are suppressed, +and geographic blanks can also mean a trip endpoint was outside Chicago. The cleaned +schema preserves these facts as measurement and missing-or-suppressed flags. + +This is a deterministic engineering fixture, not a probability sample. Its 12 time +strata help exercise a nondegenerate zone-time panel, but it is not representative of +Chicago travel, cannot identify a price elasticity, and cannot support causal claims. + +To verify the immutable fixture locally: + +```bash +shasum -a 256 data/fixtures/chicago_tnp_2022-01-01_300.csv +``` diff --git a/CasualLab/fixtures/chicago_tnp_2022-01-01_300.csv b/CasualLab/fixtures/chicago_tnp_2022-01-01_300.csv new file mode 100644 index 0000000000000000000000000000000000000000..a66ea56ecc8099efb72aa828144cbe2f5d67a46c --- /dev/null +++ b/CasualLab/fixtures/chicago_tnp_2022-01-01_300.csv @@ -0,0 +1,301 @@ +"trip_id","trip_start_timestamp","trip_end_timestamp","trip_seconds","trip_miles","pickup_census_tract","dropoff_census_tract","pickup_community_area","dropoff_community_area","fare","tip","additional_charges","trip_total","shared_trip_authorized","trips_pooled","pickup_centroid_latitude","pickup_centroid_longitude","dropoff_centroid_latitude","dropoff_centroid_longitude" +"0023918a32baa84c59a60ec6acd38ef8d8876a55","2022-01-01T00:00:00.000","2022-01-01T00:45:00.000","2123","27.8011",,,"8",,"37.5","0","7.91","45.41","false","1","41.899602111","-87.6333080367",, +"0031f13d0144700e8132ec4ced74bf91b604bafd","2022-01-01T00:00:00.000","2022-01-01T00:00:00.000","308","1.3617","17031071400","17031080400","7","8","5","0","3.75","8.75","false","1","41.922082541","-87.6341560931","41.9074128162","-87.6409015248" +"003b7701b5658afe3415169d091130f15c2d8434","2022-01-01T00:00:00.000","2022-01-01T00:15:00.000","830","3.59","17031080300","17031221400","8","22","10","0","1.02","11.02","false","1","41.9074919303","-87.6357600901","41.9208017043","-87.6945323419" +"003c710f7464bf348349ec4436fea275b97300bd","2022-01-01T00:00:00.000","2022-01-01T00:15:00.000","862","4.7492","17031222200","17031081800","22","8","10","0","3.74","13.74","false","1","41.9159097884","-87.6838259399","41.8932163595","-87.6378442095" +"0066f1154bb7dc467b2d8ce59e8def475a428557","2022-01-01T00:00:00.000","2022-01-01T00:00:00.000","471","0.7196","17031081600","17031081800","8","8","2.5","0","2.36","4.859999999999999","false","1","41.8920726347","-87.6288741572","41.8932163595","-87.6378442095" +"00ac5c7ec5b5540a83e5f60cd19f721ec46256f2","2022-01-01T00:00:00.000","2022-01-01T00:15:00.000","1057","1.0492","17031320100","17031839100","32","32","10","0","2.87","12.870000000000001","false","1","41.8849871918","-87.6209929134","41.8809944707","-87.6327464887" +"00b6c6407848e8f78a989a1b210309450c65fe8f","2022-01-01T00:00:00.000","2022-01-01T00:30:00.000","1332","6.69","17031830900","17031010201","22","1","15","0","3.34","18.34","false","1","41.9286190509","-87.685362024","42.0160105638","-87.680162272" +"01257dfa064e41843dd90d93c437d9fea037ef40","2022-01-01T00:00:00.000","2022-01-01T00:00:00.000","212","0.7139","17031833000","17031833000","28","28","5","0","3.22","8.22","false","1","41.8852813201","-87.6572331997","41.8852813201","-87.6572331997" +"01345804c5bd6c0101bcb26a14d776d569edf97d","2022-01-01T00:00:00.000","2022-01-01T00:15:00.000","962","5.2",,,"23","18","12.5","0","1.02","13.52","false","1","41.9000696026","-87.7209182385","41.9292973683","-87.7980321814" +"01683d623032683e9fcca03967dd2faeaf1141a7","2022-01-01T00:00:00.000","2022-01-01T00:30:00.000","1667","22.34",,,"8",,"32.5","0","1.02","33.52","false","1","41.899602111","-87.6333080367",, +"019e6ffd2756162afe4a35da65b3a90e6a955e23","2022-01-01T00:00:00.000","2022-01-01T00:15:00.000","472","2.3956",,,"25","25","5","0","2.44","7.4399999999999995","false","1","41.8906088526","-87.7560467111","41.8906088526","-87.7560467111" +"01b6b82321b09e07bfa3bcc72aaed2a7e5c96602","2022-01-01T00:00:00.000","2022-01-01T00:00:00.000","337","1.2816","17031071200","17031080300","7","8","5","0","2.36","7.359999999999999","false","1","41.9218549112","-87.6462109769","41.9074919303","-87.6357600901" +"01e46a6327c61dc09f8ca42369a74802a69551bf","2022-01-01T00:00:00.000","2022-01-01T00:15:00.000","215","1.21",,,"22","24","7.5","0","1.02","8.52","false","1","41.9227606205","-87.6991553432","41.9012069941","-87.6763559892" +"02051e517e227650e268bdd0ffe009def9a2ab75","2022-01-01T00:00:00.000","2022-01-01T00:15:00.000","724","9.2394","17031320400","17031691200","32","69","15","0","3.94","18.94","false","1","41.8774061234","-87.6219716519","41.7544341714","-87.632184554" +"0207218776f774621f3dc27af8263d0ad0b539af","2022-01-01T00:00:00.000","2022-01-01T00:15:00.000","889","4.3295",,,"6","28","12.5","0","3.09","15.59","false","1","41.9442266014","-87.6559981815","41.874005383","-87.6635175498" +"02a1d4ebe0c3a506e122af2691563fd9b0b1f442","2022-01-01T00:00:00.000","2022-01-01T00:30:00.000","1099","3.21","17031839100","17031081500","32","8","15","0","0","15","false","1","41.8809944707","-87.6327464887","41.8925077809","-87.6262149064" +"02a26645383576883f66a648e41d1d71ab71aee0","2022-01-01T00:00:00.000","2022-01-01T00:30:00.000","1302","11.112","17031081100","17031400400","8","40","20","0","4.27","24.27","false","1","41.9002212967","-87.6291051864","41.7911260852","-87.6183216222" +"02a6b5fd3b3d6e2e4627f77379e5d39a560cde33","2022-01-01T00:00:00.000","2022-01-01T00:15:00.000","568","2.29","17031330100","17031839000","33","32","15","0","1.02","16.02","false","1","41.859349715","-87.6173580061","41.8710158803","-87.6314065252" +"02bb1e2db87fd98e74b74d311941f47d9e41c1e7","2022-01-01T00:00:00.000","2022-01-01T00:15:00.000","562","2.1751","17031080300","17031280100","8","28","7.5","0","2.86","10.36","false","1","41.9074919303","-87.6357600901","41.8853000224","-87.6428084655" +"02d90f5c5293cb20e3ff31f1329408c924c73539","2022-01-01T00:00:00.000","2022-01-01T00:15:00.000","935","7.4735","17031320400","17031210100","32","21","12.5","0","3.51","16.009999999999998","false","1","41.8774061234","-87.6219716519","41.9428725376","-87.701330291" +"0306ba0a647a46599b611ff3e027e74d8bedeaa9","2022-01-01T00:00:00.000","2022-01-01T00:00:00.000","171","0.7206",,,"19","19","5","0","2.99","7.99","false","1","41.9272609555","-87.7655016086","41.9272609555","-87.7655016086" +"03180e7b1ebad2b2dfaeb38e5c295ea087174770","2022-01-01T00:00:00.000","2022-01-01T00:45:00.000","2619","12.44","17031081401","17031431400","8","43","22.5","0","1.02","23.52","false","1","41.8950334495","-87.6197106717","41.7559614313","-87.551994147" +"032939259b1bb2b8e2e6fc78a858b0ea1ca5efcb","2022-01-01T00:00:00.000","2022-01-01T00:15:00.000","661","1.1051",,,"28","32","5","0","2.36","7.359999999999999","false","1","41.874005383","-87.6635175498","41.8788655841","-87.6251921424" +"03382956e81eba1ab701b2522f9f8b403fa286ca","2022-01-01T00:00:00.000","2022-01-01T00:00:00.000","796","3.0386","17031831900","17031040201","6","4","7.5","0","2.58","10.08","false","1","41.9451704528","-87.6687944391","41.9725808001","-87.6940010612" +"03680a1798466f21d8729a90ab8be32fb968c8ba","2022-01-01T00:00:00.000","2022-01-01T00:00:00.000","226","0.5181","17031062200","17031062100","6","6","5","6","2.51","13.51","false","1","41.9425851797","-87.6566440918","41.9426918444","-87.6517705068" +"001e1cbcde41b2bb67ff1ce263aa80c7c8a162fd","2022-01-01T02:00:00.000","2022-01-01T02:15:00.000","856","3.26","17031832300","17031062100","22","6","35","0","1.02","36.02","false","1","41.9192250505","-87.671445766","41.9426918444","-87.6517705068" +"0023a884e6bd212188940d21454898113d06f2a8","2022-01-01T02:00:00.000","2022-01-01T02:15:00.000","970","6.0751","17031221200","17031081403","22","8","52.5","1","4","57.5","false","1","41.9210845826","-87.704648384","41.8909220259","-87.6188683546" +"00503a62c0251a9e996bd9404a0311e56b167e53","2022-01-01T02:00:00.000","2022-01-01T02:15:00.000","984","6.69","17031081402","17031061100","8","6","95","0","5","100","false","1","41.8919715078","-87.6129454143","41.9491397709","-87.6568039088" +"005a01047edfb0961b85d426d4343e9d65db199a","2022-01-01T02:00:00.000","2022-01-01T02:30:00.000","1131","12.9895",,,"11",,"87.5","14","6.59","108.09","false","1","41.9788295262","-87.771166703",, +"00642dceba4724bd6a6a12b7d8847d2cdc49a051","2022-01-01T02:00:00.000","2022-01-01T02:30:00.000","1336","12.79",,,"28",,"52.5","0","1.02","53.52","false","1","41.874005383","-87.6635175498",, +"007bbf5d69541a9528e10111f69296b78a6762f1","2022-01-01T02:00:00.000","2022-01-01T02:15:00.000","511","1.6963","17031081600","17031080300","8","8","32.5","0","2.36","34.86","false","1","41.8920726347","-87.6288741572","41.9074919303","-87.6357600901" +"008d125c49a2ae018fdf6e50a8fb3806c528afed","2022-01-01T02:00:00.000","2022-01-01T02:15:00.000","1105","5.6495",,,"42","50","20","0","3.83","23.83","false","1","41.7788768603","-87.5949254391","41.7061257523","-87.5982558383" +"00922b86ca2bc802891559359e7435589a9e8920","2022-01-01T02:00:00.000","2022-01-01T02:00:00.000","862","3.8335","17031040600","17031831000","4","22","42.5","0","2.74","45.24","false","1","41.9668340674","-87.6840183712","41.9160052737","-87.6750951155" +"009e5921c066b193a157ff143d4ca581a8bfc5c0","2022-01-01T02:00:00.000","2022-01-01T02:45:00.000","2551","27.2174","17031070101",,"7",,"127.5","0","8.2","135.7","false","1","41.9292629902","-87.6358909539",, +"00a9f2215f00a28a85d04c85e9255a9e097c498a","2022-01-01T02:00:00.000","2022-01-01T02:15:00.000","1184","4.2674","17031081403","17031070500","8","7","92.5","0","3.14","95.64","false","1","41.8909220259","-87.6188683546","41.9289459041","-87.6608925701" +"00b50e4a3c04c1e7e64b23bfdf9b6682831b2c13","2022-01-01T02:00:00.000","2022-01-01T02:15:00.000","869","4.51","17031832000","17031081201","6","8","42.5","0","1.02","43.52","false","1","41.9462945357","-87.6542980837","41.8991556134","-87.6262105324" +"00bec5987aefc771b71969cd53cbcddde245c97a","2022-01-01T02:00:00.000","2022-01-01T02:00:00.000","375","0.95","17031081401","17031320100","8","32","30","0","1.02","31.02","false","1","41.8950334495","-87.6197106717","41.8849871918","-87.6209929134" +"00c4d7bf6c8c148786c9e0c57c12085453ef7a78","2022-01-01T02:00:00.000","2022-01-01T02:30:00.000","2301","25.8816","17031320100",,"32",,"87.5","14","7.37","108.87","false","1","41.8849871918","-87.6209929134",, +"00da76980f502ddd8640663680116bf565b42d20","2022-01-01T02:00:00.000","2022-01-01T02:15:00.000","880","7.7088","17031081202","17031839900","8","60","47.5","0","6.92","54.42","false","1","41.9027880476","-87.6261455896","41.8270879119","-87.6486268165" +"00ef0264630034595f0a78d84c5776653d1460f2","2022-01-01T02:00:00.000","2022-01-01T02:15:00.000","877","5.5002","17031081800","17031062100","8","6","47.5","0","3.1","50.6","false","1","41.8932163595","-87.6378442095","41.9426918444","-87.6517705068" +"00f03d6bac6125bdbd6c69431ed1d9ebff553099","2022-01-01T02:00:00.000","2022-01-01T02:15:00.000","1238","9.8702","17031071100","17031390700","7","39","65","0","4.01","69.01","false","1","41.9217781876","-87.6510618838","41.8059116993","-87.5874792581" +"010d6ce1367e26b0aa619068d92c976dba41b103","2022-01-01T02:00:00.000","2022-01-01T02:30:00.000","1429","8.2715","17031320400","17031061000","32","6","67.5","7","4.38","78.88","false","1","41.8774061234","-87.6219716519","41.9492209135","-87.6519703953" +"01635d02c05f504e5b115eb8470c9f6c45d0f959","2022-01-01T02:00:00.000","2022-01-01T02:15:00.000","872","4.66","17031830700","17031210700","3","21","72.5","0","0","72.5","false","1","41.958055933","-87.6603894557","41.9357064711","-87.7038545435" +"0177ac28129daaf44dd4217e3a0e0f3d46b2df46","2022-01-01T02:00:00.000","2022-01-01T02:15:00.000","1427","5.5315","17031070300","17031283200","7","28","57.5","4","3.1","64.6","false","1","41.9290469366","-87.6513108767","41.8695838595","-87.6592046708" +"01b2a12687f67e92f42bab144cb15d5d79fd980c","2022-01-01T02:00:00.000","2022-01-01T02:00:00.000","291","1.3593","17031071400","17031070300","7","7","22.5","0","2.56","25.06","false","1","41.922082541","-87.6341560931","41.9290469366","-87.6513108767" +"01d4ad4c96b59aea9ad06d7a2c5c3bfa3f3a2a4b","2022-01-01T02:00:00.000","2022-01-01T02:00:00.000","151","0.5207","17031070300","17031070200","7","7","20","0","2.36","22.36","false","1","41.9290469366","-87.6513108767","41.9290776551","-87.6462934762" +"01e48e574840f4c13a8bc47f6a30b55002024376","2022-01-01T02:00:00.000","2022-01-01T02:15:00.000","324","1.4217",,,"77","1","17.5","5","2.36","24.86","false","1","41.9867117999","-87.6634164054","42.0096228806","-87.6701668569" +"01ed90b29422899258d9f55ff633ffa9cbc45577","2022-01-01T02:00:00.000","2022-01-01T02:15:00.000","336","0.7765","17031070400","17031071200","7","7","17.5","0","2.36","19.86","false","1","41.9289672664","-87.6561568309","41.9218549112","-87.6462109769" +"0207dfc652cca0475121ac7dc8bc070b7904a0d9","2022-01-01T02:00:00.000","2022-01-01T02:15:00.000","914","2.61","17031051200","17031060900","5","6","62.5","0","0","62.5","false","1","41.9414224785","-87.6759539319","41.949829346","-87.6439653703" +"022c47b7159d84e4766820715c3a845dc418341c","2022-01-01T02:00:00.000","2022-01-01T02:30:00.000","1159","8.1307",,,"28","13","62.5","0","3.65","66.15","false","1","41.874005383","-87.6635175498","41.9836363072","-87.7235831853" +"0013313e3b2938948a3b11177d8da51916dc2ee0","2022-01-01T04:00:00.000","2022-01-01T04:15:00.000","885","3.7789",,,"28","31","37.5","0","2.96","40.46","false","1","41.874005383","-87.6635175498","41.8502663663","-87.667569312" +"003bdc281cfbc37afdad07eba282f70cce2474b4","2022-01-01T04:00:00.000","2022-01-01T04:00:00.000","595","2.1519","17031081800","17031320600","8","32","30","0","2.45","32.45","false","1","41.8932163595","-87.6378442095","41.8706073724","-87.6221729369" +"00bd868807b1179288b7f4a049deea768a7ea8fa","2022-01-01T04:00:00.000","2022-01-01T04:45:00.000","2412","35.2411",,,"7",,"62.5","0","11.29","73.78999999999999","false","1","41.9226862843","-87.6494887289",, +"00bfe36f94c5e83b6e994c1db10a3dd9f300f85b","2022-01-01T04:00:00.000","2022-01-01T04:15:00.000","937","5.1927","17031330100","17031241500","33","24","25","0","3.97","28.97","false","1","41.859349715","-87.6173580061","41.9083786693","-87.6709450752" +"00d707ddbc19eb64af9b606228b1f297738ef212","2022-01-01T04:00:00.000","2022-01-01T04:00:00.000","352","1.1506",,,"2","2","5","0","2.36","7.359999999999999","false","1","42.001571027","-87.6950125892","42.001571027","-87.6950125892" +"0139ce649d719cafa08b7f47f5709a07746f0b34","2022-01-01T04:00:00.000","2022-01-01T04:00:00.000","555","2.1362","17031062100","17031070600","6","7","15","0","2.39","17.39","false","1","41.9426918444","-87.6517705068","41.9287630064","-87.665676837" +"018c99c7475b5494103c5ef1783a0e1b16649a97","2022-01-01T04:00:00.000","2022-01-01T04:15:00.000","916","5.83",,,"28","60","37.5","10","1.02","48.52","false","1","41.874005383","-87.6635175498","41.8361501547","-87.6487879519" +"0193e92448b517e6fbd84c5f7edfc03aefd6b4ba","2022-01-01T04:00:00.000","2022-01-01T04:15:00.000","387","1.4502","17031061100","17031031502","6","3","12.5","0","2.36","14.86","false","1","41.9491397709","-87.6568039088","41.9636331692","-87.6523653588" +"01e0dbb073ff6a2b42f6d1a619defb81307b3afe","2022-01-01T04:00:00.000","2022-01-01T04:30:00.000","2183","25.4545","17031040202",,"4",,"35","0","9.74","44.74","false","1","41.9798553089","-87.6940960217",, +"020173df2bd92caff31ab1faec561d15172c3a2e","2022-01-01T04:00:00.000","2022-01-01T04:00:00.000","444","2.5347",,,"4","21","7.5","0","2.9","10.4","false","1","41.9751709433","-87.6875155152","41.9386661962","-87.7112105933" +"02138507fe35b0b613edf8fc8a3ca341251954d6","2022-01-01T04:00:00.000","2022-01-01T04:00:00.000","686","2.0592","17031842200","17031833000","8","28","27.5","0","2.37","29.87","false","1","41.9049353016","-87.6499072264","41.8852813201","-87.6572331997" +"027161d703f25ea70442956c220383c5647fbbd8","2022-01-01T04:00:00.000","2022-01-01T04:15:00.000","532","2.734",,,"7","6","17.5","0","2.51","20.009999999999998","false","1","41.9226862843","-87.6494887289","41.9442266014","-87.6559981815" +"029be8dd502726283ed98b174469bfb6799387bc","2022-01-01T04:00:00.000","2022-01-01T04:00:00.000","232","1.3351","17031241400","17031243200","24","24","15","0","2.36","17.36","false","1","41.906025969","-87.6753116216","41.8924331563","-87.6696239301" +"02ba6e4b08f5ea93fc53fa5f110b085c0338ebfc","2022-01-01T04:00:00.000","2022-01-01T04:00:00.000","333","1.8487",,,"24","22","12.5","0","2.36","14.86","false","1","41.9012069941","-87.6763559892","41.9227606205","-87.6991553432" +"02c3dbf1ae2809346d5118ede4a00ef725bacbc8","2022-01-01T04:00:00.000","2022-01-01T04:15:00.000","611","3.474",,,"62",,"12.5","0","2.67","15.17","false","1","41.7929819032","-87.7242081939",, +"031eb93ae2498122ce294aa059b7c9c3c71e92ab","2022-01-01T04:00:00.000","2022-01-01T04:00:00.000","302","1.1473","17031030200","17031030604","77","77","5","1","2.36","8.36","false","1","41.9944422482","-87.6652247765","41.9854724225","-87.6537935286" +"03368f47c7ad7c8868a8a0cc7ccf901d52cf0f42","2022-01-01T04:00:00.000","2022-01-01T04:15:00.000","974","9.362",,,"17","76","30","13","34.2","77.2","false","1","41.9465114202","-87.8060200025","41.9802643146","-87.913624596" +"0389e928364f21bd70b6b4122cdc93efe8a874ad","2022-01-01T04:00:00.000","2022-01-01T04:30:00.000","1324","10.8949",,,"56",,"20","0","4.23","24.23","false","1","41.7925923603","-87.7696154528",, +"03c452529ebe902a1ca696353e04576d505b2a95","2022-01-01T04:00:00.000","2022-01-01T04:00:00.000","481","1.8334","17031062100","17031071100","6","7","12.5","0","2.36","14.86","false","1","41.9426918444","-87.6517705068","41.9217781876","-87.6510618838" +"03fa1e04827e589e803208cca90a3c29001f84c4","2022-01-01T04:00:00.000","2022-01-01T04:15:00.000","699","5.16",,,"8","22","35","0","1.02","36.02","false","1","41.899602111","-87.6333080367","41.9227606205","-87.6991553432" +"0427ed2b7b760a600e03731c85290bac314155e3","2022-01-01T04:00:00.000","2022-01-01T04:30:00.000","1104","5.592",,,"40","65","12.5","0","4.09","16.59","false","1","41.7923572233","-87.6179313803","41.7697780588","-87.7269298425" +"04501656a3be795d1c5996dce6417e3a1495544c","2022-01-01T04:00:00.000","2022-01-01T04:15:00.000","943","5.9422",,,"15","23","12.5","0","3.19","15.69","false","1","41.9540276487","-87.7633990316","41.9000696026","-87.7209182385" +"0495ddd5447706c169d98699b238f4e1079cd5ef","2022-01-01T04:00:00.000","2022-01-01T04:00:00.000","637","2.7897",,,"2","2","7.5","0","2.53","10.03","false","1","42.001571027","-87.6950125892","42.001571027","-87.6950125892" +"04a07c0d41fa5813b2db6569c9efb572e7b727e4","2022-01-01T04:00:00.000","2022-01-01T04:15:00.000","872","3.5351","17031241500","17031063200","24","6","25","0","2.68","27.68","false","1","41.9083786693","-87.6709450752","41.9383912577","-87.6385749205" +"04a68d90d5e490607c0b77a1c2bfa6a6002b55e4","2022-01-01T04:00:00.000","2022-01-01T04:00:00.000","539","2.1265","17031061100","17031071100","6","7","20","0","2.39","22.39","false","1","41.9491397709","-87.6568039088","41.9217781876","-87.6510618838" +"0082ea5f2d3513aa38eacd28d61304bf224e7eec","2022-01-01T06:00:00.000","2022-01-01T06:30:00.000","1783","22.3665",,,"59","76","62.5","11","11.72","85.22","false","1","41.8299223039","-87.6725026464","41.9802643146","-87.913624596" +"00a7dfe4db74b6fdc7bfda0bcfa8f9669c6ce81d","2022-01-01T06:00:00.000","2022-01-01T06:15:00.000","837","4.7189",,,"32","6","27.5","0","2.93","30.43","false","1","41.8788655841","-87.6251921424","41.9442266014","-87.6559981815" +"00f617fdb519e0ac6ceb924f7df9cc5194d72674","2022-01-01T06:00:00.000","2022-01-01T06:30:00.000","1028","4.99",,,"32","7","55","0","0","55","false","1","41.8788655841","-87.6251921424","41.9226862843","-87.6494887289" +"012ebd30d8823130a89043927c3b3a31c49c8ced","2022-01-01T06:00:00.000","2022-01-01T06:30:00.000","1273","14.3197",,,,"8","17.5","0","4.95","22.45","false","1",,,"41.899602111","-87.6333080367" +"02d8799fb4525fe0cd42bb208ea56d3d5ad1f0b7","2022-01-01T06:00:00.000","2022-01-01T06:00:00.000","312","1.5908",,,"61","63","15","0","4.22","19.22","false","1","41.8090182499","-87.6591665992","41.795430631","-87.6964352325" +"02e2f22d052a51c90526b83569947e6deef4f42a","2022-01-01T06:00:00.000","2022-01-01T06:15:00.000","904","6.8806",,,"6","28","27.5","7","3.38","37.88","false","1","41.9442266014","-87.6559981815","41.874005383","-87.6635175498" +"02e71b7565e7cb1f26927d19f4a6b1ec5e0c5fb6","2022-01-01T06:00:00.000","2022-01-01T06:30:00.000","1174","17.513","17031081403","17031980000","8","76","107.5","0","11.05","118.55","false","1","41.8909220259","-87.6188683546","41.9790708201","-87.9030396611" +"03290dbb88641b7f8ecaa159bb69959121eced97","2022-01-01T06:00:00.000","2022-01-01T06:15:00.000","166","0.84",,,"23","22","35","0","1.02","36.02","false","1","41.9000696026","-87.7209182385","41.9227606205","-87.6991553432" +"03ebf2689d2702eca18ac6b211e2eb0cf8fab710","2022-01-01T06:00:00.000","2022-01-01T06:30:00.000","1300","8.08",,,"65","73","45","0","0","45","false","1","41.7697780588","-87.7269298425","41.7174930361","-87.6488950721" +"046469a8603fa6b3aa159bd7599a4f58d255e2da","2022-01-01T06:00:00.000","2022-01-01T06:30:00.000","1108","17.7812","17031839100","17031980000","32","76","47.5","12","10.67","70.17","false","1","41.8809944707","-87.6327464887","41.9790708201","-87.9030396611" +"04ad2a58690a6238176f62069dd922281dd9e67c","2022-01-01T06:00:00.000","2022-01-01T06:15:00.000","816","3.6373",,,"18","15","10","0","4.32","14.32","false","1","41.9292973683","-87.7980321814","41.9540276487","-87.7633990316" +"05121befc76ed9a6eb3d961c76e1eafbd8f506b0","2022-01-01T06:00:00.000","2022-01-01T06:15:00.000","896","7.22",,,"22","31","40","0","1.02","41.02","false","1","41.9227606205","-87.6991553432","41.8502663663","-87.667569312" +"0538a2de4640e411a48611425a2dd350d46a8621","2022-01-01T06:00:00.000","2022-01-01T06:15:00.000","678","3.9002",,,"22","24","17.5","0","3.72","21.22","false","1","41.9227606205","-87.6991553432","41.9012069941","-87.6763559892" +"053de8cbd51c0dd8ba488fd29b3a00ce4d35040a","2022-01-01T06:00:00.000","2022-01-01T06:15:00.000","567","2.74",,,"23","21","32.5","0","1.02","33.52","false","1","41.9000696026","-87.7209182385","41.9386661962","-87.7112105933" +"05798254f3c30b28ec917154356195d718b2f20a","2022-01-01T06:00:00.000","2022-01-01T06:15:00.000","1243","11.72",,,,"76","35","0","6.02","41.019999999999996","false","1",,,"41.9802643146","-87.913624596" +"058c3f262514b65628f0dace5f9dc6c73144a62a","2022-01-01T06:00:00.000","2022-01-01T06:30:00.000","1548","20.1168","17031980000",,"76",,"37.5","0","12.67","50.17","false","1","41.9790708201","-87.9030396611",, +"058e972c32459f3089d815af1277cdfffa58dcf1","2022-01-01T06:00:00.000","2022-01-01T06:15:00.000","637","3.8751",,,"21","23","17.5","0","4.54","22.04","false","1","41.9386661962","-87.7112105933","41.9000696026","-87.7209182385" +"059f0a3f1c554d1d27494bb722e1632e07c35be6","2022-01-01T06:00:00.000","2022-01-01T06:00:00.000","484","3.5561",,,"74","72","7.5","4","3.46","14.96","false","1","41.6948789661","-87.7131924966","41.713148612","-87.6750753124" +"05a5abeb73f772bec8e5107af09596ff4f799920","2022-01-01T06:00:00.000","2022-01-01T06:15:00.000","714","7.2774",,,"59","8","15","0","5.07","20.07","false","1","41.8299223039","-87.6725026464","41.899602111","-87.6333080367" +"05b002bdcb663c2fafe3f03cfc160c5d9305075f","2022-01-01T06:00:00.000","2022-01-01T06:00:00.000","297","0.83",,,"24","24","17.5","0","1.02","18.52","false","1","41.9012069941","-87.6763559892","41.9012069941","-87.6763559892" +"05d3de05a86e0eed066a851f847215c3a3bb23b7","2022-01-01T06:00:00.000","2022-01-01T06:15:00.000","1020","5.0247",,,"23","18","22.5","0","2.99","25.490000000000002","false","1","41.9000696026","-87.7209182385","41.9292973683","-87.7980321814" +"05d63d2b92c1a070d8c7442a575d754fd2508ae8","2022-01-01T06:00:00.000","2022-01-01T06:30:00.000","1483","17.6595",,,"42",,"27.5","0","7.28","34.78","false","1","41.7788768603","-87.5949254391",, +"0627dfe549f5952874898f8281765e4e12c0587f","2022-01-01T06:00:00.000","2022-01-01T06:15:00.000","1111","12.1869","17031320100","17031980100","32","56","35","0","9.5","44.5","false","1","41.8849871918","-87.6209929134","41.785998518","-87.7509342894" +"06e49fd003a7fe1f5b078eec4608ad197890f142","2022-01-01T06:00:00.000","2022-01-01T06:30:00.000","1501","18.11","17031081500","17031980000","8","76","82.5","0","6.02","88.52","false","1","41.8925077809","-87.6262149064","41.9790708201","-87.9030396611" +"07314b9b1d8b1803aca8dcd87280e04e99270691","2022-01-01T06:00:00.000","2022-01-01T06:15:00.000","601","2.9232",,,"8","7","12.5","0","4.89","17.39","false","1","41.899602111","-87.6333080367","41.9226862843","-87.6494887289" +"0029109278840f24fc0c78e28c71c036a571c563","2022-01-01T08:00:00.000","2022-01-01T08:00:00.000","580","3.74",,,"49","71","17.5","0","1.02","18.52","false","1","41.7065878819","-87.6233665115","41.7442051463","-87.6563059862" +"00349f7479b00dc0b5ffb1e4016289dc400e7758","2022-01-01T08:00:00.000","2022-01-01T08:30:00.000","1301","8.71",,,,"19","22.5","0","1.02","23.52","false","1",,,"41.9272609555","-87.7655016086" +"00a2635ee5a442daf8e798a13fef6aaf95675122","2022-01-01T08:00:00.000","2022-01-01T08:00:00.000","478","1.65","17031839000","17031320400","32","32","15","0","1.02","16.02","false","1","41.8710158803","-87.6314065252","41.8774061234","-87.6219716519" +"00a8e02594b39b4e52be397a2fbc8b91050dac21","2022-01-01T08:00:00.000","2022-01-01T08:30:00.000","2636","36.192",,,"7",,"42.5","0","9.54","52.04","false","1","41.9226862843","-87.6494887289",, +"00c020b39716dcb3f58dfe93fc4bb25026507838","2022-01-01T08:00:00.000","2022-01-01T08:15:00.000","1463","18.8595","17031320600","17031980000","32","76","25","0","10.9","35.9","false","1","41.8706073724","-87.6221729369","41.9790708201","-87.9030396611" +"00cf551319730c52aaaa61c044c49d072ed3072d","2022-01-01T08:00:00.000","2022-01-01T08:15:00.000","795","5.213","17031242400","17031281900","24","28","25","0","14.71","39.71","false","1","41.8994222543","-87.684490122","41.8792550844","-87.642648998" +"00d7ac703126918de3aa87f8ac2ca6010f83fea2","2022-01-01T08:00:00.000","2022-01-01T08:15:00.000","818","7.9655","17031030103","17031081600","77","8","17.5","0","3.61","21.11","false","1","41.9955129914","-87.6558149022","41.8920726347","-87.6288741572" +"01af1c2b50f66c13c742bba4f1303451f5090865","2022-01-01T08:00:00.000","2022-01-01T08:00:00.000","387","1.6627",,,"28","31","7.5","1","2.36","10.86","false","1","41.874005383","-87.6635175498","41.8502663663","-87.667569312" +"01ba850df1507754096b6abc0d8fd4ea59101817","2022-01-01T08:00:00.000","2022-01-01T08:00:00.000","481","3.2292",,,"7","8","10","0","2.87","12.870000000000001","false","1","41.9226862843","-87.6494887289","41.899602111","-87.6333080367" +"01db5dd3f645927d6ebcbb8c1ee8c70ff6f144dd","2022-01-01T08:00:00.000","2022-01-01T08:30:00.000","1649","10.3446",,,"68",,"17.5","0","4.64","22.14","false","1","41.7771962546","-87.6424975271",, +"01df8195ecdc3577e2fe79f161364b8d28a70356","2022-01-01T08:00:00.000","2022-01-01T08:00:00.000","358","1.6473",,,"2","4","7.5","0","2.36","9.86","false","1","42.001571027","-87.6950125892","41.9751709433","-87.6875155152" +"01ffed9229a982812b58219aed021654ce5a081c","2022-01-01T08:00:00.000","2022-01-01T08:00:00.000","537","3.01","17031063303","17031081202","6","8","5","0","1.02","6.02","false","1","41.9346504482","-87.6346478774","41.9027880476","-87.6261455896" +"023990ccbcbac3d8004f2dc7f14471273ddec56a","2022-01-01T08:00:00.000","2022-01-01T08:00:00.000","521","2.3798",,,"61","59","12.5","0","3.43","15.93","false","1","41.8090182499","-87.6591665992","41.8299223039","-87.6725026464" +"024fb7d5d8db3579bb0f9eb189ea5cad21ce2671","2022-01-01T08:00:00.000","2022-01-01T08:15:00.000","585","2.8245",,,"2","3","7.5","0","2.53","10.03","false","1","42.001571027","-87.6950125892","41.96581197","-87.6558787862" +"025aaa78470c647f57d9bcb5afc6544061ab5756","2022-01-01T08:00:00.000","2022-01-01T08:15:00.000","525","1.87","17031081500","17031839100","8","32","10","1","1.02","12.02","false","1","41.8925077809","-87.6262149064","41.8809944707","-87.6327464887" +"03307553318faa698bde9b08f9b393159381a9c9","2022-01-01T08:00:00.000","2022-01-01T08:00:00.000","497","2.0842",,,"77","2","15","0","2.38","17.38","false","1","41.9867117999","-87.6634164054","42.001571027","-87.6950125892" +"036de746778aa36f1ac476b88690d917a06b580b","2022-01-01T08:00:00.000","2022-01-01T08:30:00.000","1335","9.2591",,,"7",,"20","0","4.33","24.33","false","1","41.9226862843","-87.6494887289",, +"0396bf6bdc70ff9c02d0604b227bf0acb9c7bd32","2022-01-01T08:00:00.000","2022-01-01T08:15:00.000","648","5.9719",,,,"26","12.5","0","3.19","15.69","false","1",,,"41.8785943576","-87.7302324284" +"03fa76b226ccb8b378839415d138b700c7e2ff98","2022-01-01T08:00:00.000","2022-01-01T08:00:00.000","409","1.08",,,"8","8","10","0","1.02","11.02","false","1","41.899602111","-87.6333080367","41.899602111","-87.6333080367" +"048d5a07676453f3577a08ebd423d4df83760d4b","2022-01-01T08:00:00.000","2022-01-01T08:30:00.000","1562","12.8161","17031330100","17031010201","33","1","17.5","0","5.59","23.09","false","1","41.859349715","-87.6173580061","42.0160105638","-87.680162272" +"058c35c84f145d3cf5f23229b4a249572c8298de","2022-01-01T08:00:00.000","2022-01-01T08:15:00.000","897","7.9302",,,"32","77","15","7","3.61","25.61","false","1","41.8788655841","-87.6251921424","41.9867117999","-87.6634164054" +"065944c82d2a859363a9e56b41b0521c63362558","2022-01-01T08:00:00.000","2022-01-01T08:15:00.000","1112","12.623",,,,,"20","0","4.86","24.86","false","1",,,, +"06708239423ab6b13707e59f9c0b907edcfec651","2022-01-01T08:00:00.000","2022-01-01T08:30:00.000","1433","17.1787",,,,"76","25","0","22.69","47.69","false","1",,,"41.9802643146","-87.913624596" +"0672cad6786190b5d2cf450d92408037c587bf3c","2022-01-01T08:00:00.000","2022-01-01T08:15:00.000","1043","6.8628",,,"46","41","15","0","3.38","18.38","false","1","41.7412427285","-87.551428197","41.794090253","-87.592310855" +"06850c79ff29e390b3d3bab122e926d869b54cf6","2022-01-01T08:00:00.000","2022-01-01T08:15:00.000","1027","4.726","17031310600","17031081500","31","8","12.5","0","2.97","15.47","false","1","41.8563332167","-87.6595642391","41.8925077809","-87.6262149064" +"00041c667e201f28598eae5957e9d8f4701ec32b","2022-01-01T10:00:00.000","2022-01-01T10:00:00.000","621","2.9269",,,"28","24","15","0","2.56","17.56","false","1","41.874005383","-87.6635175498","41.9012069941","-87.6763559892" +"001cb6ca0919a271c015ea30638616e743eef8a7","2022-01-01T10:00:00.000","2022-01-01T10:30:00.000","1637","9.1271",,,"66",,"20","10","4.41","34.41","false","1","41.7718485152","-87.695666342",, +"00eb8e4aabc3e9ad4ca0a163e0d5bc61ff5bc26c","2022-01-01T10:00:00.000","2022-01-01T10:15:00.000","953","5.5269",,,"52","49","10","0","3.78","13.78","false","1","41.707311449","-87.5349029012","41.7065878819","-87.6233665115" +"0174f39260610bbcd82d9dd03d6a6611065bb633","2022-01-01T10:00:00.000","2022-01-01T10:15:00.000","984","13.64",,,,"53","17.5","0","1.02","18.52","false","1",,,"41.6738199043","-87.6357397768" +"01b509495f09563205d6ac3a83bed762a9664203","2022-01-01T10:00:00.000","2022-01-01T10:15:00.000","868","8.5957",,,"8","38","20","11","3.75","34.75","false","1","41.899602111","-87.6333080367","41.8129489392","-87.6178596758" +"020a5c37b7d2cc6b6f6ec71ffd56ec5a59ed2ef8","2022-01-01T10:00:00.000","2022-01-01T10:15:00.000","388","4.0089","17031061902","17031081403","6","8","10","0","2.78","12.78","false","1","41.9431550855","-87.640698076","41.8909220259","-87.6188683546" +"022261a1d795cdec6cd77d739724122c57646907","2022-01-01T10:00:00.000","2022-01-01T10:15:00.000","943","4.8022","17031281900","17031071200","28","7","17.5","0","2.95","20.45","false","1","41.8792550844","-87.642648998","41.9218549112","-87.6462109769" +"022b6111c23f8bbb901c533417f5a6c66448df5a","2022-01-01T10:00:00.000","2022-01-01T10:00:00.000","486","1.8822","17031071500","17031081700","7","8","10","0","3.2","13.2","false","1","41.9146162864","-87.6317173661","41.8920421365","-87.6318639497" +"025d3a3b930751475238b3cd2bddf8ad937eefcd","2022-01-01T10:00:00.000","2022-01-01T10:15:00.000","969","9.0967",,,"15","8","20","0","5.42","25.42","false","1","41.9540276487","-87.7633990316","41.899602111","-87.6333080367" +"0262c7824cea51265dbbec291f8a7c8ecbac2796","2022-01-01T10:00:00.000","2022-01-01T10:00:00.000","760","3.97",,,"1","3","10","0","1.02","11.02","false","1","42.0096228806","-87.6701668569","41.96581197","-87.6558787862" +"027183ad2ee73dad1985ef2d21ec0ea05c215e57","2022-01-01T10:00:00.000","2022-01-01T10:15:00.000","604","2.3612","17031280100","17031081300","28","8","15","5","2.44","22.44","false","1","41.8853000224","-87.6428084655","41.8983317935","-87.6207628651" +"02c42f70bac7063e55c982268ab62da946dd27b2","2022-01-01T10:00:00.000","2022-01-01T10:00:00.000","805","2.3427","17031081300","17031281900","8","28","12.5","0","2.43","14.93","false","1","41.8983317935","-87.6207628651","41.8792550844","-87.642648998" +"0318bfab0780d71ea2c367e33d062bcf6e2ef052","2022-01-01T10:00:00.000","2022-01-01T10:15:00.000","844","4.3026",,,"28",,"10","0","2.84","12.84","false","1","41.874005383","-87.6635175498",, +"03d20aa4b1a8151d225f34e3165b7e25fb02d61d","2022-01-01T10:00:00.000","2022-01-01T10:15:00.000","789","3.2104","17031062900","17031080300","6","8","10","0","2.61","12.61","false","1","41.9362371791","-87.6564115308","41.9074919303","-87.6357600901" +"03ec36a00974f9b39d915d75d56abed942332c15","2022-01-01T10:00:00.000","2022-01-01T10:30:00.000","1404","17.154","17031081700","17031980000","8","76","75","0","11.04","86.03999999999999","false","1","41.8920421365","-87.6318639497","41.9790708201","-87.9030396611" +"040109553e0606b7bbd73126b5ef3f5f079766b4","2022-01-01T10:00:00.000","2022-01-01T10:15:00.000","718","2.9416","17031842200","17031281900","8","28","12.5","0","2.73","15.23","false","1","41.9049353016","-87.6499072264","41.8792550844","-87.642648998" +"040959b6a0bd524a11efe09817a83606d22f8bbd","2022-01-01T10:00:00.000","2022-01-01T10:30:00.000","1946","16.9024","17031070200","17031980000","7","76","30","0","10.49","40.49","false","1","41.9290776551","-87.6462934762","41.9790708201","-87.9030396611" +"040a6202fd529307b0ec8e90f549665ecdebd17e","2022-01-01T10:00:00.000","2022-01-01T10:30:00.000","1069","7.5906",,,"58",,"15","0","3.53","18.53","false","1","41.8173662079","-87.6988607973",, +"04103dda4607a1a23b792a7e569959ea4e105e2c","2022-01-01T10:00:00.000","2022-01-01T10:15:00.000","452","1.92","17031071400","17031081000","7","8","12.5","0","1.02","13.52","false","1","41.922082541","-87.6341560931","41.9002656868","-87.6321092196" +"044b1a883492b13a5f03c319580dae8506a3ec35","2022-01-01T10:00:00.000","2022-01-01T10:00:00.000","656","2.3736","17031081403","17031280100","8","28","15","0","2.44","17.44","false","1","41.8909220259","-87.6188683546","41.8853000224","-87.6428084655" +"0468c857fba58091b2697022cf02d4dc58d6b925","2022-01-01T10:00:00.000","2022-01-01T10:15:00.000","652","3.2826",,,"67","73","10","0","2.64","12.64","false","1","41.7759288274","-87.6665962653","41.7174930361","-87.6488950721" +"04ecd51489ab0580c2a4125dd77589e9a6b6cead","2022-01-01T10:00:00.000","2022-01-01T10:30:00.000","1792","8.9707",,,"56","42","20","0","8.82","28.82","false","1","41.7925923603","-87.7696154528","41.7788768603","-87.5949254391" +"04f624e4f1b89c969c67d23e8db4a0f0a58969ce","2022-01-01T10:00:00.000","2022-01-01T10:00:00.000","306","1.4958",,,"3","3","7.5","0","2.36","9.86","false","1","41.96581197","-87.6558787862","41.96581197","-87.6558787862" +"054b3cd69f9bf524ed1af1423b510f6eda12f31a","2022-01-01T10:00:00.000","2022-01-01T10:30:00.000","1024","12.25","17031980100","17031243400","56","24","27.5","0","6.02","33.519999999999996","false","1","41.785998518","-87.7509342894","41.8925368719","-87.6598643178" +"0566a7bcb4f0627608bb0fd7cd20b858e3b612bd","2022-01-01T10:00:00.000","2022-01-01T10:15:00.000","693","4.2439",,,"22","8","17.5","0","2.83","20.33","false","1","41.9227606205","-87.6991553432","41.899602111","-87.6333080367" +"00141a14714351b327eb4f70872ec8715f1cd1f9","2022-01-01T12:00:00.000","2022-01-01T12:00:00.000","695","3.7664",,,"1",,"10","5","3.18","18.18","false","1","42.0096228806","-87.6701668569",, +"00332b356e8d6d1dbf41c9d6cfa7dcf091ad1001","2022-01-01T12:00:00.000","2022-01-01T12:15:00.000","1297","5.7558","17031040201","17031241400","4","24","15","3","3.15","21.15","false","1","41.9725808001","-87.6940010612","41.906025969","-87.6753116216" +"00b516b6a1ea4e4a28db7c29e2e363dea58b42f0","2022-01-01T12:00:00.000","2022-01-01T12:00:00.000","822","3.6371",,,"51",,"10","0","4.62","14.620000000000001","false","1","41.6906333472","-87.5700582686",, +"01030bf19d9a9759ab08f9eb3f9fb1cd55db78be","2022-01-01T12:00:00.000","2022-01-01T12:15:00.000","375","0.9937",,,"7","7","12.5","7","2.87","22.37","false","1","41.9226862843","-87.6494887289","41.9226862843","-87.6494887289" +"013d597e586723a28387ab69c59649fb38a976f3","2022-01-01T12:00:00.000","2022-01-01T12:30:00.000","1510","14.2565",,,"32","44","52.5","0","12.57","65.07","false","1","41.8788655841","-87.6251921424","41.7402057565","-87.6159695226" +"01579800bdf1e05f869aa07df3aaa89e7d4b4edf","2022-01-01T12:00:00.000","2022-01-01T12:15:00.000","263","1.0916","17031320100","17031081700","32","8","15","0","2.36","17.36","false","1","41.8849871918","-87.6209929134","41.8920421365","-87.6318639497" +"016a5c6306ba737c5b35b4e1d43e9c84b592275b","2022-01-01T12:00:00.000","2022-01-01T12:15:00.000","494","1.2965",,,"71","71","7.5","0","2.65","10.15","false","1","41.7442051463","-87.6563059862","41.7442051463","-87.6563059862" +"01724b2af5b258629879f18334ca4988cc6c1dc7","2022-01-01T12:00:00.000","2022-01-01T12:15:00.000","662","2.7694","17031080300","17031070600","8","7","22.5","4","2.52","29.02","false","1","41.9074919303","-87.6357600901","41.9287630064","-87.665676837" +"0195531ee2b54cae2fd19269428e4dc800dedfd2","2022-01-01T12:00:00.000","2022-01-01T12:15:00.000","705","1.7427","17031081300","17031081402","8","8","30","0","7.87","37.87","false","1","41.8983317935","-87.6207628651","41.8919715078","-87.6129454143" +"01c1574e1124bf6dd626e51c95b44677c2b3542c","2022-01-01T12:00:00.000","2022-01-01T12:15:00.000","1267","10.0448",,,"25","60","15","0","5.31","20.31","false","1","41.8906088526","-87.7560467111","41.8361501547","-87.6487879519" +"01e91b43d0f634834163dde6ff97e9dbd278a5fc","2022-01-01T12:00:00.000","2022-01-01T12:15:00.000","1477","14","17031980000","17031061500","76","6","25","0","9.88","34.88","false","1","41.9790708201","-87.9030396611","41.9452823311","-87.6615450961" +"01fc9d670a5ed9f200ebfd58608fa1a40c7b95d6","2022-01-01T12:00:00.000","2022-01-01T12:15:00.000","694","5.75",,,"28","60","25","4","1.02","30.02","false","1","41.874005383","-87.6635175498","41.8361501547","-87.6487879519" +"020d88eaa51566d24865e6a0f7f61be23427c7a0","2022-01-01T12:00:00.000","2022-01-01T12:00:00.000","801","2.54","17031841900","17031320100","28","32","37.5","7","0","44.5","false","1","41.8679024175","-87.6429586652","41.8849871918","-87.6209929134" +"020e26ac357f7044bedbb6454d7b10d8b272438a","2022-01-01T12:00:00.000","2022-01-01T12:15:00.000","337","1.0898","17031062200","17031832100","6","6","10","0","2.87","12.870000000000001","false","1","41.9425851797","-87.6566440918","41.9528229157","-87.6532439924" +"0212bd8c83f7b54360b933721f8607bef62bcca5","2022-01-01T12:00:00.000","2022-01-01T12:15:00.000","542","1.4945","17031320100","17031839000","32","32","27.5","4","2.36","33.86","false","1","41.8849871918","-87.6209929134","41.8710158803","-87.6314065252" +"02391780804e76ad87cc47b2908550ac7886ffa3","2022-01-01T12:00:00.000","2022-01-01T12:15:00.000","900","3.4745",,,"22","14","10","0","3.71","13.71","false","1","41.9227606205","-87.6991553432","41.968069","-87.7215590627" +"0263ed0edf9dc84700e523f07fc3dc2cb69213dd","2022-01-01T12:00:00.000","2022-01-01T12:15:00.000","881","3.2051","17031063000","17031842300","6","24","10","1","2.61","13.61","false","1","41.9363101308","-87.6515625922","41.8983058696","-87.6536139825" +"028bad4f796e38455319de500e6acc4fb31740d2","2022-01-01T12:00:00.000","2022-01-01T12:00:00.000","512","1.7198","17031839100","17031320100","32","32","20","0","2.36","22.36","false","1","41.8809944707","-87.6327464887","41.8849871918","-87.6209929134" +"02972d1f1bf8d3f1681c0e82c5e29da389e3c68b","2022-01-01T12:00:00.000","2022-01-01T12:00:00.000","449","1.58","17031243000","17031241500","24","24","12.5","2","1.02","15.52","false","1","41.8922767078","-87.6793974791","41.9083786693","-87.6709450752" +"029ac6e3b10cfd89d7a6d154c38b0efee4aae2f6","2022-01-01T12:00:00.000","2022-01-01T12:45:00.000","2066","21.2935",,,,"30","27.5","0","6.71","34.21","false","1",,,"41.8390869059","-87.714003807" +"02a3b588bf6e4315a362e2c03ea5e95215d69d4a","2022-01-01T12:00:00.000","2022-01-01T12:15:00.000","1158","5.1326","17031062100","17031081100","6","8","20","0","3.02","23.02","false","1","41.9426918444","-87.6517705068","41.9002212967","-87.6291051864" +"02c7fe25979bb475c6b4290b86b6adb95a8153c9","2022-01-01T12:00:00.000","2022-01-01T12:15:00.000","542","1.2","17031081800","17031081401","8","8","22.5","0","1.02","23.52","false","1","41.8932163595","-87.6378442095","41.8950334495","-87.6197106717" +"03151b34430008d78d51b3da3f3494b006c78e0c","2022-01-01T12:00:00.000","2022-01-01T12:00:00.000","459","1.3965","17031063301","17031070600","6","7","12.5","0","2.87","15.370000000000001","false","1","41.9345397158","-87.6430228044","41.9287630064","-87.665676837" +"032d46da22430537c6dc50dec43659f7655562b0","2022-01-01T12:00:00.000","2022-01-01T12:00:00.000","353","2.06",,,"40","38","15","0","1.02","16.02","false","1","41.7923572233","-87.6179313803","41.8129489392","-87.6178596758" +"034388c29084a0c8342efc46d6c812a16291aa4f","2022-01-01T12:00:00.000","2022-01-01T12:00:00.000","592","2.6066","17031080400","17031242100","8","24","22.5","2","2.49","26.990000000000002","false","1","41.9074128162","-87.6409015248","41.8996701799","-87.6698377982" +"000bb07b7bc41b9d3a5632c48e5ae2a8d3163df0","2022-01-01T14:00:00.000","2022-01-01T14:15:00.000","369","1.2845","17031320100","17031081100","32","8","22.5","0","2.36","24.86","false","1","41.8849871918","-87.6209929134","41.9002212967","-87.6291051864" +"000e17662c02e4a351696841c2ae67e13bf2533b","2022-01-01T14:00:00.000","2022-01-01T14:30:00.000","1090","6.98","17031830900","17031320100","22","32","20","0","1.02","21.02","false","1","41.9286190509","-87.685362024","41.8849871918","-87.6209929134" +"006bf65be9befecc994e87d821cadccdb6dc7977","2022-01-01T14:00:00.000","2022-01-01T14:15:00.000","518","1.5404","17031320400","17031081700","32","8","17.5","3","2.36","22.86","false","1","41.8774061234","-87.6219716519","41.8920421365","-87.6318639497" +"0079e13c7b09508efd63fcf9fa039097fabbd4fa","2022-01-01T14:00:00.000","2022-01-01T14:00:00.000","348","1.0087","17031062200","17031060800","6","6","17.5","0","2.36","19.86","false","1","41.9425851797","-87.6566440918","41.9534000435","-87.6460070664" +"00ac00d059d288e71ac9026e11f10c67358b6d45","2022-01-01T14:00:00.000","2022-01-01T14:00:00.000","336","1.5438","17031831000","17031842200","22","8","12.5","0","2.36","14.86","false","1","41.9160052737","-87.6750951155","41.9049353016","-87.6499072264" +"00c4bc3be41e2df093bb83614dbeb0c927e3f9d6","2022-01-01T14:00:00.000","2022-01-01T14:00:00.000","206","0.6284","17031081401","17031081300","8","8","15","2","2.36","19.36","false","1","41.8950334495","-87.6197106717","41.8983317935","-87.6207628651" +"014cd2b7c24c3982b7d860fa0879671b0234c27c","2022-01-01T14:00:00.000","2022-01-01T14:00:00.000","283","1.02","17031283800","17031842900","28","28","12.5","0","1.02","13.52","false","1","41.8634226841","-87.6537566193","41.8631181033","-87.672920435" +"01520b20660fadfa8a81bcf5cf6814471bba1b84","2022-01-01T14:00:00.000","2022-01-01T14:00:00.000","631","3.4584","17031260900","17031840700","26","30","12.5","0","2.67","15.17","false","1","41.8710123117","-87.7228130756","41.853834685","-87.6935387966" +"015cdc1624f48aab7c11580d669569ed852fc17f","2022-01-01T14:00:00.000","2022-01-01T14:15:00.000","232","0.3677","17031081500","17031081401","8","8","15","0","2.36","17.36","false","1","41.8925077809","-87.6262149064","41.8950334495","-87.6197106717" +"0160f06d4fe6ea71229f2673e52a3e7eedcf9002","2022-01-01T14:00:00.000","2022-01-01T14:00:00.000","301","0.78","17031081500","17031081700","8","8","30","6","1.02","37.02","false","1","41.8925077809","-87.6262149064","41.8920421365","-87.6318639497" +"016465bc8838502a633fab974111ef5ca9aa744a","2022-01-01T14:00:00.000","2022-01-01T14:30:00.000","1648","13.5839",,,"2","76","27.5","6","10.38","43.88","false","1","42.001571027","-87.6950125892","41.9802643146","-87.913624596" +"01f0612114687c9e9c014bf9547328315bfc10a0","2022-01-01T14:00:00.000","2022-01-01T14:15:00.000","1001","5.4","17031833100","17031063000","28","6","30","0","1.02","31.02","false","1","41.8790669938","-87.657005027","41.9363101308","-87.6515625922" +"01fcedf9eeaa67d8acdd63811374c1fb71b6e567","2022-01-01T14:00:00.000","2022-01-01T14:15:00.000","802","4.6195",,,"75",,"10","0","3.94","13.94","false","1","41.6897299145","-87.6690544032",, +"0224593a4fd4255e93dcd3f406d4f17903cbd729","2022-01-01T14:00:00.000","2022-01-01T14:00:00.000","281","1.0743","17031061500","17031070600","6","7","15","0","2.36","17.36","false","1","41.9452823311","-87.6615450961","41.9287630064","-87.665676837" +"0231091a8823eee0c7d2ac321bf14e9810ac2eac","2022-01-01T14:00:00.000","2022-01-01T14:00:00.000","282","0.6254","17031833100","17031281900","28","28","10","0","2.4","12.4","false","1","41.8790669938","-87.657005027","41.8792550844","-87.642648998" +"02475e2e585e715587c4082e1b159fcfa46bf797","2022-01-01T14:00:00.000","2022-01-01T14:15:00.000","872","2.5562","17031841100","17031320400","34","32","10","5","2.48","17.48","false","1","41.8510178239","-87.6350918563","41.8774061234","-87.6219716519" +"0252a2797cc7aee5c02a0c819e756ec682633772","2022-01-01T14:00:00.000","2022-01-01T14:15:00.000","862","4.1356","17031320100","17031071300","32","7","22.5","5","2.81","30.31","false","1","41.8849871918","-87.6209929134","41.9217783562","-87.6414597588" +"025e4bc34e85a50fd05c52d43eeef3b707b9a2ee","2022-01-01T14:00:00.000","2022-01-01T14:15:00.000","624","2.0288","17031842200","17031081401","8","8","12.5","0","2.37","14.870000000000001","false","1","41.9049353016","-87.6499072264","41.8950334495","-87.6197106717" +"02621aba931fdd440d703a0c8d348b9b2500d313","2022-01-01T14:00:00.000","2022-01-01T14:00:00.000","209","0.4928","17031081000","17031081800","8","8","12.5","0","2.36","14.86","false","1","41.9002656868","-87.6321092196","41.8932163595","-87.6378442095" +"029214e579443b7b3fba68277472efda0cd11c5a","2022-01-01T14:00:00.000","2022-01-01T14:00:00.000","543","1.8073",,,"6","6","12.5","0","2.36","14.86","false","1","41.9442266014","-87.6559981815","41.9442266014","-87.6559981815" +"029d6715e40fe93530a4c998026581ac09ec7956","2022-01-01T14:00:00.000","2022-01-01T14:15:00.000","802","4.1678","17031241500","17031081402","24","8","10","0","2.82","12.82","false","1","41.9083786693","-87.6709450752","41.8919715078","-87.6129454143" +"02bacd4c9d8b6ddf9709b4cbc343932bb8201e1a","2022-01-01T14:00:00.000","2022-01-01T14:00:00.000","420","0.9612","17031241600","17031241400","24","24","7.5","3","2.36","12.86","false","1","41.9066507664","-87.6653376596","41.906025969","-87.6753116216" +"02c9dae192d114e2b3570e4df8229b2a1f284ce7","2022-01-01T14:00:00.000","2022-01-01T14:15:00.000","506","2.4395","17031320600","17031833000","32","28","17.5","0","2.45","19.95","false","1","41.8706073724","-87.6221729369","41.8852813201","-87.6572331997" +"02da53297f34b859e2970ccefe2c4d4126985333","2022-01-01T14:00:00.000","2022-01-01T14:15:00.000","641","2.7122",,,"7","22","12.5","0","2.51","15.01","false","1","41.9226862843","-87.6494887289","41.9227606205","-87.6991553432" +"02f54b668980f5b1225fbf870546edf281038230","2022-01-01T14:00:00.000","2022-01-01T14:15:00.000","969","6.3824",,,,"74","12.5","3","3.28","18.78","false","1",,,"41.6948789661","-87.7131924966" +"0060b79854d4e7871c012675d61a8c5ba700b891","2022-01-01T16:00:00.000","2022-01-01T16:15:00.000","632","2.86","17031060900","17031030800","6","77","17.5","3","1.02","21.52","false","1","41.949829346","-87.6439653703","41.9799124453","-87.6641882421" +"006c6d8b2922006d6724786f309315a7a8bc5ded","2022-01-01T16:00:00.000","2022-01-01T16:00:00.000","279","0.97",,,"75",,"12.5","0","1.02","13.52","false","1","41.6897299145","-87.6690544032",, +"00bfc651dfbacce7feb5e58e64f84719c3678c88","2022-01-01T16:00:00.000","2022-01-01T16:00:00.000","492","2.456",,,"22","22","7.5","0","2.46","9.96","false","1","41.9227606205","-87.6991553432","41.9227606205","-87.6991553432" +"0114183d4dcfd75f3c3e81943b616d20ec007b36","2022-01-01T16:00:00.000","2022-01-01T16:15:00.000","926","3.4948","17031071200","17031833000","7","28","17.5","0","5.59","23.09","false","1","41.9218549112","-87.6462109769","41.8852813201","-87.6572331997" +"012a14d26da9cae53a08327c275967231c50130c","2022-01-01T16:00:00.000","2022-01-01T16:00:00.000","602","3.41",,,"71","67","20","0","1.02","21.02","false","1","41.7442051463","-87.6563059862","41.7759288274","-87.6665962653" +"012c62fe1632e4820a58a79c0c9772c606697ab6","2022-01-01T16:00:00.000","2022-01-01T16:00:00.000","385","1.4244","17031841100","17031839000","34","32","12.5","0","2.87","15.370000000000001","false","1","41.8510178239","-87.6350918563","41.8710158803","-87.6314065252" +"0145e952e8bffaa677e9221362f8d7e8851ab222","2022-01-01T16:00:00.000","2022-01-01T16:15:00.000","852","4.8134","17031330100","17031241500","33","24","30","0","2.95","32.95","false","1","41.859349715","-87.6173580061","41.9083786693","-87.6709450752" +"0149d8dd6d0112bf56f2e3bf075bc031224a140a","2022-01-01T16:00:00.000","2022-01-01T16:00:00.000","325","0.9684","17031320100","17031081500","32","8","12.5","0","3.89","16.39","false","1","41.8849871918","-87.6209929134","41.8925077809","-87.6262149064" +"014db3f06490bf6346b076ef767dbf291cb7f754","2022-01-01T16:00:00.000","2022-01-01T16:00:00.000","411","1.2575","17031330100","17031320400","33","32","7.5","0","2.36","9.86","false","1","41.859349715","-87.6173580061","41.8774061234","-87.6219716519" +"0173cfd33799da3d840b18d055b8b8d8e5440fb1","2022-01-01T16:00:00.000","2022-01-01T16:15:00.000","997","7.1508","17031160700","17031281900","16","28","12.5","2","4.08","18.58","false","1","41.9504044107","-87.7020071282","41.8792550844","-87.642648998" +"020ce9d2f6603a44b9eeaabe4fc17e36d4c8fe06","2022-01-01T16:00:00.000","2022-01-01T16:15:00.000","1547","17.3296","17031081600","17031806600","8",,"40","9","5.58","54.58","false","1","41.8920726347","-87.6288741572",, +"0222a607e4f8e5d67792f402dacc78b1bcd14507","2022-01-01T16:00:00.000","2022-01-01T16:00:00.000","405","1.2152","17031330100","17031320600","33","32","15","3","2.36","20.36","false","1","41.859349715","-87.6173580061","41.8706073724","-87.6221729369" +"023843e8c29f887753cdf4a6423a6816535c3da7","2022-01-01T16:00:00.000","2022-01-01T16:30:00.000","1846","4.3209","17031241600","17031241500","24","24","20","0","2.85","22.85","false","1","41.9066507664","-87.6653376596","41.9083786693","-87.6709450752" +"023a427a868e1455bfaefcefae6b833e1bc538b6","2022-01-01T16:00:00.000","2022-01-01T16:15:00.000","1185","11.0224",,,"23","9","22.5","0","4.25","26.75","false","1","41.9000696026","-87.7209182385","42.0076125931","-87.8137810343" +"024cd11fd84a9f15b0ee961bed5a843aa7cb5fae","2022-01-01T16:00:00.000","2022-01-01T16:00:00.000","329","1.4628",,,"15","15","17.5","0","2.36","19.86","false","1","41.9540276487","-87.7633990316","41.9540276487","-87.7633990316" +"0335c1d4d271c9f3ef87e369c5a2c6648954998f","2022-01-01T16:00:00.000","2022-01-01T16:15:00.000","1112","7.3087","17031320100","17031061200","32","6","27.5","0","3.48","30.98","false","1","41.8849871918","-87.6209929134","41.9490605256","-87.6616429039" +"0355b4d1106cafbb8196b66b0e0b8cc39592aadd","2022-01-01T16:00:00.000","2022-01-01T16:15:00.000","883","5.3",,,"77","6","15","0","1.02","16.02","false","1","41.9867117999","-87.6634164054","41.9442266014","-87.6559981815" +"0398c46b478736b1466c4d23264847a4b4bd957f","2022-01-01T16:00:00.000","2022-01-01T16:15:00.000","703","6.11",,,"10","76","22.5","4","6.02","32.519999999999996","false","1","41.9850151008","-87.8045320063","41.9802643146","-87.913624596" +"039fb0cab0e78f1013067f7b3ed65a659b72560a","2022-01-01T16:00:00.000","2022-01-01T16:15:00.000","764","4.24",,,"6","8","22.5","0","1.02","23.52","false","1","41.9442266014","-87.6559981815","41.899602111","-87.6333080367" +"03adc96e45895e0cd9e04e6fc83f7e7c425a5f3d","2022-01-01T16:00:00.000","2022-01-01T16:15:00.000","554","1.99","17031833000","17031081000","28","8","25","0","1.02","26.02","false","1","41.8852813201","-87.6572331997","41.9002656868","-87.6321092196" +"03ecf3e831813a4b00787eca7b0143b0f8ffc1af","2022-01-01T16:00:00.000","2022-01-01T16:15:00.000","893","3.0787","17031330100","17031081201","33","8","27.5","4","2.59","34.09","false","1","41.859349715","-87.6173580061","41.8991556134","-87.6262105324" +"041baef069f907854eb0584701b2fb7a9710f6bd","2022-01-01T16:00:00.000","2022-01-01T16:15:00.000","550","1.6364","17031081100","17031839100","8","32","10","4","2.36","16.36","false","1","41.9002212967","-87.6291051864","41.8809944707","-87.6327464887" +"046ccd251908d575c8e51f00e078605fa5cca473","2022-01-01T16:00:00.000","2022-01-01T16:00:00.000","364","0.8362","17031081201","17031081700","8","8","7.5","0","3.99","11.49","false","1","41.8991556134","-87.6262105324","41.8920421365","-87.6318639497" +"0476bf165e42623aa22a5a8a67ce8af2d1d19efb","2022-01-01T16:00:00.000","2022-01-01T16:15:00.000","637","2.9912","17031320100","17031281900","32","28","27.5","0","3.07","30.57","false","1","41.8849871918","-87.6209929134","41.8792550844","-87.642648998" +"0478f0421241e0006aa0d8b545ba52375b13bd46","2022-01-01T16:00:00.000","2022-01-01T16:30:00.000","1263","11.567",,,,"76","35","0","9.37","44.37","false","1",,,"41.9802643146","-87.913624596" +"0015c55b4a42cbdaf2b48c9baccafe49f4b0524c","2022-01-01T18:00:00.000","2022-01-01T18:15:00.000","739","5.3097",,,"6","32","10","0","3.06","13.06","false","1","41.9442266014","-87.6559981815","41.8788655841","-87.6251921424" +"0087438c5d92b7e5b07086ad001d04e9c89b0ecc","2022-01-01T18:00:00.000","2022-01-01T18:15:00.000","1159","7.67",,,"35","8","30","0","1.02","31.02","false","1","41.8351179863","-87.6186777673","41.899602111","-87.6333080367" +"008dc34b91450b4045bfbdacac9286ff308a74e2","2022-01-01T18:00:00.000","2022-01-01T18:15:00.000","742","3.6555","17031283100","17031081700","28","8","10","5","2.71","17.71","false","1","41.8692744531","-87.6640472412","41.8920421365","-87.6318639497" +"009eef304799cbfe4bbd66d4418d8446da1112c5","2022-01-01T18:00:00.000","2022-01-01T18:00:00.000","114","0.4061","17031071500","17031071500","7","7","5","0","2.83","7.83","false","1","41.9146162864","-87.6317173661","41.9146162864","-87.6317173661" +"00db795bb0009c1ed7f220d3f9213f8861dbe0a6","2022-01-01T18:00:00.000","2022-01-01T18:15:00.000","347","1.02","17031320100","17031081500","32","8","15","1","1.02","17.02","false","1","41.8849871918","-87.6209929134","41.8925077809","-87.6262149064" +"00f5dcdabb19f589cc8acb8a32648f2ef80ed605","2022-01-01T18:00:00.000","2022-01-01T18:15:00.000","694","1.7848","17031081500","17031839100","8","32","7.5","3","2.36","12.86","false","1","41.8925077809","-87.6262149064","41.8809944707","-87.6327464887" +"01285080bc16b68e9fe6f74820f2864e2fd2c28f","2022-01-01T18:00:00.000","2022-01-01T18:15:00.000","563","2.4168",,,"51","44","7.5","0","3.53","11.03","false","1","41.6906333472","-87.5700582686","41.7402057565","-87.6159695226" +"018fa4a25f3cd7150d564a04228b1200dad1d628","2022-01-01T18:00:00.000","2022-01-01T18:15:00.000","344","0.6102","17031081100","17031081300","8","8","5","0","2.64","7.640000000000001","false","1","41.9002212967","-87.6291051864","41.8983317935","-87.6207628651" +"01baa766fa6d20086d5d42a69b0e7300451365c1","2022-01-01T18:00:00.000","2022-01-01T18:00:00.000","397","1.7399",,,"56","56","7.5","1","2.36","10.86","false","1","41.7925923603","-87.7696154528","41.7925923603","-87.7696154528" +"02012016e50a0ed35731d50a05a511ae3733d451","2022-01-01T18:00:00.000","2022-01-01T19:00:00.000","3465","12.6884",,,"44","44","35","0","6.4","41.4","false","1","41.7402057565","-87.6159695226","41.7402057565","-87.6159695226" +"022d55abee0411e8c0ed453df3fa0cdc3de0d8e8","2022-01-01T18:00:00.000","2022-01-01T18:30:00.000","2015","10.9748",,,,"44","20","0","6.78","26.78","false","1",,,"41.7402057565","-87.6159695226" +"02745338abf6fcbd1b39b025d99da03225c17b5e","2022-01-01T18:00:00.000","2022-01-01T18:30:00.000","2007","15.7991",,,"16",,"22.5","0","6.76","29.259999999999998","false","1","41.9535821253","-87.7234523905",, +"0304d0d7a99da8dd57da55e8de3017b63c3c7546","2022-01-01T18:00:00.000","2022-01-01T18:30:00.000","1560","7.8471",,,,"30","15","0","5.59","20.59","false","1",,,"41.8390869059","-87.714003807" +"031811971502e6aeab4d48b48f8281ff21be18d8","2022-01-01T18:00:00.000","2022-01-01T18:00:00.000","431","2.15",,,"40","42","25","0","1.02","26.02","false","1","41.7923572233","-87.6179313803","41.7788768603","-87.5949254391" +"037a6fd7b584f273ad3f508b7c71789a32979330","2022-01-01T18:00:00.000","2022-01-01T18:30:00.000","1309","4.8736","17031061000","17031161300","6","16","12.5","1","2.96","16.46","false","1","41.9492209135","-87.6519703953","41.9426995777","-87.7310024842" +"037ec46c45215e49ad1e427fd16a5a2b18522acf","2022-01-01T18:00:00.000","2022-01-01T18:00:00.000","415","1.3098","17031833000","17031320100","28","32","12.5","5","2.87","20.37","false","1","41.8852813201","-87.6572331997","41.8849871918","-87.6209929134" +"0390646476feeb847c3d3e854032c26a72323c49","2022-01-01T18:00:00.000","2022-01-01T18:15:00.000","363","1.23","17031839000","17031839100","32","32","22.5","0","1.02","23.52","false","1","41.8710158803","-87.6314065252","41.8809944707","-87.6327464887" +"039e14b9db7220284b35dfec89c318bc003976c4","2022-01-01T18:00:00.000","2022-01-01T18:15:00.000","865","4.37","17031071400","17031320100","7","32","22.5","5","1.02","28.52","false","1","41.922082541","-87.6341560931","41.8849871918","-87.6209929134" +"03ab81bb67bf7d060048db2e274e2e14e8ac70f5","2022-01-01T18:00:00.000","2022-01-01T18:30:00.000","1582","8.4358","17031661000","17031837400","66","27","17.5","0","3.86","21.36","false","1","41.7611057444","-87.6855896618","41.8759663","-87.6937939017" +"03f0f340a70e8bd7720f2cca2317448f95c5e490","2022-01-01T18:00:00.000","2022-01-01T18:00:00.000","781","7.1879",,,"77","8","15","3","3.75","21.75","false","1","41.9867117999","-87.6634164054","41.899602111","-87.6333080367" +"043c3f428b468026f9c86831151b81b6643f2868","2022-01-01T18:00:00.000","2022-01-01T18:00:00.000","229","0.95",,,"75","74","15","3","1.02","19.02","false","1","41.6897299145","-87.6690544032","41.6948789661","-87.7131924966" +"044f7f42a1912df78cab7865bf14463237bfda7c","2022-01-01T18:00:00.000","2022-01-01T18:00:00.000","676","2.3927",,,"7","6","7.5","0","2.44","9.94","false","1","41.9226862843","-87.6494887289","41.9442266014","-87.6559981815" +"045cf93dacee4230f1c847fe6a7d3d478cc759e3","2022-01-01T18:00:00.000","2022-01-01T18:15:00.000","349","0.85","17031061500","17031061000","6","6","20","4","1.02","25.02","false","1","41.9452823311","-87.6615450961","41.9492209135","-87.6519703953" +"04a945780caaa46e60995c187c19feefb87a79a7","2022-01-01T18:00:00.000","2022-01-01T18:00:00.000","331","0.9919","17031081403","17031081700","8","8","5","3","2.36","10.36","false","1","41.8909220259","-87.6188683546","41.8920421365","-87.6318639497" +"04ad18e253f3fbd3d021f45f0cbd429ec8d35473","2022-01-01T18:00:00.000","2022-01-01T18:15:00.000","476","1.06","17031841900","17031330100","28","33","15","0","1.02","16.02","false","1","41.8679024175","-87.6429586652","41.859349715","-87.6173580061" +"001e83aa74a5c14d9393540946890e3e979249dc","2022-01-01T20:00:00.000","2022-01-01T20:15:00.000","473","2.93",,,"19",,"22.5","0","1.02","23.52","false","1","41.9272609555","-87.7655016086",, +"0020be3d3d7a29ed9dbb5ef633818337d366cb1f","2022-01-01T20:00:00.000","2022-01-01T20:30:00.000","1531","5.77","17031081403","17031330100","8","33","30","5","6.02","41.019999999999996","false","1","41.8909220259","-87.6188683546","41.859349715","-87.6173580061" +"0099fd71f255ff21870809bedbc80e1eee417674","2022-01-01T20:00:00.000","2022-01-01T20:30:00.000","1850","19.5607","17031839100","17031980000","32","76","55","0","11.61","66.61","false","1","41.8809944707","-87.6327464887","41.9790708201","-87.9030396611" +"00c187e8b803b194bf481a56748de9ccb098a454","2022-01-01T20:00:00.000","2022-01-01T20:30:00.000","1099","7.44",,,"6","12","15","5","1.02","21.02","false","1","41.9442266014","-87.6559981815","41.9939301285","-87.7583535876" +"00def3acaf80749f72efb882c603703a756f1806","2022-01-01T20:00:00.000","2022-01-01T20:15:00.000","869","3.61","17031240300","17031060400","24","6","17.5","0","1.02","18.52","false","1","41.9123643542","-87.6750627566","41.9506733576","-87.6665362813" +"00e8a079723ffc3cbde765332706fc50561f783a","2022-01-01T20:00:00.000","2022-01-01T20:15:00.000","1009","6.314",,,"28","5","37.5","10","3.27","50.77","false","1","41.874005383","-87.6635175498","41.9477915865","-87.6838349425" +"0114d32b9717e2a2beb1531c5b83b7b0be0f536e","2022-01-01T20:00:00.000","2022-01-01T20:00:00.000","372","1.41",,,"41","41","15","0","1.02","16.02","false","1","41.794090253","-87.592310855","41.794090253","-87.592310855" +"0115ee1f99f73fbb42609de51eb62d91d05a73ba","2022-01-01T20:00:00.000","2022-01-01T20:00:00.000","513","3.1194","17031980000","17031770700","76",,"7.5","0","7.6","15.1","false","1","41.9790708201","-87.9030396611","41.9827750091","-87.8773053996" +"0116230a3ed9aa2f6824f4f37829ea8d4e7e57c1","2022-01-01T20:00:00.000","2022-01-01T20:15:00.000","984","6.0886","17031832000","17031280100","6","28","30","0","3.47","33.47","false","1","41.9462945357","-87.6542980837","41.8853000224","-87.6428084655" +"012894d5b531a06ba509a142e57ad5f992fe33af","2022-01-01T20:00:00.000","2022-01-01T20:00:00.000","581","1.9","17031080100","17031081800","8","8","12.5","0","1.02","13.52","false","1","41.9075200747","-87.6266589003","41.8932163595","-87.6378442095" +"01780e0d9e21ef62c94c44355cf18058c69d8c61","2022-01-01T20:00:00.000","2022-01-01T20:00:00.000","561","3.07","17031830900","17031160300","22","16","15","0","1.02","16.02","false","1","41.9286190509","-87.685362024","41.9572641084","-87.7308987849" +"019c5068a4f9980969ef2188c688321875973652","2022-01-01T20:00:00.000","2022-01-01T20:00:00.000","685","4.6913","17031081401","17031062800","8","6","22.5","0","2.92","25.42","false","1","41.8950334495","-87.6197106717","41.936159071","-87.6612652184" +"01e6f07d2a3de1182bc448169de10c6e24df40e5","2022-01-01T20:00:00.000","2022-01-01T20:00:00.000","368","1.0738","17031842300","17031280100","24","28","7.5","0","2.36","9.86","false","1","41.8983058696","-87.6536139825","41.8853000224","-87.6428084655" +"021192cf10cf2e7dda18adb0f9378daa1ce97ebc","2022-01-01T20:00:00.000","2022-01-01T20:15:00.000","569","3.1453",,,"6","8","17.5","3","2.6","23.1","false","1","41.9442266014","-87.6559981815","41.899602111","-87.6333080367" +"0229da905759933830133252d8dd34dd2d2c3078","2022-01-01T20:00:00.000","2022-01-01T20:15:00.000","1482","5.9858",,,"4","6","17.5","0","4.51","22.009999999999998","false","1","41.9751709433","-87.6875155152","41.9442266014","-87.6559981815" +"026e2084b42589b88336847051570caf311b961d","2022-01-01T20:00:00.000","2022-01-01T20:15:00.000","364","1.1289","17031062100","17031070300","6","7","5","0","2.36","7.359999999999999","false","1","41.9426918444","-87.6517705068","41.9290469366","-87.6513108767" +"0293bd3d0e94b30b7fb9437ae5423f7cd8cd88d2","2022-01-01T20:00:00.000","2022-01-01T20:15:00.000","1286","14.8441","17031980000","17031071600","76","7","22.5","0","10.06","32.56","false","1","41.9790708201","-87.9030396611","41.9164733164","-87.6411836567" +"02b7c72737ab5395fea08fe07e16d2cc0be6083e","2022-01-01T20:00:00.000","2022-01-01T20:15:00.000","736","3.2332","17031020100","17031130300","2","13","10","0","2.62","12.620000000000001","false","1","42.0157199072","-87.6871159899","41.9865581808","-87.7133688039" +"02b820e1ded7ac9626af56c851106317f7710bd8","2022-01-01T20:00:00.000","2022-01-01T20:00:00.000","420","1.6611","17031839100","17031081700","32","8","15","0","2.36","17.36","false","1","41.8809944707","-87.6327464887","41.8920421365","-87.6318639497" +"02c08aff2fdeb78e3f6cde77f6b82d0d1b723cf4","2022-01-01T20:00:00.000","2022-01-01T20:00:00.000","432","1.287","17031081201","17031080300","8","8","12.5","1","2.87","16.37","false","1","41.8991556134","-87.6262105324","41.9074919303","-87.6357600901" +"02e282ba7cc96e82283a4ac21eb5cc20ced050c2","2022-01-01T20:00:00.000","2022-01-01T20:15:00.000","730","3.8754",,,"43","44","12.5","0","2.75","15.25","false","1","41.7615779081","-87.5727819867","41.7402057565","-87.6159695226" +"033470095d925a8897facca543dca00c69049f4b","2022-01-01T20:00:00.000","2022-01-01T20:15:00.000","1344","6.5123",,,"42","71","17.5","2","3.31","22.81","false","1","41.7788768603","-87.5949254391","41.7442051463","-87.6563059862" +"03b50f5dd59358b9ac44196f3b5ad0f678e2a236","2022-01-01T20:00:00.000","2022-01-01T20:15:00.000","592","2.8707","17031832600","17031081800","7","8","15","0","2.54","17.54","false","1","41.9147473049","-87.6540070286","41.8932163595","-87.6378442095" +"03bc71ea67763a4237b69173148157c160229bbb","2022-01-01T20:00:00.000","2022-01-01T20:00:00.000","403","2.58","17031070101","17031081300","7","8","20","0","1.02","21.02","false","1","41.9292629902","-87.6358909539","41.8983317935","-87.6207628651" +"03cb4309dba39d19e48652fe6811e62bf8f6d5ed","2022-01-01T20:00:00.000","2022-01-01T20:00:00.000","251","0.5334","17031081700","17031081500","8","8","15","0","2.4","17.4","false","1","41.8920421365","-87.6318639497","41.8925077809","-87.6262149064" +"00075c29393b6cc6ad23ff4ea55b273c357d6dfd","2022-01-01T22:00:00.000","2022-01-01T22:30:00.000","1624","12.3661","17031980000","17031812301","76",,"60","0","10.11","70.11","false","1","41.9790708201","-87.9030396611",, +"001b4fa745431e7f3d3ba6b3587103d405e491f0","2022-01-01T22:00:00.000","2022-01-01T22:00:00.000","406","0.97","17031081800","17031833000","8","28","17.5","4","0","21.5","false","1","41.8932163595","-87.6378442095","41.8852813201","-87.6572331997" +"004aa7200b06e0f3c8c9e6e32b77ba33b0bb4016","2022-01-01T22:00:00.000","2022-01-01T22:00:00.000","571","2.099","17031071200","17031061000","7","6","12.5","0","2.38","14.879999999999999","false","1","41.9218549112","-87.6462109769","41.9492209135","-87.6519703953" +"00e1d43b93f8818b17cb786dbc39a36b482eb58b","2022-01-01T22:00:00.000","2022-01-01T22:45:00.000","2314","24.4","17031980000",,"76",,"82.5","0","13.01","95.51","false","1","41.9790708201","-87.9030396611",, +"012cbd33f238b499d7437752e42e61800a3a2b21","2022-01-01T22:00:00.000","2022-01-01T22:00:00.000","489","2.35",,,"6","5","15","4","1.02","20.02","false","1","41.9442266014","-87.6559981815","41.9477915865","-87.6838349425" +"01468eaa263319c41f1b9c530f61a28ffe4adb6a","2022-01-01T22:00:00.000","2022-01-01T22:15:00.000","564","2.3195","17031832300","17031080300","22","8","22.5","0","2.43","24.93","false","1","41.9192250505","-87.671445766","41.9074919303","-87.6357600901" +"016cbc5d1da0677d3c46072304aee27c04327280","2022-01-01T22:00:00.000","2022-01-01T22:15:00.000","659","3.86","17031071100","17031221300","7","22","15","0","1.02","16.02","false","1","41.9217781876","-87.6510618838","41.9211259143","-87.6997544065" +"018343c87cfb5e3a14e6cff57c383067b0bb7a85","2022-01-01T22:00:00.000","2022-01-01T22:00:00.000","436","1.69",,,"27","29","15","0","1.02","16.02","false","1","41.8789144956","-87.7058971305","41.8601900192","-87.7172201" +"01b778672597511de2831c054801ab5d0debf6d0","2022-01-01T22:00:00.000","2022-01-01T22:15:00.000","318","0.82",,,"77","1","15","0","1.02","16.02","false","1","41.9867117999","-87.6634164054","42.0096228806","-87.6701668569" +"01c6131206696e9931b7883cc930a9698f2332df","2022-01-01T22:00:00.000","2022-01-01T22:00:00.000","574","2.5862","17031081201","17031281900","8","28","12.5","0","2.48","14.98","false","1","41.8991556134","-87.6262105324","41.8792550844","-87.642648998" +"02735fabb5117c23aaf11b8c4e049e6c0d08f612","2022-01-01T22:00:00.000","2022-01-01T22:30:00.000","2269","19.4247",,,"3","66","27.5","3","17.85","48.35","false","1","41.96581197","-87.6558787862","41.7718485152","-87.695666342" +"02925cd137c2149d5fa69c480a9db918283a0296","2022-01-01T22:00:00.000","2022-01-01T22:15:00.000","1213","5.1156",,,"20","6","15","0","3.31","18.31","false","1","41.9243470769","-87.7347397536","41.9442266014","-87.6559981815" +"029a95c44e07fedc1681312017d09fb7334474d5","2022-01-01T22:00:00.000","2022-01-01T22:15:00.000","1085","4.84","17031320600","17031842200","32","8","30","0","1.02","31.02","false","1","41.8706073724","-87.6221729369","41.9049353016","-87.6499072264" +"02c4eebc2542d66b4cd50af3bd3bd169f8920e0e","2022-01-01T22:00:00.000","2022-01-01T22:15:00.000","759","3.417","17031320100","17031242100","32","24","22.5","0","2.66","25.16","false","1","41.8849871918","-87.6209929134","41.8996701799","-87.6698377982" +"035ce757f9a8d2fdeb6567660c64734210d3adcb","2022-01-01T22:00:00.000","2022-01-01T22:15:00.000","1101","7.7",,,"6",,"17.5","0","4.01","21.509999999999998","false","1","41.9442266014","-87.6559981815",, +"0399bf5e8d8f6d9684a6c159a7bfbcda63e296b1","2022-01-01T22:00:00.000","2022-01-01T22:15:00.000","650","1.9068","17031842300","17031320600","24","32","15","0","2.36","17.36","false","1","41.8983058696","-87.6536139825","41.8706073724","-87.6221729369" +"03fdc9c63104db1a39e3611f25bf2747cd69d906","2022-01-01T22:00:00.000","2022-01-01T22:15:00.000","758","4.8965","17031839100","17031837100","32","27","20","0","3.26","23.259999999999998","false","1","41.8809944707","-87.6327464887","41.885621155","-87.6988915914" +"040ef80924e8ae8f4ec01cb42356761d79b84740","2022-01-01T22:00:00.000","2022-01-01T22:30:00.000","1837","6.8655","17031830800","17031833100","4","28","17.5","0","3.38","20.88","false","1","41.9651417087","-87.6765780714","41.8790669938","-87.657005027" +"04575f024ae4f3ed0e1d643eeabc7995d5b9e3de","2022-01-01T22:00:00.000","2022-01-01T22:15:00.000","1081","4.3397",,,"14","15","12.5","0","2.85","15.35","false","1","41.968069","-87.7215590627","41.9540276487","-87.7633990316" +"04b3359a36305892677ebcef1dd74ce17d450542","2022-01-01T22:00:00.000","2022-01-01T22:15:00.000","1324","7.216",,,"43","53","17.5","0","3.9","21.4","false","1","41.7615779081","-87.5727819867","41.6738199043","-87.6357397768" +"04b63c20f6767a5bb48dc5866bb6eab4101a994f","2022-01-01T22:00:00.000","2022-01-01T22:15:00.000","666","2.0049","17031833000","17031838100","28","28","20","0","2.87","22.87","false","1","41.8852813201","-87.6572331997","41.8786674201","-87.6716536214" +"04ef106636128a01a3a93f69e9d07f641dc5f9ff","2022-01-01T22:00:00.000","2022-01-01T22:15:00.000","767","4.6889",,,"23","25","32.5","0","2.92","35.42","false","1","41.9000696026","-87.7209182385","41.8906088526","-87.7560467111" +"052fcd028ddc59718129f8b15f91c9e2c8822f60","2022-01-01T22:00:00.000","2022-01-01T22:45:00.000","2477","27.19",,"17031062800",,"6","85","0","1.89","86.89","false","1",,,"41.936159071","-87.6612652184" +"055ec360ebdc21b07059540eb086ff366da61126","2022-01-01T22:00:00.000","2022-01-01T22:00:00.000","462","2.1231","17031080300","17031070200","8","7","15","0","2.39","17.39","false","1","41.9074919303","-87.6357600901","41.9290776551","-87.6462934762" +"05666dba3029500646f0967fd51b7dc24a20d6ba","2022-01-01T22:00:00.000","2022-01-01T22:00:00.000","719","3.44","17031081403","17031241600","8","24","25","0","3.25","28.25","false","1","41.8909220259","-87.6188683546","41.9066507664","-87.6653376596" diff --git a/CasualLab/fixtures/manifest.json b/CasualLab/fixtures/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..149a3bbaa50a9979b7c332c3cadded64f94090bb --- /dev/null +++ b/CasualLab/fixtures/manifest.json @@ -0,0 +1,22 @@ +{ + "files": [ + { + "bytes": 70621, + "path": "chicago_tnp_2022-01-01_300.csv", + "rows": 300, + "sha256": "84177e5a72548cc4346df99f0a6b671adb50d7762e23abe041f01b2958b85ad7" + } + ], + "retrieved_at": "2026-08-07", + "selection": { + "dataset_id": "m6dm-c72p", + "hours_local": [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22], + "order_within_hour": "trip_id", + "query_predicate": "trip_start_timestamp = exact reported hourly timestamp", + "query_url_template": "https://data.cityofchicago.org/resource/m6dm-c72p.csv?$where=trip_start_timestamp%20%3D%20%272022-01-01T%7BHH%7D%3A00%3A00%27&$order=trip_id&$limit=25", + "rows_per_hour": 25, + "service_date": "2022-01-01" + }, + "source": "City of Chicago Transportation Network Providers - Trips (2018-2022)", + "source_page": "https://data.cityofchicago.org/Transportation/Transportation-Network-Providers-Trips-2018-2022-/m6dm-c72p" +} diff --git a/CasualLab/nyc_sample/clean/trips/source=nyc_hvfhv/service_year=2024/service_month=1/part-00000.parquet b/CasualLab/nyc_sample/clean/trips/source=nyc_hvfhv/service_year=2024/service_month=1/part-00000.parquet new file mode 100644 index 0000000000000000000000000000000000000000..15ec627076e87c7a2df97b079a83c1bba70af93e --- /dev/null +++ b/CasualLab/nyc_sample/clean/trips/source=nyc_hvfhv/service_year=2024/service_month=1/part-00000.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:814f91d674ba2e9a0480f4c5cd6fe4f79ff9458931fb04f3b1568184291f5e9d +size 585723 diff --git a/CasualLab/nyc_sample/diagnostics.json b/CasualLab/nyc_sample/diagnostics.json new file mode 100644 index 0000000000000000000000000000000000000000..c8d394154c7c3f7b8080e4c0d680b5490394ae9b --- /dev/null +++ b/CasualLab/nyc_sample/diagnostics.json @@ -0,0 +1,218 @@ +{ + "missingness": { + "additional_charges": { + "count": 0, + "rate": 0.0 + }, + "airport_fee": { + "count": 0, + "rate": 0.0 + }, + "airport_trip": { + "count": 0, + "rate": 0.0 + }, + "dispatching_base_id": { + "count": 0, + "rate": 0.0 + }, + "driver_pay": { + "count": 0, + "rate": 0.0 + }, + "dropoff_census_tract": { + "count": 10000, + "rate": 1.0 + }, + "dropoff_census_tract_missing_or_suppressed": { + "count": 10000, + "rate": 1.0 + }, + "dropoff_datetime": { + "count": 0, + "rate": 0.0 + }, + "dropoff_datetime_utc": { + "count": 0, + "rate": 0.0 + }, + "dropoff_zone_id": { + "count": 0, + "rate": 0.0 + }, + "dropoff_zone_missing": { + "count": 0, + "rate": 0.0 + }, + "fare": { + "count": 0, + "rate": 0.0 + }, + "fare_on_declared_grid": { + "count": 10000, + "rate": 1.0 + }, + "pickup_census_tract": { + "count": 10000, + "rate": 1.0 + }, + "pickup_census_tract_missing_or_suppressed": { + "count": 10000, + "rate": 1.0 + }, + "pickup_datetime": { + "count": 0, + "rate": 0.0 + }, + "pickup_datetime_utc": { + "count": 0, + "rate": 0.0 + }, + "pickup_on_15_minute_grid": { + "count": 0, + "rate": 0.0 + }, + "pickup_zone_id": { + "count": 0, + "rate": 0.0 + }, + "pickup_zone_missing": { + "count": 0, + "rate": 0.0 + }, + "provider_id": { + "count": 0, + "rate": 0.0 + }, + "record_id_is_surrogate": { + "count": 0, + "rate": 0.0 + }, + "reported_fare_rounding_increment": { + "count": 10000, + "rate": 1.0 + }, + "reported_timestamp_rounding_minutes": { + "count": 10000, + "rate": 1.0 + }, + "reported_tip_rounding_increment": { + "count": 10000, + "rate": 1.0 + }, + "request_datetime": { + "count": 0, + "rate": 0.0 + }, + "service_date": { + "count": 0, + "rate": 0.0 + }, + "service_day_of_week": { + "count": 0, + "rate": 0.0 + }, + "service_month": { + "count": 0, + "rate": 0.0 + }, + "service_year": { + "count": 0, + "rate": 0.0 + }, + "shared_matched": { + "count": 0, + "rate": 0.0 + }, + "shared_requested": { + "count": 0, + "rate": 0.0 + }, + "source": { + "count": 0, + "rate": 0.0 + }, + "source_dataset_id": { + "count": 0, + "rate": 0.0 + }, + "source_timezone": { + "count": 0, + "rate": 0.0 + }, + "taxes_and_surcharges": { + "count": 0, + "rate": 0.0 + }, + "tips": { + "count": 0, + "rate": 0.0 + }, + "tolls": { + "count": 0, + "rate": 0.0 + }, + "total_amount": { + "count": 0, + "rate": 0.0 + }, + "trip_id": { + "count": 0, + "rate": 0.0 + }, + "trip_miles": { + "count": 0, + "rate": 0.0 + }, + "trip_seconds": { + "count": 0, + "rate": 0.0 + }, + "trips_pooled": { + "count": 10000, + "rate": 1.0 + }, + "zone_type": { + "count": 0, + "rate": 0.0 + } + }, + "rounding": { + "declared_fare_rounding_increments": [], + "declared_timestamp_rounding_minutes": [], + "fare_on_declared_grid_rate": null, + "interpretation": "Grid conformance verifies reported-value patterns; it does not recover latent exact fares or timestamps.", + "pickup_on_15_minute_grid_rate": 0.0009 + }, + "row_count": 10000, + "schema_version": "1.0.0", + "source_caveats": { + "nyc_hvfhv": { + "census_tracts": "not published in the monthly HVFHV trip schema", + "sample_selection": "equal configured day-hour quotas are deterministic engineering coverage, not probability or population-weighted sampling", + "schema": "monthly HVFHV Parquet; cbd_congestion_fee is optional pre-2025" + } + }, + "sources": [ + "nyc_hvfhv" + ], + "suppression_or_nonreporting": { + "dropoff_census_tract_count": 0, + "dropoff_census_tract_rate": null, + "dropoff_indicator_known_count": 0, + "dropoff_indicator_status": "unavailable", + "interpretation": "Null availability indicators mean the source does not report the field; they must not be recoded as unsuppressed. Chicago blank census tracts may be privacy-suppressed or outside Chicago, and no record-level mechanism is claimed.", + "pickup_census_tract_count": 0, + "pickup_census_tract_rate": null, + "pickup_indicator_known_count": 0, + "pickup_indicator_status": "unavailable" + }, + "validity": { + "duplicate_trip_id_count": 0, + "missing_trip_id_count": 0, + "negative_fare_count": 1, + "negative_trip_miles_count": 0, + "nonpositive_trip_seconds_count": 0, + "utc_conversion_null_count": 0 + } +} diff --git a/CasualLab/nyc_sample/manifest.json b/CasualLab/nyc_sample/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..3f7a54fd63bd9b9b2de1d1cc837bde4c0edaac38 --- /dev/null +++ b/CasualLab/nyc_sample/manifest.json @@ -0,0 +1,150 @@ +{ + "config": { + "chicago_dataset_id": "m6dm-c72p", + "clean_dir": "data/nyc_sample/clean", + "complete_panel_grid": false, + "diagnostics_path": "data/nyc_sample/diagnostics.json", + "end_datetime": null, + "fixture_path": null, + "manifest_path": "data/nyc_sample/manifest.json", + "max_pages": null, + "mode": "sample", + "nyc_months": [ + 1 + ], + "nyc_sample_days": [ + 1, + 10, + 19, + 28 + ], + "nyc_sample_hours": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23 + ], + "nyc_year": 2024, + "page_size": 50000, + "panel_dir": "data/nyc_sample/panel", + "panel_frequency": "1h", + "partition_by": [ + "source", + "service_year", + "service_month" + ], + "project_root": ".", + "raw_dir": "data/nyc_sample/raw", + "sample_rows": 10000, + "source": "nyc_hvfhv", + "start_datetime": null, + "timeout_seconds": 300 + }, + "files": [ + { + "bytes": 585723, + "path": "data/nyc_sample/clean/trips/source=nyc_hvfhv/service_year=2024/service_month=1/part-00000.parquet", + "sha256": "814f91d674ba2e9a0480f4c5cd6fe4f79ff9458931fb04f3b1568184291f5e9d" + }, + { + "bytes": 4750, + "path": "data/nyc_sample/diagnostics.json", + "sha256": "829d5fd7a57ad69ee99821d8f7330d46cfc82e6e8ae79cc08869a4fdc3baeba9" + }, + { + "bytes": 79641, + "path": "data/nyc_sample/panel/od_flow/source=nyc_hvfhv/year=2024/month=1/part-00000.parquet", + "sha256": "94640b5734d26dc3e53c78b1263daccfe9c5ec39cbdaf8d9c45b73e1a16dc21c" + }, + { + "bytes": 158627, + "path": "data/nyc_sample/panel/zone_time/source=nyc_hvfhv/year=2024/month=1/part-00000.parquet", + "sha256": "d22dd86463d95966ed33ee8ac8505f751bf5598131fd65566924b2d00b2fa9cc" + }, + { + "bytes": 325339, + "path": "data/nyc_sample/raw/fhvhv_tripdata_2024-01_stratified_10000_ca1e55852837.parquet", + "sha256": "b8aeeb5c99ab94306251a22419a894769d1e8801a1080862a47105c19800dfae" + } + ], + "generated_at_utc": "2026-08-08T21:58:36.921324+00:00", + "metadata": { + "causal_claim": false, + "evidence_label": "descriptive_real_data", + "od_flow_rows": 9852, + "sample_selection": { + "days": [ + 1, + 10, + 19, + 28 + ], + "hours": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23 + ], + "population_weighted": false, + "probability_sample": false, + "requested_rows": 10000, + "strategy": "equal_quota_per_configured_day_hour_stable_hash_v1" + }, + "trip_rows": 10000, + "zone_time_rows": 7112 + }, + "schema_version": "1.0.0", + "source_metadata": { + "dataset_page": "https://www.nyc.gov/site/tlc/about/tlc-trip-record-data.page", + "known_measurement": { + "census_tracts": "not published in the monthly HVFHV trip schema", + "sample_selection": "equal configured day-hour quotas are deterministic engineering coverage, not probability or population-weighted sampling", + "schema": "monthly HVFHV Parquet; cbd_congestion_fee is optional pre-2025" + }, + "publisher": "New York City Taxi and Limousine Commission", + "timezone": "America/New_York" + }, + "source_urls": [ + "https://d37ci6vzurychx.cloudfront.net/trip-data/fhvhv_tripdata_2024-01.parquet" + ] +} diff --git a/CasualLab/nyc_sample/panel/od_flow/source=nyc_hvfhv/year=2024/month=1/part-00000.parquet b/CasualLab/nyc_sample/panel/od_flow/source=nyc_hvfhv/year=2024/month=1/part-00000.parquet new file mode 100644 index 0000000000000000000000000000000000000000..0f0cfe282ca181716cdebba7d4fc598a90765158 --- /dev/null +++ b/CasualLab/nyc_sample/panel/od_flow/source=nyc_hvfhv/year=2024/month=1/part-00000.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:94640b5734d26dc3e53c78b1263daccfe9c5ec39cbdaf8d9c45b73e1a16dc21c +size 79641 diff --git a/CasualLab/nyc_sample/panel/zone_time/source=nyc_hvfhv/year=2024/month=1/part-00000.parquet b/CasualLab/nyc_sample/panel/zone_time/source=nyc_hvfhv/year=2024/month=1/part-00000.parquet new file mode 100644 index 0000000000000000000000000000000000000000..b8e29e32e8c18b33aacdac1acde2e1b674363422 --- /dev/null +++ b/CasualLab/nyc_sample/panel/zone_time/source=nyc_hvfhv/year=2024/month=1/part-00000.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d22dd86463d95966ed33ee8ac8505f751bf5598131fd65566924b2d00b2fa9cc +size 158627 diff --git a/CasualLab/project.yaml b/CasualLab/project.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8459bcef23e80f0ff8b5e78968177332822e7bec --- /dev/null +++ b/CasualLab/project.yaml @@ -0,0 +1,43 @@ +title: CasualLab +slug: casuallab +summary: Experimental causal inference and policy simulation toolkit with NYC-oriented public examples. +research_question: How do causal mechanisms and heterogeneous treatment effects shape market outcomes and policy interventions in field-like datasets? +why_it_matters: Credible policy evaluation requires both transparent identification assumptions and reproducible decision rules. +research_fields: + - Causal inference + - Experimental economics + - Market design +project_type: research-replication +status: public-live +authors: + - Repository owner and maintainer +original_source: CasualLab workspace project +original_sample_period: Not applicable; the public package uses synthetic and open examples. +updated_sample_period: Updated when a documented public-data refresh is released. +data_sources: + - Public synthetic or open policy data configured per run + - Repository fixtures and NYC sample data +data_license: RIGHTS_UNKNOWN for raw third-party sources; included fixtures are publishable examples. +code_license: MIT; third-party components retain their own licenses. +reproduction_command: make reproduce +expected_runtime: Varies by module and selected estimator. +outputs: + - src/ + - reports/ + - scripts/ + - tests/ + - data/fixtures/ +github_url: https://github.com/YangXiaoShawn/open-economic-quant-casuallab +site_url: https://yangxiaoshawn.github.io/projects/casuallab/ +dataset_url: https://huggingface.co/datasets/ShawnChamberlain/open-economic-quant-research-data/tree/main/CasualLab +space_url: https://huggingface.co/spaces/ShawnChamberlain/open-economic-quant-research-observatory +last_updated: 2026-08-10 +limitations: Numerical result comparisons are reported only when a source, sample, and validation record are available. Publication rights for new raw sources must be reviewed before release. +catalog: + field: causal + accent: teal + tags: + - Causal Inference + - Policy Simulation + - Heterogeneity + metric: Reproducible fixtures diff --git a/CasualLab/pyproject.toml b/CasualLab/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..65603011666d0398c4c08894f951a0e5232fba7a --- /dev/null +++ b/CasualLab/pyproject.toml @@ -0,0 +1,61 @@ +[build-system] +requires = ["hatchling>=1.25"] +build-backend = "hatchling.build" + +[project] +name = "causal-marketplace-lab" +version = "0.1.0" +description = "Reproducible marketplace experiment design, interference simulation, and policy learning." +readme = "README.md" +requires-python = ">=3.11" +license = {text = "MIT"} +authors = [{name = "Causal Marketplace Lab"}] +dependencies = [ + "duckdb>=1.1", + "numpy>=1.26", + "pandas>=2.1", + "polars>=1.0", + "pyarrow>=15", + "pyshp>=2.3", + "PyYAML>=6.0", + "pyproj>=3.6", + "scikit-learn>=1.4", + "scipy>=1.11", + "shapely>=2.0", + "statsmodels>=0.14", + # Shared monorepo package, pinned by commit so this project installs standalone; + # inside the monorepo, uv uses the workspace copy (root tool.uv.sources). + "oeq-core @ git+https://github.com/YangXiaoShawn/open-economic-quant@3d309b7e90ca7b970bb5396d3bb781c92de4ea7e#subdirectory=packages/oeq-core", +] + +[project.optional-dependencies] +dashboard = [ + "altair>=5.3", + "streamlit>=1.36", +] +dev = [ + "pytest>=8.0", + "pytest-cov>=5.0", + "ruff>=0.6", +] + +[project.scripts] +casuallab = "casuallab.cli:main" + +[tool.hatch.metadata] +allow-direct-references = true + +[tool.hatch.build.targets.wheel] +packages = ["src/casuallab"] + +[tool.pytest.ini_options] +addopts = "-q" +testpaths = ["tests"] + +[tool.ruff] +line-length = 100 +target-version = "py311" + +[tool.ruff.lint] +select = ["E", "F", "I", "UP", "B"] +ignore = ["E501"] diff --git a/CasualLab/src/casuallab/__init__.py b/CasualLab/src/casuallab/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2aeff56d0c0142ff833c6386ba7a8b1a52257daa --- /dev/null +++ b/CasualLab/src/casuallab/__init__.py @@ -0,0 +1,4 @@ +"""Causal Marketplace Lab public API.""" + +__version__ = "0.1.0" + diff --git a/CasualLab/src/casuallab/__main__.py b/CasualLab/src/casuallab/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..729e54c37bf6c27ff9dd01faf0499b575c7ef9c7 --- /dev/null +++ b/CasualLab/src/casuallab/__main__.py @@ -0,0 +1,6 @@ +"""Module entry point for ``python -m casuallab``.""" + +from casuallab.cli import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/CasualLab/src/casuallab/analysis.py b/CasualLab/src/casuallab/analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..20794bd09be6b6ad8e4328584100be38512d39db --- /dev/null +++ b/CasualLab/src/casuallab/analysis.py @@ -0,0 +1,287 @@ +"""Descriptive marketplace analysis with explicit non-causal evidence labels.""" + +from __future__ import annotations + +import json +import re +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd + + +def _to_pandas(frame: Any) -> pd.DataFrame: + if isinstance(frame, pd.DataFrame): + return frame.copy() + if hasattr(frame, "to_pandas"): + return frame.to_pandas() + raise TypeError("expected a pandas or Polars DataFrame") + + +def _first_column(frame: pd.DataFrame, candidates: tuple[str, ...], *, required: bool = True) -> str | None: + for candidate in candidates: + if candidate in frame.columns: + return candidate + if required: + raise ValueError(f"none of the required columns are present: {list(candidates)}") + return None + + +def _weighted_mean(values: pd.Series, weights: pd.Series) -> float: + numeric_values = pd.to_numeric(values, errors="coerce") + numeric_weights = pd.to_numeric(weights, errors="coerce") + valid = numeric_values.notna() & numeric_weights.notna() & (numeric_weights > 0) + if not valid.any(): + return float("nan") + return float(np.average(numeric_values.loc[valid], weights=numeric_weights.loc[valid])) + + +def compute_descriptive_moments(panel: Any) -> dict[str, object]: + """Compute transparent empirical moments from a compact zone-time panel. + + Returned correlations are labeled associations. No transformation in this + function provides exogenous price variation or a causal identification strategy. + """ + + frame = _to_pandas(panel) + if frame.empty: + raise ValueError("panel must not be empty") + zone = _first_column(frame, ("zone_id", "pickup_zone", "pickup_community_area", "zone")) + period = _first_column( + frame, + ("period_start", "time_bin", "time_period", "hour", "trip_start_hour"), + ) + demand = _first_column(frame, ("trip_count", "completed_trips", "demand", "outcome")) + fare = _first_column(frame, ("average_fare", "avg_fare", "mean_fare", "fare"), required=False) + pooled = _first_column( + frame, + ( + "pooled_trip_share", + "pooled_share", + "shared_trip_share", + "shared_matched_share", + "shared_requested_share", + ), + required=False, + ) + + demand_values = pd.to_numeric(frame[demand], errors="coerce") + if demand_values.notna().sum() == 0: + raise ValueError("demand column contains no numeric observations") + + moments: dict[str, object] = { + "evidence_type": "empirical_association", + "panel_rows": int(len(frame)), + "zones": int(frame[zone].nunique(dropna=True)), + "periods": int(frame[period].nunique(dropna=True)), + "total_observed_trips": float(demand_values.sum()), + "mean_trips_per_cell": float(demand_values.mean()), + "p90_trips_per_cell": float(demand_values.quantile(0.90)), + "price_endogeneity_warning": ( + "Observed fare and demand are jointly determined by marketplace state. " + "Their correlation is descriptive and is not a causal elasticity." + ), + } + if fare is not None: + fare_values = pd.to_numeric(frame[fare], errors="coerce") + moments["mean_observed_fare"] = _weighted_mean(fare_values, demand_values) + moments["equal_observed_cell_mean_fare"] = float(fare_values.mean()) + moments["fare_demand_correlation_association"] = float(fare_values.corr(demand_values)) + if pooled is not None: + moments["mean_pooled_trip_share"] = _weighted_mean( + frame[pooled], demand_values + ) + + ordered = frame.assign(_demand=demand_values).sort_values([zone, period]) + previous_observed = ordered.groupby(zone, dropna=False)["_demand"].shift(1) + moments["zone_previous_observed_cell_demand_correlation_association"] = float( + ordered["_demand"].corr(previous_observed) + ) + + period_values = pd.to_datetime(ordered[period], errors="coerce") + if period_values.notna().all(): + lag_minutes: int | None = None + if "panel_grain" in ordered and ordered["panel_grain"].notna().any(): + match = re.search(r"_(\d+)([mh])$", str(ordered["panel_grain"].dropna().iloc[0])) + if match: + magnitude = int(match.group(1)) + lag_minutes = magnitude if match.group(2) == "m" else 60 * magnitude + if lag_minutes is not None: + exact = ordered[[zone, period, "_demand"]].copy() + exact[period] = period_values + prior = exact.rename(columns={"_demand": "_prior_demand"}) + prior[period] = prior[period] + pd.Timedelta(minutes=lag_minutes) + pairs = exact.merge(prior, on=[zone, period], how="inner") + correlation = float(pairs["_demand"].corr(pairs["_prior_demand"])) + moments["zone_exact_lag_demand_correlation_association"] = ( + correlation if np.isfinite(correlation) else None + ) + moments["zone_exact_lag_support_pairs"] = int(len(pairs)) + moments["zone_exact_lag_minutes"] = lag_minutes + + income_column = _first_column( + frame, + ( + "neighborhood_income_index", + "neighborhood__income_index", + "neighborhood__neighborhood_income_index", + ), + required=False, + ) + if income_column is not None: + income = pd.to_numeric(frame[income_column], errors="coerce") + median_income = float(income.median()) + high = demand_values.loc[income >= median_income].mean() + low = demand_values.loc[income < median_income].mean() + moments["high_minus_low_income_mean_demand_association"] = float(high - low) + moments["neighborhood_income_known_rows"] = int(income.notna().sum()) + weather_column = _first_column( + frame, + ("adverse_weather", "weather__adverse_weather", "weather__precipitation"), + required=False, + ) + if weather_column is not None: + weather_values = pd.to_numeric(frame[weather_column], errors="coerce") + known_weather = weather_values.notna() + weather = weather_values > 0 + contrast = demand_values.loc[known_weather & weather].mean() - demand_values.loc[ + known_weather & ~weather + ].mean() + moments["adverse_weather_minus_other_mean_demand_association"] = ( + float(contrast) if np.isfinite(contrast) else None + ) + moments["weather_known_rows"] = int(known_weather.sum()) + event_column = _first_column( + frame, + ("event_intensity", "events__event_intensity"), + required=False, + ) + if event_column is not None: + event_values = pd.to_numeric(frame[event_column], errors="coerce") + known_event = event_values.notna() + events = event_values > 0 + contrast = demand_values.loc[known_event & events].mean() - demand_values.loc[ + known_event & ~events + ].mean() + moments["event_minus_nonevent_mean_demand_association"] = ( + float(contrast) if np.isfinite(contrast) else None + ) + moments["event_known_rows"] = int(known_event.sum()) + return moments + + +def descriptive_tables(panel: Any) -> dict[str, pd.DataFrame]: + """Return demand-by-time, demand-by-zone, and cross-zone co-movement tables.""" + + frame = _to_pandas(panel) + if frame.empty: + raise ValueError("panel must not be empty") + zone = _first_column(frame, ("zone_id", "pickup_zone", "pickup_community_area", "zone")) + period = _first_column( + frame, + ("period_start", "time_bin", "time_period", "hour", "trip_start_hour"), + ) + demand = _first_column(frame, ("trip_count", "completed_trips", "demand", "outcome")) + frame[demand] = pd.to_numeric(frame[demand], errors="coerce") + + period_values = pd.to_datetime(frame[period], errors="coerce") + if period_values.notna().any(): + frame["hour_of_day"] = period_values.dt.hour + else: + frame["hour_of_day"] = pd.to_numeric(frame[period], errors="coerce") + + by_hour = ( + frame.groupby("hour_of_day", dropna=False)[demand] + .agg(mean_trip_count="mean", total_trip_count="sum", cells="size") + .reset_index() + ) + by_zone = ( + frame.groupby(zone, dropna=False)[demand] + .agg(mean_trip_count="mean", total_trip_count="sum", periods_observed="size") + .reset_index() + .rename(columns={zone: "zone_id"}) + ) + wide = frame.pivot_table(index=period, columns=zone, values=demand, aggfunc="sum") + correlation = wide.corr(min_periods=2) + correlation.index.name = "origin_zone" + correlation.columns.name = "comparison_zone" + cross_zone = correlation.stack().rename("demand_correlation").reset_index() + for table in (by_hour, by_zone, cross_zone): + table["evidence_type"] = "empirical_association" + return {"demand_by_hour": by_hour, "demand_by_zone": by_zone, "cross_zone": cross_zone} + + +def origin_destination_summary(trips: Any) -> pd.DataFrame: + """Summarize observed flows without interpreting them as substitution effects.""" + + frame = _to_pandas(trips) + origin = _first_column( + frame, + ( + "pickup_zone", + "pickup_zone_id", + "pickup_community_area", + "pickup_location_id", + "origin_zone", + ), + ) + destination = _first_column( + frame, + ( + "dropoff_zone", + "dropoff_zone_id", + "dropoff_community_area", + "dropoff_location_id", + "destination_zone", + ), + ) + flows = ( + frame.groupby([origin, destination], dropna=False) + .size() + .rename("trip_count") + .reset_index() + .rename(columns={origin: "origin_zone", destination: "destination_zone"}) + ) + origin_totals = flows.groupby("origin_zone", dropna=False)["trip_count"].transform("sum") + flows["origin_flow_share"] = flows["trip_count"] / origin_totals + flows["evidence_type"] = "empirical_association" + flows["interpretation_warning"] = ( + "Observed flows reveal connected markets but do not identify causal spatial substitution." + ) + return flows.sort_values(["origin_zone", "trip_count"], ascending=[True, False]).reset_index( + drop=True + ) + + +def write_descriptive_artifacts( + panel: Any, + output_directory: str | Path, + *, + trips: Any | None = None, +) -> dict[str, Path]: + """Write deterministic JSON/CSV descriptive artifacts.""" + + directory = Path(output_directory) + directory.mkdir(parents=True, exist_ok=True) + moments = compute_descriptive_moments(panel) + + # JSON has no portable NaN representation; unresolved compact-sample moments are + # retained as null rather than converted to a made-up number. + clean_moments = { + key: (None if isinstance(value, float) and not np.isfinite(value) else value) + for key, value in moments.items() + } + moments_path = directory / "descriptive_moments.json" + moments_path.write_text(json.dumps(clean_moments, indent=2, sort_keys=True) + "\n", encoding="utf-8") + + paths = {"moments": moments_path} + for name, table in descriptive_tables(panel).items(): + path = directory / f"{name}.csv" + table.to_csv(path, index=False) + paths[name] = path + if trips is not None: + flow_path = directory / "origin_destination_flows.csv" + origin_destination_summary(trips).to_csv(flow_path, index=False) + paths["origin_destination_flows"] = flow_path + return paths diff --git a/CasualLab/src/casuallab/benchmark.py b/CasualLab/src/casuallab/benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..9b430f411d0ffc275b8804d4a7d1769a27ae6f8d --- /dev/null +++ b/CasualLab/src/casuallab/benchmark.py @@ -0,0 +1,291 @@ +"""Monte Carlo metrics for design and estimator comparisons.""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path +from statistics import NormalDist + +import numpy as np +import pandas as pd +import yaml + + +def _jeffreys_binomial_sd(successes: int, trials: int) -> float: + """Return Jeffreys-posterior uncertainty for a simulated binomial rate.""" + + posterior_success = successes + 0.5 + posterior_failure = trials - successes + 0.5 + posterior_total = posterior_success + posterior_failure + return float( + np.sqrt( + posterior_success + * posterior_failure + / (posterior_total**2 * (posterior_total + 1.0)) + ) + ) + + +@dataclass(frozen=True) +class BenchmarkConfig: + """Laptop-safe Monte Carlo configuration.""" + + replications: int = 100 + seed: int = 1729 + confidence_level: float = 0.95 + designs: tuple[str, ...] = ("individual", "geo_cluster", "switchback") + estimators: tuple[str, ...] = ("difference_in_means", "regression_adjusted", "cluster_robust") + target_estimand: str = "market_total_effect" + cost_per_market_period: float = 1.0 + + def __post_init__(self) -> None: + if self.replications < 2: + raise ValueError("replications must be at least 2") + if not 0.5 < self.confidence_level < 1.0: + raise ValueError("confidence_level must be between 0.5 and 1") + if not self.designs: + raise ValueError("at least one design is required") + if not self.estimators: + raise ValueError("at least one estimator is required") + if self.cost_per_market_period <= 0: + raise ValueError("cost_per_market_period must be positive") + + @classmethod + def from_mapping(cls, values: Mapping[str, object]) -> BenchmarkConfig: + benchmark_values = values.get("benchmark", values) + if not isinstance(benchmark_values, Mapping): + raise ValueError("benchmark configuration must be a mapping") + kwargs = dict(benchmark_values) + if "designs" in kwargs: + kwargs["designs"] = tuple(str(value) for value in kwargs["designs"]) + if "estimators" in kwargs: + kwargs["estimators"] = tuple(str(value) for value in kwargs["estimators"]) + allowed = set(cls.__dataclass_fields__) + unknown = set(kwargs).difference(allowed) + if unknown: + raise ValueError(f"unknown benchmark configuration keys: {sorted(unknown)}") + return cls(**kwargs) + + @classmethod + def from_yaml(cls, path: str | Path) -> BenchmarkConfig: + with Path(path).open(encoding="utf-8") as stream: + values = yaml.safe_load(stream) or {} + return cls.from_mapping(values) + + +def summarize_monte_carlo( + records: pd.DataFrame, + *, + confidence_level: float = 0.95, + group_columns: Sequence[str] | None = None, +) -> pd.DataFrame: + """Summarize estimates against row-level known ground truth. + + Required columns are ``design``, ``estimator``, ``estimate``, ``std_error``, and + ``truth``. Optional grouping columns (target estimand, interference, persistence, + duration, or budget) are retained. Intervals are normal approximations using the + estimator's own standard error. ``information_cost`` is defined transparently as + total design cost times MSE: cost divided by precision (where precision is 1/MSE). + Coverage and power Monte Carlo uncertainty use the posterior standard deviation + under Jeffreys' binomial prior. Unlike the plug-in binomial standard error, this + remains positive when every simulated interval covers (or every test rejects), so + a small finite run is not presented as exact knowledge. + """ + + required = {"design", "estimator", "estimate", "std_error", "truth"} + missing = required.difference(records.columns) + if missing: + raise ValueError(f"Monte Carlo records missing columns: {sorted(missing)}") + if records.empty: + raise ValueError("Monte Carlo records must not be empty") + if not 0.5 < confidence_level < 1.0: + raise ValueError("confidence_level must be between 0.5 and 1") + + numeric = records[["estimate", "std_error", "truth"]].to_numpy(dtype=float) + if not np.isfinite(numeric).all(): + raise ValueError("estimate, std_error, and truth must be finite") + if (records["std_error"] < 0).any(): + raise ValueError("std_error cannot be negative") + + alpha = 1.0 - confidence_level + z = NormalDist().inv_cdf(0.5 + confidence_level / 2.0) + frame = records.copy() + frame["error"] = frame["estimate"] - frame["truth"] + frame["squared_error"] = frame["error"] ** 2 + if {"ci_low", "ci_high"}.issubset(frame.columns): + frame["covered"] = (frame["ci_low"] <= frame["truth"]) & ( + frame["truth"] <= frame["ci_high"] + ) + else: + frame["covered"] = ( + (frame["estimate"] - z * frame["std_error"] <= frame["truth"]) + & (frame["truth"] <= frame["estimate"] + z * frame["std_error"]) + ) + if "p_value" in frame: + frame["reject_null"] = frame["p_value"] < alpha + else: + frame["reject_null"] = ( + np.abs(frame["estimate"] / frame["std_error"].replace(0.0, np.nan)) > z + ) + frame["design_cost"] = frame.get("design_cost", pd.Series(1.0, index=frame.index)).astype(float) + + if group_columns is None: + declared_scenario_dimensions = ( + "design", + "estimator", + "target_estimand", + "scenario", + "spillover_strength", + "persistence", + "treatment_duration", + "washout_periods", + "treatment_saturation", + "budget", + "n_clusters", + "cluster_size", + "n_zones", + "n_periods", + "identified", + "evidence_type", + ) + group_columns = [ + column for column in declared_scenario_dimensions if column in frame.columns + ] + else: + group_columns = list(group_columns) + required_groups = {"design", "estimator"} + if not required_groups.issubset(group_columns): + raise ValueError("group_columns must include design and estimator") + + rows: list[dict[str, object]] = [] + grouped = frame.groupby(group_columns, dropna=False, sort=True) + for keys, group in grouped: + if not isinstance(keys, tuple): + keys = (keys,) + mse = float(group["squared_error"].mean()) + n_replications = int(len(group)) + rmse = float(np.sqrt(mse)) + bias_mcse = float(group["error"].std(ddof=1) / np.sqrt(n_replications)) + coverage = float(group["covered"].mean()) + power = float(group["reject_null"].mean()) + covered_count = int(group["covered"].sum()) + rejected_count = int(group["reject_null"].sum()) + + squared_error_mcse = float( + group["squared_error"].std(ddof=1) / np.sqrt(n_replications) + ) + row: dict[str, object] = dict(zip(group_columns, keys, strict=True)) + row.update( + { + "truth": float(group["truth"].mean()), + "mean_estimate": float(group["estimate"].mean()), + "bias": float(group["error"].mean()), + "bias_mcse": bias_mcse, + "variance": float(group["estimate"].var(ddof=1)), + "rmse": rmse, + "rmse_mcse": squared_error_mcse / (2.0 * rmse) if rmse > 0 else 0.0, + "coverage": coverage, + "coverage_mcse": _jeffreys_binomial_sd( + covered_count, n_replications + ), + "power": power, + "power_mcse": _jeffreys_binomial_sd( + rejected_count, n_replications + ), + "binomial_mcse_method": "jeffreys_posterior_standard_deviation", + "mean_std_error": float(group["std_error"].mean()), + "replications": n_replications, + "mean_design_cost": float(group["design_cost"].mean()), + "information_cost": float(group["design_cost"].mean()) * mse, + "confidence_level": confidence_level, + "evidence_type": "semi_synthetic_causal_monte_carlo", + } + ) + rows.append(row) + return pd.DataFrame(rows).sort_values(group_columns).reset_index(drop=True) + + +ReplicationFunction = Callable[[str, str, int], Mapping[str, object]] + + +def run_replications( + config: BenchmarkConfig, + replication_function: ReplicationFunction, +) -> tuple[pd.DataFrame, pd.DataFrame]: + """Run a caller-supplied simulation/estimation function deterministically. + + The callback receives ``(design, estimator, seed)`` and must return at least + ``estimate``, ``std_error``, and ``truth``. This narrow interface keeps the metric + engine reusable while simulator-specific orchestration remains explicit. + """ + + rows: list[dict[str, object]] = [] + seed_sequence = np.random.SeedSequence(config.seed) + # All estimators see the same market draw within a design/replication. This + # paired Monte Carlo comparison reduces noise in estimator rankings and makes + # debugging differences substantially easier. + child_sequences = seed_sequence.spawn(config.replications * len(config.designs)) + sequence_index = 0 + for design in config.designs: + for replication in range(config.replications): + seed = int(child_sequences[sequence_index].generate_state(1)[0]) + sequence_index += 1 + for estimator in config.estimators: + values = dict(replication_function(design, estimator, seed)) + missing = {"estimate", "std_error", "truth"}.difference(values) + if missing: + raise ValueError(f"replication callback missing: {sorted(missing)}") + values.update( + { + "design": design, + "estimator": estimator, + "replication": replication, + "seed": seed, + "target_estimand": values.get( + "target_estimand", config.target_estimand + ), + "design_cost": values.get( + "design_cost", config.cost_per_market_period + ), + } + ) + rows.append(values) + records = pd.DataFrame(rows) + return records, summarize_monte_carlo(records, confidence_level=config.confidence_level) + + +def write_benchmark_outputs( + records: pd.DataFrame, + summary: pd.DataFrame, + output_directory: str | Path, +) -> tuple[Path, Path]: + """Write stable CSV outputs with explicit evidence labels.""" + + directory = Path(output_directory) + directory.mkdir(parents=True, exist_ok=True) + records_path = directory / "monte_carlo_records.csv" + summary_path = directory / "benchmark_results.csv" + records.sort_values(["design", "estimator", "replication"]).to_csv(records_path, index=False) + summary.to_csv(summary_path, index=False) + return records_path, summary_path + + +def best_design_by_rmse( + summary: pd.DataFrame, + *, + target_estimand: str, + allowed_designs: Sequence[str] | None = None, +) -> pd.Series: + """Select the lowest-RMSE design/estimator for one declared estimand.""" + + required = {"design", "estimator", "target_estimand", "rmse"} + missing = required.difference(summary.columns) + if missing: + raise ValueError(f"benchmark summary missing columns: {sorted(missing)}") + eligible = summary.loc[summary["target_estimand"] == target_estimand] + if allowed_designs is not None: + eligible = eligible.loc[eligible["design"].isin(allowed_designs)] + if eligible.empty: + raise ValueError(f"no benchmark rows for target estimand {target_estimand!r}") + return eligible.sort_values(["rmse", "information_cost", "design", "estimator"]).iloc[0] diff --git a/CasualLab/src/casuallab/calibration.py b/CasualLab/src/casuallab/calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..b8c4bd63921bef902d0cb1a012d5b241acfdfded --- /dev/null +++ b/CasualLab/src/casuallab/calibration.py @@ -0,0 +1,195 @@ +"""Illustrative simulator scale anchoring from a descriptive real-data panel.""" + +from __future__ import annotations + +import json +from dataclasses import dataclass, replace +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd + +from casuallab.config import SimulationConfig + + +@dataclass(frozen=True) +class CalibrationResult: + """Calibrated config plus an audit trail of empirical and assumed quantities.""" + + config: SimulationConfig + empirical_targets: dict[str, float | int | None] + unchanged_structural_assumptions: tuple[str, ...] + evidence_type: str = "illustrative_empirical_scale_anchor" + + def to_dict(self) -> dict[str, object]: + return { + "evidence_type": self.evidence_type, + "empirical_targets": self.empirical_targets, + "unchanged_structural_assumptions": list(self.unchanged_structural_assumptions), + "simulation_config": self.config.to_dict(), + "warning": ( + "This stratified engineering fixture anchors scale but is not representative " + "of city market intensity. It does not identify structural price, incentive, " + "interference, substitution, or persistence parameters." + ), + } + + +def _to_pandas(frame: Any) -> pd.DataFrame: + if isinstance(frame, pd.DataFrame): + return frame.copy() + if hasattr(frame, "to_pandas"): + return frame.to_pandas() + raise TypeError("expected a pandas or Polars DataFrame") + + +def _find(frame: pd.DataFrame, candidates: tuple[str, ...]) -> str | None: + return next((column for column in candidates if column in frame.columns), None) + + +def _finite_mean(frame: pd.DataFrame, column: str | None) -> float | None: + if column is None: + return None + values = pd.to_numeric(frame[column], errors="coerce") + result = float(values.mean()) + return result if np.isfinite(result) else None + + +def _finite_weighted_mean( + frame: pd.DataFrame, + column: str | None, + weight_column: str, +) -> float | None: + if column is None: + return None + values = pd.to_numeric(frame[column], errors="coerce") + weights = pd.to_numeric(frame[weight_column], errors="coerce") + valid = values.notna() & weights.notna() & (weights > 0) + if not valid.any(): + return None + result = float(np.average(values.loc[valid], weights=weights.loc[valid])) + return result if np.isfinite(result) else None + + +def calibrate_simulation( + panel: Any, + template: SimulationConfig | None = None, +) -> CalibrationResult: + """Anchor baseline scale and fare while preserving causal assumptions. + + The public panel can provide observed trip and fare scale anchors. It cannot identify + latent requests, available drivers, demand response, supply response, spillovers, + persistence, substitution, or welfare, so those values remain config assumptions. + """ + + frame = _to_pandas(panel) + if frame.empty: + raise ValueError("calibration panel must not be empty") + base = template or SimulationConfig() + demand_column = _find(frame, ("trip_count", "completed_trips", "demand", "outcome")) + if demand_column is None: + raise ValueError("panel has no trip-count column for calibration") + fare_column = _find(frame, ("average_fare", "avg_fare", "mean_fare", "fare")) + duration_column = _find( + frame, + ("average_trip_seconds", "avg_trip_seconds", "mean_trip_seconds", "trip_seconds"), + ) + distance_column = _find( + frame, + ("average_trip_miles", "avg_trip_miles", "mean_trip_miles", "trip_miles"), + ) + pooled_column = _find( + frame, + ( + "pooled_trip_share", + "pooled_share", + "shared_trip_share", + "shared_matched_share", + "shared_requested_share", + ), + ) + + mean_demand = _finite_mean(frame, demand_column) + if mean_demand is None or mean_demand <= 0: + raise ValueError("mean panel trip count must be positive") + mean_fare = _finite_weighted_mean(frame, fare_column, demand_column) + # Rescale supply with demand so the configured (assumed) baseline tightness is + # preserved. Trip records do not observe available drivers, so the ratio itself + # is not estimated from this panel. + scale = mean_demand / base.base_demand + updates: dict[str, float] = { + "base_demand": mean_demand, + "base_supply": base.base_supply * scale, + } + if mean_fare is not None and mean_fare > 0: + updates["base_fare"] = mean_fare + + calibrated = replace(base, **updates) + # Completed trips are a matched-market outcome, not latent requests. Run the + # structural control path once, then proportionally rescale demand and supply so + # the achieved mean completed trips matches the empirical target while preserving + # the explicitly assumed supply-to-demand ratio. + from casuallab.simulator import simulate_market + + initial_control = simulate_market(calibrated).counterfactuals["control"] + initial_completed = float(initial_control["trips"].mean()) + if not np.isfinite(initial_completed) or initial_completed <= 0: + raise ValueError("simulator control path has non-positive completed trips") + market_scale = mean_demand / initial_completed + calibrated = replace( + calibrated, + base_demand=calibrated.base_demand * market_scale, + base_supply=calibrated.base_supply * market_scale, + ) + achieved_control = float( + simulate_market(calibrated).counterfactuals["control"]["trips"].mean() + ) + empirical_targets: dict[str, float | int | None] = { + "panel_rows": int(len(frame)), + "mean_completed_trips_per_observed_cell": mean_demand, + "mean_observed_fare": mean_fare, + "equal_observed_cell_mean_fare": _finite_mean(frame, fare_column), + "mean_observed_trip_seconds": _finite_weighted_mean( + frame, duration_column, demand_column + ), + "mean_observed_trip_miles": _finite_weighted_mean( + frame, distance_column, demand_column + ), + "mean_observed_pooled_trip_share": _finite_weighted_mean( + frame, pooled_column, demand_column + ), + "preserved_assumed_supply_to_demand_ratio": base.base_supply / base.base_demand, + "achieved_simulated_control_completed_trips": achieved_control, + "completed_trip_calibration_error": achieved_control - mean_demand, + } + structural = ( + "baseline_supply_to_demand_ratio", + "capacity_per_driver", + "matching_efficiency", + "rider_value", + "operating_cost_per_trip", + "wait_disutility_per_minute", + "treatment_version", + "discount_rate", + "incentive_per_driver", + "reference_incentive_per_driver", + "direct_demand_effect", + "direct_supply_effect", + "spillover_strength", + "persistence", + "rider_substitution", + "driver_mobility", + "zone_heterogeneity_sd", + "demand_noise_sd", + "supply_noise_sd", + "time_pattern_strength", + ) + return CalibrationResult(calibrated, empirical_targets, structural) + + +def write_calibration(result: CalibrationResult, path: str | Path) -> Path: + destination = Path(path) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(json.dumps(result.to_dict(), indent=2, sort_keys=True) + "\n", encoding="utf-8") + return destination diff --git a/CasualLab/src/casuallab/cli.py b/CasualLab/src/casuallab/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..4635c30aacf05268fbfd159779bd05681279f100 --- /dev/null +++ b/CasualLab/src/casuallab/cli.py @@ -0,0 +1,1883 @@ +"""Command-line entry points for the reproducible Causal Marketplace Lab workflow.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import platform +import sys +from collections.abc import Mapping, Sequence +from dataclasses import replace +from datetime import UTC, datetime +from importlib.metadata import PackageNotFoundError, version +from pathlib import Path +from time import perf_counter +from typing import Any + +import numpy as np +import pandas as pd +import yaml + +from casuallab.analysis import write_descriptive_artifacts +from casuallab.benchmark import BenchmarkConfig +from casuallab.calibration import calibrate_simulation, write_calibration +from casuallab.config import DesignConfig, DesignName, SimulationConfig, load_simulation_config +from casuallab.data import ( + download_sample, + load_data_config, + nyc_hvfhv_urls, + read_partitioned_parquet, + run_data_pipeline, + sha256_file, +) +from casuallab.equilibrium import ( + EquilibriumConfig, + run_equilibrium_benchmark, + write_equilibrium_artifacts, +) +from casuallab.generated_reports import generate_report_bundle +from casuallab.heterogeneity import cross_fitted_s_learner, subgroup_effect_summary +from casuallab.interference_benchmark import ( + InterferenceBenchmarkConfig, + InterferenceBenchmarkResult, + run_interference_benchmark, +) +from casuallab.marketplace_benchmark import run_marketplace_benchmark +from casuallab.nyc_benchmark import ( + NYCBenchmarkConfig, + run_nyc_informed_marketplace_benchmark, + write_nyc_benchmark_artifacts, +) +from casuallab.nyc_calibration import write_nyc_calibration_bundle +from casuallab.nyc_events import ( + download_nyc_permitted_events_snapshot, + write_nyc_events_bundle, +) +from casuallab.nyc_full_analysis import write_nyc_full_analysis +from casuallab.nyc_graph_benchmark import ( + NYCGraphBenchmarkConfig, + run_nyc_graph_benchmark, + write_nyc_graph_benchmark_artifacts, +) +from casuallab.nyc_income import write_nyc_income_bundle +from casuallab.nyc_simulation import ( + NYCSimulationAnchorSettings, + build_nyc_simulation_anchor, +) +from casuallab.nyc_weather import ( + download_noaa_daily_weather, + write_nyc_weather_bundle, +) +from casuallab.simulator import SimulationResult, simulate_market + +_REPRODUCTION_PACKAGES = ( + "duckdb", + "numpy", + "pandas", + "polars", + "pyarrow", + "pyproj", + "pyshp", + "PyYAML", + "scikit-learn", + "scipy", + "shapely", + "statsmodels", + "streamlit", +) + + +def _json_safe(value: Any) -> Any: + if isinstance(value, Path): + return str(value) + if isinstance(value, Mapping): + return {str(key): _json_safe(item) for key, item in value.items()} + if isinstance(value, (list, tuple, set, frozenset)): + return [_json_safe(item) for item in value] + if isinstance(value, (np.integer, np.floating)): + value = value.item() + if isinstance(value, float) and not np.isfinite(value): + return None + return value + + +def _write_json(payload: Mapping[str, Any], path: str | Path) -> Path: + destination = Path(path) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text( + json.dumps(_json_safe(payload), indent=2, sort_keys=True, allow_nan=False) + "\n", + encoding="utf-8", + ) + return destination + + +def _artifact_manifest( + files: Sequence[str | Path], + destination: str | Path, + *, + metadata: Mapping[str, Any], + root: str | Path | None = None, +) -> Path: + target = Path(destination) + project_root = Path(__file__).resolve().parents[2] + if root is not None: + manifest_root = Path(root).resolve() + else: + try: + target.resolve().relative_to(project_root) + manifest_root = project_root + except ValueError: + manifest_root = target.parent.resolve() + entries: list[dict[str, Any]] = [] + for raw_path in sorted({Path(path).resolve() for path in files}): + if not raw_path.is_file(): + raise FileNotFoundError(raw_path) + try: + rendered = str(raw_path.relative_to(manifest_root)) + except ValueError as exc: + if root is not None: + raise ValueError( + f"manifest input is outside the declared root: {raw_path}" + ) from exc + rendered = str(raw_path) + entries.append( + { + "path": rendered, + "bytes": raw_path.stat().st_size, + "sha256": sha256_file(raw_path), + } + ) + return _write_json( + { + "generated_at_utc": datetime.now(UTC).isoformat(), + "files": entries, + "metadata": metadata, + }, + target, + ) + + +def _source_tree_sha256(project_root: Path) -> str: + digest = hashlib.sha256() + candidates = [ + *project_root.joinpath("src").rglob("*.py"), + *project_root.joinpath("configs").rglob("*.yaml"), + project_root / "pyproject.toml", + project_root / "constraints.txt", + project_root / "Makefile", + ] + for path in sorted({item for item in candidates if item.is_file()}): + digest.update(str(path.relative_to(project_root)).encode("utf-8")) + digest.update(b"\0") + digest.update(path.read_bytes()) + digest.update(b"\0") + return digest.hexdigest() + + +def _runtime_environment() -> dict[str, Any]: + packages: dict[str, str | None] = {} + for package in _REPRODUCTION_PACKAGES: + try: + packages[package] = version(package) + except PackageNotFoundError: + packages[package] = None + return { + "python": sys.version.split()[0], + "implementation": platform.python_implementation(), + "platform": platform.platform(), + "packages": packages, + } + + +def write_simulation_outputs( + result: SimulationResult, + output_directory: str | Path, +) -> dict[str, Path]: + """Persist a simulation without serializing unavailable estimands as JSON NaN.""" + + directory = Path(output_directory) + directory.mkdir(parents=True, exist_ok=True) + panel_path = directory / "simulated_panel.parquet" + assignment_path = directory / "assignment.csv" + truth_path = directory / "ground_truth_unit_effects.parquet" + metadata_path = directory / "simulation_metadata.json" + result.panel.to_parquet(panel_path, index=False) + result.assignment.to_csv(assignment_path, index=False) + result.ground_truth.unit_effects.to_parquet(truth_path, index=False) + _write_json(dict(result.metadata), metadata_path) + manifest_path = _artifact_manifest( + [panel_path, assignment_path, truth_path, metadata_path], + directory / "manifest.json", + metadata={ + "evidence_type": "semi_synthetic_known_ground_truth", + "simulation_seed": result.metadata["simulation_seed"], + "assignment_seed": result.metadata["assignment_seed"], + "target_population_id": result.metadata["target_population_id"], + }, + ) + return { + "panel": panel_path, + "assignment": assignment_path, + "truth": truth_path, + "metadata": metadata_path, + "manifest": manifest_path, + } + + +def write_marketplace_benchmark_outputs( + records: pd.DataFrame, + summary: pd.DataFrame, + failures: pd.DataFrame, + fit_ledger: pd.DataFrame, + output_directory: str | Path, + *, + benchmark_config: BenchmarkConfig, + benchmark_config_path: str | Path, + simulation_config: SimulationConfig, + simulation_config_path: str | Path, + additional_input_paths: Sequence[str | Path] = (), +) -> dict[str, Path]: + directory = Path(output_directory) + directory.mkdir(parents=True, exist_ok=True) + records_path = directory / "monte_carlo_records.csv" + summary_path = directory / "benchmark_results.csv" + failures_path = directory / "benchmark_failures.csv" + fit_ledger_path = directory / "benchmark_fit_ledger.csv" + records.to_csv(records_path, index=False) + summary.to_csv(summary_path, index=False) + failures.to_csv(failures_path, index=False) + fit_ledger.to_csv(fit_ledger_path, index=False) + manifest_path = _artifact_manifest( + [ + records_path, + summary_path, + failures_path, + fit_ledger_path, + benchmark_config_path, + simulation_config_path, + *additional_input_paths, + ], + directory / "manifest.json", + metadata={ + "evidence_type": "semi_synthetic_causal_monte_carlo", + "benchmark_config": { + "replications": benchmark_config.replications, + "seed": benchmark_config.seed, + "confidence_level": benchmark_config.confidence_level, + "designs": list(benchmark_config.designs), + "estimators": list(benchmark_config.estimators), + "target_estimand": benchmark_config.target_estimand, + }, + "base_simulation_config_before_benchmark_overrides": ( + simulation_config.to_dict() + ), + "effective_scenario_plan": summary[ + [ + column + for column in ( + "scenario", + "declared_scenario_set", + "declared_scenario_count", + "varied_dimension", + "scenario_role", + "spillover_strength", + "persistence", + "treatment_duration", + "washout_periods", + "treatment_saturation", + "treatment_probability", + "configured_geo_clusters", + "cluster_size", + "budget", + "budget_scope", + "shared_budget_coupling", + "budget_binding_rate", + "treatment_version", + "n_zones", + "n_periods", + ) + if column in summary + ] + ] + .drop_duplicates() + .to_dict(orient="records"), + }, + ) + return { + "records": records_path, + "summary": summary_path, + "failures": failures_path, + "fit_ledger": fit_ledger_path, + "manifest": manifest_path, + } + + +def write_interference_benchmark_outputs( + result: InterferenceBenchmarkResult, + output_directory: str | Path, +) -> dict[str, Path]: + """Persist the known-truth mapped-exposure benchmark and its audit ledger.""" + + directory = Path(output_directory) + directory.mkdir(parents=True, exist_ok=True) + records_path = directory / "interference_records.csv" + summary_path = directory / "interference_summary.csv" + failures_path = directory / "interference_failures.csv" + fit_ledger_path = directory / "interference_fit_ledger.csv" + metadata_path = directory / "interference_metadata.json" + result.records.to_csv(records_path, index=False) + result.summary.to_csv(summary_path, index=False) + result.failures.to_csv(failures_path, index=False) + result.fit_ledger.to_csv(fit_ledger_path, index=False) + _write_json(dict(result.metadata), metadata_path) + manifest_path = _artifact_manifest( + [records_path, summary_path, failures_path, fit_ledger_path, metadata_path], + directory / "interference_manifest.json", + metadata={ + "evidence_type": result.metadata["evidence_type"], + "benchmark_config": result.metadata["config"], + "known_estimands": result.metadata["known_estimands"], + "controlled_exposure_not_market_total": True, + }, + ) + return { + "records": records_path, + "summary": summary_path, + "failures": failures_path, + "fit_ledger": fit_ledger_path, + "metadata": metadata_path, + "manifest": manifest_path, + } + + +def write_nyc_simulation_anchor_output( + anchor: Mapping[str, Any], + output_directory: str | Path, + *, + calibration_path: str | Path, + calibration_manifest_path: str | Path, + simulation_config_path: str | Path, + project_root: str | Path | None = None, +) -> dict[str, Path]: + """Persist one validated, explicitly noncausal NYC simulation anchor.""" + + directory = Path(output_directory) + directory.mkdir(parents=True, exist_ok=True) + anchor_path = _write_json(anchor, directory / "nyc_simulation_anchor.json") + manifest_path = _artifact_manifest( + [ + anchor_path, + calibration_path, + calibration_manifest_path, + simulation_config_path, + ], + directory / "manifest.json", + metadata={ + "evidence_label": anchor["evidence_label"], + "causal_claim": anchor["causal_claim"], + "status": anchor["status"], + "calibration_sha256": sha256_file(calibration_path), + "calibration_manifest_sha256": sha256_file(calibration_manifest_path), + "simulation_config_sha256": sha256_file(simulation_config_path), + "source_data_manifest_sha256": anchor["integrity"][ + "source_data_manifest_sha256" + ], + }, + root=project_root, + ) + return {"anchor": anchor_path, "manifest": manifest_path} + + +def _load_policy_yaml(path: str | Path) -> tuple[dict[str, Any], int, int]: + source = Path(path) + payload = yaml.safe_load(source.read_text(encoding="utf-8")) or {} + if not isinstance(payload, Mapping): + raise ValueError("policy configuration must be a mapping") + section = payload.get("policy", payload) + if not isinstance(section, Mapping): + raise ValueError("policy configuration section must be a mapping") + values = dict(section) + n_train = int(values.pop("n_train", 12)) + n_holdout = int(values.pop("n_holdout", 8)) + return values, n_train, n_holdout + + +def _write_hte_artifacts( + simulation: SimulationConfig, + output_directory: str | Path, +) -> dict[str, Path]: + # A geo-time experiment supplies binary variation across zones and periods. The + # benchmark removes interference/carryover so the conditional assignment + # contrast matches the simulator's controlled-zone truth, and entire geographic + # randomization clusters are held out in every nuisance fold. + n_zones = max(8, simulation.n_zones) + design = DesignConfig( + name=DesignName.GEO_TIME, + treatment_probability=0.5, + treatment_saturation=1.0, + n_clusters=4, + cluster_size=max(1, n_zones // 4), + treatment_duration=max(4, simulation.design.treatment_duration), + washout_periods=0, + budget=None, + seed=simulation.seed + 71, + ) + hte_config = replace( + simulation, + n_zones=n_zones, + budget=None, + spillover_strength=0.0, + persistence=0.0, + rider_substitution=0.0, + driver_mobility=0.0, + design=design, + ) + generated = simulate_market(hte_config) + hte = cross_fitted_s_learner( + generated.panel, + group="cluster_id", + folds=4, + trees=80, + seed=simulation.seed + 72, + evidence_type=( + "model_based_controlled_zone_heterogeneity_conditional_on_randomized_design" + ), + ) + predictions = hte.predictions.copy() + predictions["known_controlled_zone_truth"] = generated.panel[ + "true_controlled_zone_direct_effect" + ].to_numpy(dtype=float) + predictions["prediction_error"] = ( + predictions["estimated_cate"] - predictions["known_controlled_zone_truth"] + ) + known_truth = predictions["known_controlled_zone_truth"].to_numpy(dtype=float) + estimated_cate = predictions["estimated_cate"].to_numpy(dtype=float) + oracle_constant = float(np.mean(known_truth)) + constant_effect_baseline_rmse = float( + np.sqrt(np.mean((known_truth - oracle_constant) ** 2)) + ) + hte_rmse = float(np.sqrt(np.mean(predictions["prediction_error"] ** 2))) + predicted_truth_correlation = float( + pd.Series(estimated_cate).corr(pd.Series(known_truth), method="pearson") + ) + predicted_truth_rank_correlation = float( + pd.Series(estimated_cate).corr(pd.Series(known_truth), method="spearman") + ) + subgroup = subgroup_effect_summary( + generated.panel, + predictions["estimated_cate"], + modifier="market_tightness", + ) + calibration_frame = predictions[ + ["estimated_cate", "known_controlled_zone_truth", "prediction_error"] + ].copy() + calibration_frame["score_bin"] = pd.qcut( + calibration_frame["estimated_cate"], + q=5, + duplicates="drop", + ).astype(str) + calibration = ( + calibration_frame.groupby("score_bin", observed=True) + .agg( + mean_predicted_cate=("estimated_cate", "mean"), + mean_known_truth=("known_controlled_zone_truth", "mean"), + mean_error=("prediction_error", "mean"), + rmse=("prediction_error", lambda value: float(np.sqrt(np.mean(value**2)))), + rows=("prediction_error", "size"), + ) + .reset_index() + ) + subgroup_recovery_frame = pd.DataFrame( + { + "market_tightness": generated.panel["market_tightness"].to_numpy(dtype=float), + "estimated_cate": predictions["estimated_cate"], + "known_truth": predictions["known_controlled_zone_truth"], + "prediction_error": predictions["prediction_error"], + } + ) + subgroup_recovery_frame["market_tightness_bin"] = pd.qcut( + subgroup_recovery_frame["market_tightness"], + q=4, + duplicates="drop", + ).astype(str) + subgroup_recovery = ( + subgroup_recovery_frame.groupby("market_tightness_bin", observed=True) + .agg( + mean_market_tightness=("market_tightness", "mean"), + mean_predicted_cate=("estimated_cate", "mean"), + mean_known_truth=("known_truth", "mean"), + mean_error=("prediction_error", "mean"), + rows=("prediction_error", "size"), + ) + .reset_index() + ) + fold_stability = ( + predictions.groupby("crossfit_fold", observed=True) + .agg( + mean_predicted_cate=("estimated_cate", "mean"), + mean_known_truth=("known_controlled_zone_truth", "mean"), + mean_error=("prediction_error", "mean"), + rmse=("prediction_error", lambda value: float(np.sqrt(np.mean(value**2)))), + rows=("prediction_error", "size"), + ) + .reset_index() + ) + directory = Path(output_directory) + directory.mkdir(parents=True, exist_ok=True) + predictions_path = directory / "hte_predictions.csv" + importance_path = directory / "hte_feature_importance.csv" + subgroup_path = directory / "hte_subgroups.csv" + calibration_path = directory / "hte_calibration_by_score.csv" + subgroup_recovery_path = directory / "hte_subgroup_recovery.csv" + fold_stability_path = directory / "hte_fold_stability.csv" + calibration_chart_path = directory / "hte_calibration_chart.html" + summary_path = directory / "hte_recovery.json" + predictions.to_csv(predictions_path, index=False) + hte.feature_importance.to_csv(importance_path, index=False) + subgroup.to_csv(subgroup_path, index=False) + calibration.to_csv(calibration_path, index=False) + subgroup_recovery.to_csv(subgroup_recovery_path, index=False) + fold_stability.to_csv(fold_stability_path, index=False) + import altair as alt # noqa: PLC0415 + + calibration_chart = ( + alt.Chart(calibration) + .mark_line(point=True) + .encode( + x=alt.X("mean_known_truth:Q", title="Mean known controlled-zone truth"), + y=alt.Y("mean_predicted_cate:Q", title="Mean cross-fitted predicted CATE"), + tooltip=[ + "score_bin:N", + "rows:Q", + "mean_known_truth:Q", + "mean_predicted_cate:Q", + "mean_error:Q", + ], + ) + .properties(title="CATE calibration by held-out score bin") + ) + calibration_chart.save(calibration_chart_path) + _write_json( + { + "evidence_type": "semi_synthetic_hte_known_truth_recovery", + "target_estimand": "controlled_zone_direct_effect", + "crossfit_group": "geographic_randomization_cluster", + "interference": 0.0, + "persistence": 0.0, + "rows": len(predictions), + "bias": float(predictions["prediction_error"].mean()), + "rmse": hte_rmse, + "known_truth_sd": float(np.std(known_truth, ddof=0)), + "oracle_constant_effect_rmse": constant_effect_baseline_rmse, + "predicted_truth_correlation": predicted_truth_correlation, + "predicted_truth_rank_correlation": predicted_truth_rank_correlation, + "hte_beats_oracle_constant": hte_rmse < constant_effect_baseline_rmse, + "recovery_gate": "rmse_below_oracle_constant_effect_rmse", + "fold_mean_cate_sd": float( + fold_stability["mean_predicted_cate"].std(ddof=1) + ), + "fold_bias_sd": float(fold_stability["mean_error"].std(ddof=1)), + "calibration_bins": len(calibration), + "simulation_seed": hte_config.seed, + "assignment_seed": design.seed, + }, + summary_path, + ) + manifest_path = _artifact_manifest( + [ + predictions_path, + importance_path, + subgroup_path, + calibration_path, + subgroup_recovery_path, + fold_stability_path, + calibration_chart_path, + summary_path, + ], + directory / "manifest.json", + metadata={ + "target_estimand": "controlled_zone_direct_effect", + "evidence_type": "semi_synthetic_hte_known_truth_recovery", + "simulation_config": hte_config.to_dict(), + }, + ) + return { + "predictions": predictions_path, + "importance": importance_path, + "subgroups": subgroup_path, + "calibration": calibration_path, + "subgroup_recovery": subgroup_recovery_path, + "fold_stability": fold_stability_path, + "calibration_chart": calibration_chart_path, + "summary": summary_path, + "manifest": manifest_path, + } + + +def _run_download_sample(args: argparse.Namespace) -> list[Path]: + config = load_data_config(args.config) + if config.mode != "sample": + raise ValueError("download-sample requires a data config with mode: sample") + return [download_sample(config, refresh=args.refresh)] + + +def _run_build_panel(args: argparse.Namespace) -> list[Path]: + config = load_data_config(args.config) + if config.mode == "full" and not getattr(args, "allow_full_download", False): + raise ValueError( + "full-data ingestion requires explicit --allow-full-download; " + "sample_rows does not bound full mode" + ) + artifacts = run_data_pipeline(config, refresh=args.refresh) + return [ + *artifacts.raw_files, + *artifacts.clean_files, + *artifacts.panel_files, + *artifacts.od_flow_files, + artifacts.diagnostics_path, + artifacts.manifest_path, + ] + + +def _run_validate_nyc_full(args: argparse.Namespace) -> list[Path]: + """Build and validate one explicitly authorized NYC full-month extract.""" + + config = load_data_config(args.config) + if config.source != "nyc_hvfhv" or config.mode != "full": + raise ValueError("validate-nyc-full requires a NYC mode: full config") + if not getattr(args, "allow_full_download", False): + raise ValueError("validate-nyc-full requires explicit --allow-full-download") + raw_paths = tuple(config.raw_dir / Path(url).name for url in nyc_hvfhv_urls(config)) + raw_cached = all(path.is_file() for path in raw_paths) + started = perf_counter() + data_artifacts = run_data_pipeline(config, refresh=args.refresh) + analysis = write_nyc_full_analysis( + config, + args.output_dir, + started_at_monotonic=started, + raw_cached=raw_cached, + command=( + ".venv/bin/python -m casuallab validate-nyc-full " + f"--config {args.config} --allow-full-download" + ), + ) + calibration = write_nyc_calibration_bundle( + config, + Path(args.output_dir) / "calibration_network", + ) + return [ + *data_artifacts.raw_files, + data_artifacts.diagnostics_path, + data_artifacts.manifest_path, + *analysis.paths(), + *calibration.paths(), + ] + + +def _run_simulate(args: argparse.Namespace) -> list[Path]: + config = load_simulation_config(args.config) + outputs = write_simulation_outputs(simulate_market(config), args.output_dir) + return list(outputs.values()) + + +def _run_benchmark(args: argparse.Namespace) -> list[Path]: + benchmark = BenchmarkConfig.from_yaml(args.config) + simulation = load_simulation_config(args.simulation_config) + result = run_marketplace_benchmark(benchmark, simulation) + outputs = write_marketplace_benchmark_outputs( + result.records, + result.summary, + result.failures, + result.fit_ledger, + args.output_dir, + benchmark_config=benchmark, + benchmark_config_path=args.config, + simulation_config=simulation, + simulation_config_path=args.simulation_config, + ) + return list(outputs.values()) + + +def _run_interference_benchmark(args: argparse.Namespace) -> list[Path]: + config = InterferenceBenchmarkConfig( + replications=args.replications, + seed=args.seed, + ) + outputs = write_interference_benchmark_outputs( + run_interference_benchmark(config), + args.output_dir, + ) + return list(outputs.values()) + + +def _run_nyc_simulation_anchor(args: argparse.Namespace) -> list[Path]: + project_root = Path(__file__).resolve().parents[2] + anchor = build_nyc_simulation_anchor( + args.calibration, + project_root=project_root, + manifest_path=args.calibration_manifest, + settings=NYCSimulationAnchorSettings( + target_n_zones=args.n_zones, + target_n_periods=args.n_periods, + seed=args.seed, + ), + assumption_template=load_simulation_config(args.simulation_config), + ) + outputs = write_nyc_simulation_anchor_output( + anchor, + args.output_dir, + calibration_path=args.calibration, + calibration_manifest_path=args.calibration_manifest, + simulation_config_path=args.simulation_config, + project_root=project_root, + ) + return list(outputs.values()) + + +def _run_nyc_weather(args: argparse.Namespace) -> list[Path]: + """Validate the pinned NOAA response and join it to the full NYC panel.""" + + project_root = Path(__file__).resolve().parents[2] + raw_path = download_noaa_daily_weather(args.raw, refresh=args.refresh) + artifacts = write_nyc_weather_bundle( + raw_path, + args.panel_dir, + args.data_manifest, + args.output_dir, + project_root=project_root, + ) + return list(artifacts.paths()) + + +def _run_nyc_events(args: argparse.Namespace) -> list[Path]: + """Validate cached official calendars and publish descriptive event evidence.""" + + project_root = Path(__file__).resolve().parents[2] + event_path = download_nyc_permitted_events_snapshot( + args.events, + refresh=args.refresh, + ) + artifacts = write_nyc_events_bundle( + args.holidays, + event_path, + args.panel_dir, + args.data_manifest, + args.output_dir, + project_root=project_root, + ) + return list(artifacts.paths()) + + +def _run_nyc_income(args: argparse.Namespace) -> list[Path]: + """Publish ecological, non-causal NYC high/low-income trip descriptions.""" + + project_root = Path(__file__).resolve().parents[2] + artifacts = write_nyc_income_bundle( + args.taxi_zones, + args.nta, + args.tract_to_nta, + args.acs_b19001, + args.panel_dir, + args.data_manifest, + args.output_dir, + project_root=project_root, + ) + return list(artifacts.paths()) + + +def _run_nyc_benchmark(args: argparse.Namespace) -> list[Path]: + """Run the known-truth marketplace benchmark from the validated NYC anchor.""" + + project_root = Path(__file__).resolve().parents[2] + result = run_nyc_informed_marketplace_benchmark( + args.anchor, + args.anchor_manifest, + config=NYCBenchmarkConfig( + replications=args.replications, + seed=args.seed, + n_zones=args.n_zones, + n_periods=args.n_periods, + ), + project_root=project_root, + ) + outputs = write_nyc_benchmark_artifacts( + result, + args.output_dir, + project_root=project_root, + ) + return [path for key, path in outputs.items() if key != "output_directory"] + + +def _run_nyc_graph_benchmark(args: argparse.Namespace) -> list[Path]: + """Run the known-truth interference benchmark on the validated NYC OD graph.""" + + project_root = Path(__file__).resolve().parents[2] + result = run_nyc_graph_benchmark( + args.bundle, + NYCGraphBenchmarkConfig( + replications=args.replications, + seed=args.seed, + n_zones=args.n_zones, + n_periods=args.n_periods, + ), + ) + outputs = write_nyc_graph_benchmark_artifacts( + result, + args.output_dir, + project_root=project_root, + ) + return [path for key, path in outputs.items() if key != "output_directory"] + + +def _run_equilibrium_benchmark(args: argparse.Namespace) -> list[Path]: + """Solve and persist a transparent two-sided fixed-point benchmark.""" + + project_root = Path(__file__).resolve().parents[2] + result = run_equilibrium_benchmark( + EquilibriumConfig( + n_zones=args.n_zones, + seed=args.seed, + treatment_version=args.treatment_version, + budget=args.budget, + ), + planned_treatment_intensity=args.treatment_intensity, + ) + return list( + write_equilibrium_artifacts( + result, + args.output_dir, + project_root, + ).paths() + ) + + +def _optional_nyc_full_evidence_paths( + args: argparse.Namespace, +) -> tuple[Path | None, Path | None]: + """Return a complete cached NYC evidence pair or preserve a partial pair to fail closed.""" + + validation_value = getattr(args, "nyc_full_validation", None) + manifest_value = getattr(args, "nyc_full_manifest", None) + if not validation_value and not manifest_value: + return None, None + validation = Path(validation_value) if validation_value else None + manifest = Path(manifest_value) if manifest_value else None + if ( + validation is not None + and manifest is not None + and not validation.exists() + and not manifest.exists() + ): + return None, None + return validation, manifest + + +def _optional_treatment_version_policy_paths( + args: argparse.Namespace, +) -> tuple[Path | None, Path | None]: + summary_value = getattr(args, "treatment_version_policy", None) + manifest_value = getattr(args, "treatment_version_policy_manifest", None) + if not summary_value and not manifest_value: + return None, None + summary = Path(summary_value) if summary_value else None + manifest = Path(manifest_value) if manifest_value else None + if ( + summary is not None + and manifest is not None + and not summary.exists() + and not manifest.exists() + ): + return None, None + return summary, manifest + + +def _optional_interference_paths( + args: argparse.Namespace, +) -> tuple[Path | None, Path | None]: + summary_value = getattr(args, "interference_summary", None) + manifest_value = getattr(args, "interference_manifest", None) + if not summary_value and not manifest_value: + return None, None + summary = Path(summary_value) if summary_value else None + manifest = Path(manifest_value) if manifest_value else None + if ( + summary is not None + and manifest is not None + and not summary.exists() + and not manifest.exists() + ): + return None, None + return summary, manifest + + +def _optional_nyc_anchor_paths( + args: argparse.Namespace, +) -> tuple[Path | None, Path | None]: + anchor_value = getattr(args, "nyc_simulation_anchor", None) + manifest_value = getattr(args, "nyc_simulation_anchor_manifest", None) + if not anchor_value and not manifest_value: + return None, None + anchor = Path(anchor_value) if anchor_value else None + manifest = Path(manifest_value) if manifest_value else None + if ( + anchor is not None + and manifest is not None + and not anchor.exists() + and not manifest.exists() + ): + return None, None + return anchor, manifest + + +def _optional_manifest_path(args: argparse.Namespace, field: str) -> Path | None: + """Return an optional generated manifest, treating an absent default as unavailable.""" + + value = getattr(args, field, None) + if not value: + return None + path = Path(value) + return path if path.is_file() else None + + +def _offline_enrichment_ready( + label: str, + *, + nyc_dependencies: Sequence[Path], + external_sources: Sequence[Path], +) -> bool: + """Gate an optional enrichment without silently accepting partial cached state.""" + + nyc_present = [path.exists() for path in nyc_dependencies] + if not any(nyc_present): + return False + if not all(nyc_present): + missing = [ + str(path) + for path, present in zip(nyc_dependencies, nyc_present, strict=True) + if not present + ] + raise ValueError(f"cached {label} requires complete NYC dependencies; missing {missing}") + source_present = [path.is_file() for path in external_sources] + if not any(source_present): + return False + if not all(source_present): + missing = [ + str(path) + for path, present in zip(external_sources, source_present, strict=True) + if not present + ] + raise ValueError(f"cached {label} requires every pinned external source; missing {missing}") + return True + + +def _run_report(args: argparse.Namespace) -> list[Path]: + policy = Path(args.policy) if args.policy else None + if policy is not None and not policy.is_file(): + policy = None + nyc_validation, nyc_manifest = _optional_nyc_full_evidence_paths(args) + version_policy, version_policy_manifest = _optional_treatment_version_policy_paths( + args + ) + interference_summary, interference_manifest = _optional_interference_paths(args) + nyc_anchor, nyc_anchor_manifest = _optional_nyc_anchor_paths(args) + nyc_benchmark_manifest = _optional_manifest_path(args, "nyc_benchmark_manifest") + nyc_graph_manifest = _optional_manifest_path(args, "nyc_graph_benchmark_manifest") + equilibrium_manifest = _optional_manifest_path(args, "equilibrium_manifest") + nyc_weather_manifest = _optional_manifest_path(args, "nyc_weather_manifest") + nyc_events_manifest = _optional_manifest_path(args, "nyc_events_manifest") + nyc_income_manifest = _optional_manifest_path(args, "nyc_income_manifest") + outputs = generate_report_bundle( + args.benchmark, + output_directory=args.output_dir, + policy_path=policy, + descriptive_path=args.descriptive, + calibration_path=args.calibration, + failures_path=args.failures, + hte_summary_path=getattr(args, "hte_summary", None), + hte_calibration_path=getattr(args, "hte_calibration", None), + hte_stability_path=getattr(args, "hte_stability", None), + nyc_full_validation_path=nyc_validation, + nyc_full_manifest_path=nyc_manifest, + treatment_version_policy_path=version_policy, + treatment_version_policy_manifest_path=version_policy_manifest, + interference_summary_path=interference_summary, + interference_manifest_path=interference_manifest, + nyc_simulation_anchor_path=nyc_anchor, + nyc_simulation_anchor_manifest_path=nyc_anchor_manifest, + nyc_benchmark_manifest_path=nyc_benchmark_manifest, + nyc_graph_benchmark_manifest_path=nyc_graph_manifest, + equilibrium_manifest_path=equilibrium_manifest, + nyc_weather_manifest_path=nyc_weather_manifest, + nyc_events_manifest_path=nyc_events_manifest, + nyc_income_manifest_path=nyc_income_manifest, + target_estimand=args.target_estimand, + ) + return list(outputs.values()) + + +def _run_reproduce_inner(args: argparse.Namespace) -> list[Path]: + outputs: list[Path] = [] + project_root = Path(__file__).resolve().parents[2] + data_artifacts = run_data_pipeline(args.config, refresh=args.refresh) + outputs.extend( + [ + *data_artifacts.raw_files, + *data_artifacts.clean_files, + *data_artifacts.panel_files, + *data_artifacts.od_flow_files, + data_artifacts.diagnostics_path, + data_artifacts.manifest_path, + ] + ) + panel = read_partitioned_parquet(load_data_config(args.config).panel_dir / "zone_time") + trips = read_partitioned_parquet(load_data_config(args.config).clean_dir / "trips") + descriptive = write_descriptive_artifacts( + panel, + Path(args.output_root) / "reports/descriptive", + trips=trips, + ) + outputs.extend(descriptive.values()) + + simulation_template = load_simulation_config(args.simulation_config) + calibration = calibrate_simulation(panel, simulation_template) + calibration_path = write_calibration( + calibration, + Path(args.output_root) / "reports/calibration.json", + ) + outputs.append(calibration_path) + nyc_anchor_outputs: dict[str, Path] = {} + nyc_benchmark_outputs: dict[str, Path] = {} + nyc_graph_outputs: dict[str, Path] = {} + nyc_weather_outputs: dict[str, Path] = {} + nyc_events_outputs: dict[str, Path] = {} + nyc_income_outputs: dict[str, Path] = {} + nyc_validation_value = getattr(args, "nyc_full_validation", None) + nyc_artifact_root = ( + Path(nyc_validation_value).parent + if nyc_validation_value + else project_root / "artifacts/nyc_full" + ) + nyc_calibration_path = nyc_artifact_root / "calibration_network/calibration.json" + nyc_calibration_manifest = nyc_artifact_root / "calibration_network/manifest.json" + if nyc_calibration_path.exists() != nyc_calibration_manifest.exists(): + raise ValueError("cached NYC calibration requires both calibration and manifest") + if nyc_calibration_path.is_file() and nyc_calibration_manifest.is_file(): + nyc_anchor = build_nyc_simulation_anchor( + nyc_calibration_path, + project_root=project_root, + manifest_path=nyc_calibration_manifest, + settings=NYCSimulationAnchorSettings( + target_n_zones=32, + target_n_periods=168, + seed=simulation_template.seed, + ), + assumption_template=simulation_template, + ) + nyc_anchor_outputs = write_nyc_simulation_anchor_output( + nyc_anchor, + Path(args.output_root) / "nyc_full/simulation_anchor", + calibration_path=nyc_calibration_path, + calibration_manifest_path=nyc_calibration_manifest, + simulation_config_path=args.simulation_config, + project_root=project_root, + ) + outputs.extend(nyc_anchor_outputs.values()) + nyc_benchmark_outputs = write_nyc_benchmark_artifacts( + run_nyc_informed_marketplace_benchmark( + nyc_anchor_outputs["anchor"], + nyc_anchor_outputs["manifest"], + config=NYCBenchmarkConfig(), + project_root=project_root, + ), + Path(args.output_root) / "benchmarks/nyc_informed", + project_root=project_root, + ) + outputs.extend( + path + for key, path in nyc_benchmark_outputs.items() + if key != "output_directory" + ) + + nyc_graph_outputs = write_nyc_graph_benchmark_artifacts( + run_nyc_graph_benchmark( + nyc_calibration_path.parent, + NYCGraphBenchmarkConfig(), + ), + Path(args.output_root) / "benchmarks/nyc_graph", + project_root=project_root, + ) + outputs.extend( + path + for key, path in nyc_graph_outputs.items() + if key != "output_directory" + ) + + full_data_manifest = project_root / "data/nyc_full/manifest.json" + full_panel_directory = project_root / "data/nyc_full/panel/zone_time" + weather_raw = ( + project_root + / "data/nyc_weather/raw/noaa_central_park_2024-01.csv" + ) + weather_dependencies = ( + full_data_manifest, + full_panel_directory, + weather_raw, + ) + if all(path.exists() for path in weather_dependencies): + weather_artifacts = write_nyc_weather_bundle( + weather_raw, + full_panel_directory, + full_data_manifest, + Path(args.output_root) / "nyc_full/weather", + project_root=project_root, + ) + nyc_weather_outputs = { + "normalized": weather_artifacts.normalized_weather_path, + "daily": weather_artifacts.daily_panel_path, + "hourly": weather_artifacts.hourly_contrast_path, + "summary": weather_artifacts.summary_path, + "manifest": weather_artifacts.manifest_path, + } + outputs.extend(nyc_weather_outputs.values()) + + full_data_manifest = project_root / "data/nyc_full/manifest.json" + full_panel_directory = project_root / "data/nyc_full/panel/zone_time" + shared_nyc_dependencies = (full_data_manifest, full_panel_directory) + income_sources = ( + project_root / "data/nyc_income/raw/taxi_zones.zip", + project_root / "data/nyc_income/raw/nyc_nta2020.geojson", + project_root / "data/nyc_income/raw/nyc_tract2020_to_nta2020.csv", + project_root / "data/nyc_income/raw/acs_2022_5yr_b19001_nyc_tracts.dat", + ) + if _offline_enrichment_ready( + "NYC income enrichment", + nyc_dependencies=shared_nyc_dependencies, + external_sources=income_sources, + ): + income_artifacts = write_nyc_income_bundle( + *income_sources, + full_panel_directory, + full_data_manifest, + Path(args.output_root) / "nyc_full/income", + project_root=project_root, + ) + nyc_income_outputs = { + "crosswalk": income_artifacts.crosswalk_path, + "nta_income": income_artifacts.nta_income_path, + "zone_income": income_artifacts.zone_income_path, + "daily": income_artifacts.daily_path, + "monthly": income_artifacts.monthly_path, + "summary": income_artifacts.summary_path, + "manifest": income_artifacts.manifest_path, + } + outputs.extend(nyc_income_outputs.values()) + + event_sources = ( + project_root / "data/nyc_events/raw/official_holidays_2024-01.csv", + project_root / "data/nyc_events/raw/nyc_permitted_events_overlap_2024-01.csv", + ) + if _offline_enrichment_ready( + "NYC calendar/event enrichment", + nyc_dependencies=shared_nyc_dependencies, + external_sources=event_sources, + ): + event_artifacts = write_nyc_events_bundle( + *event_sources, + full_panel_directory, + full_data_manifest, + Path(args.output_root) / "nyc_full/events", + project_root=project_root, + ) + nyc_events_outputs = { + "calendar_daily": event_artifacts.calendar_daily_path, + "normalized_events": event_artifacts.normalized_events_path, + "event_type_daily": event_artifacts.event_type_daily_path, + "daily": event_artifacts.daily_panel_path, + "hourly": event_artifacts.hourly_contrast_path, + "summary": event_artifacts.summary_path, + "manifest": event_artifacts.manifest_path, + } + outputs.extend(nyc_events_outputs.values()) + outputs.extend( + write_simulation_outputs( + simulate_market(calibration.config), + Path(args.output_root) / "simulation", + ).values() + ) + + equilibrium_artifacts = write_equilibrium_artifacts( + run_equilibrium_benchmark(EquilibriumConfig()), + Path(args.output_root) / "benchmarks/equilibrium", + project_root, + ) + equilibrium_outputs = { + "summary": equilibrium_artifacts.summary_path, + "zone_effects": equilibrium_artifacts.zone_effects_path, + "ledger": equilibrium_artifacts.ledger_path, + "manifest": equilibrium_artifacts.manifest_path, + } + outputs.extend(equilibrium_outputs.values()) + + benchmark = BenchmarkConfig.from_yaml(args.benchmark_config) + benchmark_result = run_marketplace_benchmark(benchmark, calibration.config) + benchmark_outputs = write_marketplace_benchmark_outputs( + benchmark_result.records, + benchmark_result.summary, + benchmark_result.failures, + benchmark_result.fit_ledger, + Path(args.output_root) / "benchmarks", + benchmark_config=benchmark, + benchmark_config_path=args.benchmark_config, + simulation_config=calibration.config, + simulation_config_path=args.simulation_config, + additional_input_paths=(calibration_path,), + ) + outputs.extend(benchmark_outputs.values()) + interference_outputs = write_interference_benchmark_outputs( + run_interference_benchmark(), + Path(args.output_root) / "benchmarks", + ) + outputs.extend(interference_outputs.values()) + hte_outputs = _write_hte_artifacts( + calibration.config, + Path(args.output_root) / "benchmarks/heterogeneity", + ) + outputs.extend(hte_outputs.values()) + + # Imported lazily so the core data/simulation commands remain usable even when + # policy extras are being developed independently. + from casuallab.marketplace_policy import ( # noqa: PLC0415 + MarketplacePolicyConfig, + run_marketplace_policy_evaluation, + run_treatment_version_policy_evaluation, + ) + + policy_values, n_train, n_holdout = _load_policy_yaml(args.policy_config) + policy_config = MarketplacePolicyConfig.from_mapping(policy_values) + policy_result = run_marketplace_policy_evaluation( + calibration.config, + policy_config, + n_train_markets=n_train, + n_holdout_markets=n_holdout, + ) + policy_path = Path(args.output_root) / "benchmarks/policy_results.csv" + policy_ledger_path = Path(args.output_root) / "benchmarks/policy_market_ledger.csv" + policy_path.parent.mkdir(parents=True, exist_ok=True) + policy_result.summary.to_csv(policy_path, index=False) + policy_result.market_results.to_csv(policy_ledger_path, index=False) + policy_manifest = _artifact_manifest( + [policy_path, policy_ledger_path, args.policy_config, calibration_path], + Path(args.output_root) / "benchmarks/policy_manifest.json", + metadata={ + "evidence_type": "semi_synthetic_policy_holdout", + "simulation_config": calibration.config.to_dict(), + "policy_config": policy_values, + "training_markets": n_train, + "holdout_markets": n_holdout, + }, + ) + outputs.extend([policy_path, policy_ledger_path, policy_manifest]) + + version_policy_result = run_treatment_version_policy_evaluation( + calibration.config, + policy_config, + n_train_markets=n_train, + n_holdout_markets=n_holdout, + ) + version_policy_path = ( + Path(args.output_root) / "benchmarks/treatment_version_policy_results.csv" + ) + version_policy_ledger_path = ( + Path(args.output_root) / "benchmarks/treatment_version_policy_market_ledger.csv" + ) + version_policy_result.summary.to_csv(version_policy_path, index=False) + version_policy_result.market_results.to_csv( + version_policy_ledger_path, index=False + ) + treatment_versions = list( + dict.fromkeys(version_policy_result.summary["treatment_version"].astype(str)) + ) + version_policy_manifest = _artifact_manifest( + [ + version_policy_path, + version_policy_ledger_path, + args.policy_config, + calibration_path, + ], + Path(args.output_root) / "benchmarks/treatment_version_policy_manifest.json", + metadata={ + "evidence_type": "semi_synthetic_treatment_version_policy_sensitivity", + "treatment_versions": treatment_versions, + "version_pairing": ( + "common training/holdout market seeds across intervention versions" + ), + "simulation_config_before_treatment_version_overrides": ( + calibration.config.to_dict() + ), + "policy_config": policy_values, + "training_markets": n_train, + "holdout_markets": n_holdout, + }, + ) + outputs.extend( + [version_policy_path, version_policy_ledger_path, version_policy_manifest] + ) + + report_args = argparse.Namespace( + benchmark=str(benchmark_outputs["summary"]), + policy=str(policy_path), + output_dir=str(Path(args.output_root) / "reports"), + descriptive=str(descriptive["moments"]), + calibration=str(calibration_path), + failures=str(benchmark_outputs["failures"]), + hte_summary=str(hte_outputs["summary"]), + hte_calibration=str(hte_outputs["calibration"]), + hte_stability=str(hte_outputs["fold_stability"]), + nyc_full_validation=getattr(args, "nyc_full_validation", None), + nyc_full_manifest=getattr(args, "nyc_full_manifest", None), + treatment_version_policy=str(version_policy_path), + treatment_version_policy_manifest=str(version_policy_manifest), + interference_summary=str(interference_outputs["summary"]), + interference_manifest=str(interference_outputs["manifest"]), + nyc_simulation_anchor=( + str(nyc_anchor_outputs["anchor"]) if nyc_anchor_outputs else None + ), + nyc_simulation_anchor_manifest=( + str(nyc_anchor_outputs["manifest"]) if nyc_anchor_outputs else None + ), + nyc_benchmark_manifest=( + str(nyc_benchmark_outputs["manifest"]) + if nyc_benchmark_outputs + else None + ), + nyc_graph_benchmark_manifest=( + str(nyc_graph_outputs["manifest"]) if nyc_graph_outputs else None + ), + equilibrium_manifest=str(equilibrium_outputs["manifest"]), + nyc_weather_manifest=( + str(nyc_weather_outputs["manifest"]) + if nyc_weather_outputs + else None + ), + nyc_events_manifest=( + str(nyc_events_outputs["manifest"]) + if nyc_events_outputs + else None + ), + nyc_income_manifest=( + str(nyc_income_outputs["manifest"]) + if nyc_income_outputs + else None + ), + target_estimand=benchmark.target_estimand, + ) + outputs.extend(_run_report(report_args)) + nyc_validation, nyc_manifest = _optional_nyc_full_evidence_paths(report_args) + nyc_full_lineage: dict[str, Any] | None = None + if nyc_validation is not None and nyc_manifest is not None: + validation_payload = json.loads(nyc_validation.read_text(encoding="utf-8")) + nyc_full_lineage = { + "validation_sha256": sha256_file(nyc_validation), + "analysis_manifest_sha256": sha256_file(nyc_manifest), + "source_data_manifest_sha256": validation_payload["provenance"][ + "data_manifest_sha256" + ], + } + treatment_version_policy_lineage = { + "summary_sha256": sha256_file(version_policy_path), + "manifest_sha256": sha256_file(version_policy_manifest), + } + extended_evidence_layers = [ + "theoretical_simulation_known_ground_truth", + ] + if nyc_benchmark_outputs: + extended_evidence_layers.append( + "semi_synthetic_nyc_informed_known_truth_monte_carlo" + ) + if nyc_graph_outputs: + extended_evidence_layers.append( + "semi_synthetic_known_truth_on_descriptive_nyc_graph" + ) + if nyc_weather_outputs: + extended_evidence_layers.append("descriptive_observed_external_weather") + if nyc_events_outputs: + extended_evidence_layers.append( + "descriptive_observed_external_calendar_events" + ) + if nyc_income_outputs: + extended_evidence_layers.append( + "descriptive_observed_external_neighborhood_income" + ) + manifest = _artifact_manifest( + outputs, + Path(args.output_root) / "reproduce_manifest.json", + metadata={ + "evidence_layers": [ + "descriptive_real_data", + "illustrative_empirical_scale_anchor", + "semi_synthetic_known_ground_truth", + "semi_synthetic_causal_monte_carlo", + "semi_synthetic_policy_holdout", + "semi_synthetic_treatment_version_policy_sensitivity", + "semi_synthetic_exposure_mapped_known_truth_benchmark", + "semi_synthetic_descriptive_anchor", + *extended_evidence_layers, + ], + "data_config_sha256": sha256_file(args.config), + "simulation_config_sha256": sha256_file(args.simulation_config), + "benchmark_config_sha256": sha256_file(args.benchmark_config), + "policy_config_sha256": sha256_file(args.policy_config), + "constraints_sha256": sha256_file(project_root / "constraints.txt"), + "source_tree_sha256": _source_tree_sha256(project_root), + "runtime_environment": _runtime_environment(), + "nyc_full_evidence": nyc_full_lineage, + "treatment_version_policy_evidence": treatment_version_policy_lineage, + "interference_benchmark_evidence": { + "summary_sha256": sha256_file(interference_outputs["summary"]), + "manifest_sha256": sha256_file(interference_outputs["manifest"]), + }, + "nyc_simulation_anchor_evidence": ( + { + "anchor_sha256": sha256_file(nyc_anchor_outputs["anchor"]), + "manifest_sha256": sha256_file(nyc_anchor_outputs["manifest"]), + } + if nyc_anchor_outputs + else None + ), + "nyc_informed_benchmark_evidence": ( + { + "manifest_sha256": sha256_file( + nyc_benchmark_outputs["manifest"] + ), + "summary_sha256": sha256_file(nyc_benchmark_outputs["summary"]), + } + if nyc_benchmark_outputs + else None + ), + "nyc_graph_benchmark_evidence": ( + { + "manifest_sha256": sha256_file(nyc_graph_outputs["manifest"]), + "summary_sha256": sha256_file(nyc_graph_outputs["summary"]), + } + if nyc_graph_outputs + else None + ), + "equilibrium_benchmark_evidence": { + "manifest_sha256": sha256_file(equilibrium_outputs["manifest"]), + "summary_sha256": sha256_file(equilibrium_outputs["summary"]), + }, + "nyc_weather_evidence": ( + { + "manifest_sha256": sha256_file(nyc_weather_outputs["manifest"]), + "summary_sha256": sha256_file(nyc_weather_outputs["summary"]), + } + if nyc_weather_outputs + else None + ), + "nyc_events_evidence": ( + { + "manifest_sha256": sha256_file(nyc_events_outputs["manifest"]), + "summary_sha256": sha256_file(nyc_events_outputs["summary"]), + } + if nyc_events_outputs + else None + ), + "nyc_income_evidence": ( + { + "manifest_sha256": sha256_file(nyc_income_outputs["manifest"]), + "summary_sha256": sha256_file(nyc_income_outputs["summary"]), + } + if nyc_income_outputs + else None + ), + }, + ) + outputs.append(manifest) + return outputs + + +def _run_reproduce(args: argparse.Namespace) -> list[Path]: + """Publish a complete run only after every stage and final manifest succeed. + + Artifacts are still written incrementally so the workflow remains portable on a + laptop, but an old completion manifest is invalidated before the first write. + Consumers fail closed while the marker exists, and a failed run deliberately + leaves that marker behind for diagnosis. + """ + + data_config = load_data_config(args.config) + if data_config.mode != "sample": + raise ValueError( + "reproduce-sample requires a bounded mode: sample data config; " + "full-data ingestion is a separate explicit operation" + ) + output_root = Path(args.output_root) + output_root.mkdir(parents=True, exist_ok=True) + completion_manifest = output_root / "reproduce_manifest.json" + incomplete_marker = output_root / "REPRODUCE_INCOMPLETE.json" + completion_manifest.unlink(missing_ok=True) + started_at = datetime.now(UTC).isoformat() + _write_json( + { + "status": "incomplete", + "started_at_utc": started_at, + "message": ( + "This marker is removed only after every requested artifact and the " + "hash manifest have been written successfully." + ), + "configs": { + "data": str(args.config), + "simulation": str(args.simulation_config), + "benchmark": str(args.benchmark_config), + "policy": str(args.policy_config), + }, + }, + incomplete_marker, + ) + outputs = _run_reproduce_inner(args) + if not completion_manifest.is_file(): + raise RuntimeError("reproduction completed without a final hash manifest") + incomplete_marker.unlink(missing_ok=True) + return outputs + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="casuallab", + description="Reproducible causal marketplace experiment laboratory", + ) + subparsers = parser.add_subparsers(dest="command", required=True) + + download = subparsers.add_parser( + "download-sample", help="materialize a bounded configured raw sample" + ) + download.add_argument("--config", default="configs/sample.yaml") + download.add_argument("--refresh", action="store_true") + download.set_defaults(handler=_run_download_sample) + + panel = subparsers.add_parser("build-panel", help="build clean trip and market panels") + panel.add_argument("--config", default="configs/sample.yaml") + panel.add_argument("--refresh", action="store_true") + panel.add_argument( + "--allow-full-download", + action="store_true", + help="explicitly permit an unbounded full-data download", + ) + panel.set_defaults(handler=_run_build_panel) + + full_validation = subparsers.add_parser( + "validate-nyc-full", + help=( + "stream, validate, describe, and build calibration/network inputs for " + "one full NYC HVFHV month" + ), + ) + full_validation.add_argument("--config", default="configs/full.yaml") + full_validation.add_argument("--output-dir", default="artifacts/nyc_full") + full_validation.add_argument("--refresh", action="store_true") + full_validation.add_argument( + "--allow-full-download", + action="store_true", + help="explicitly permit the configured full-month data operation", + ) + full_validation.set_defaults(handler=_run_validate_nyc_full) + + simulation = subparsers.add_parser("simulate", help="run the structural simulator") + simulation.add_argument("--config", default="configs/simulation.yaml") + simulation.add_argument("--output-dir", default="artifacts/simulation") + simulation.set_defaults(handler=_run_simulate) + + benchmark = subparsers.add_parser("benchmark", help="run Monte Carlo design comparisons") + benchmark.add_argument("--config", default="configs/benchmark.yaml") + benchmark.add_argument("--simulation-config", default="configs/simulation.yaml") + benchmark.add_argument("--output-dir", default="artifacts/benchmarks") + benchmark.set_defaults(handler=_run_benchmark) + + interference = subparsers.add_parser( + "interference-benchmark", + help="run the known-truth two-stage saturation exposure benchmark", + ) + interference.add_argument("--replications", type=int, default=24) + interference.add_argument("--seed", type=int, default=880321) + interference.add_argument("--output-dir", default="artifacts/benchmarks") + interference.set_defaults(handler=_run_interference_benchmark) + + nyc_anchor = subparsers.add_parser( + "nyc-simulation-anchor", + help="build a validated semi-synthetic anchor from the NYC full-month bundle", + ) + nyc_anchor.add_argument( + "--calibration", + default="artifacts/nyc_full/calibration_network/calibration.json", + ) + nyc_anchor.add_argument( + "--calibration-manifest", + default="artifacts/nyc_full/calibration_network/manifest.json", + ) + nyc_anchor.add_argument("--simulation-config", default="configs/simulation.yaml") + nyc_anchor.add_argument("--n-zones", type=int, default=32) + nyc_anchor.add_argument("--n-periods", type=int, default=168) + nyc_anchor.add_argument("--seed", type=int, default=202503) + nyc_anchor.add_argument( + "--output-dir", default="artifacts/nyc_full/simulation_anchor" + ) + nyc_anchor.set_defaults(handler=_run_nyc_simulation_anchor) + + nyc_weather = subparsers.add_parser( + "nyc-weather", + help=( + "validate pinned NOAA Central Park weather and compute descriptive " + "full-month NYC associations" + ), + ) + nyc_weather.add_argument( + "--raw", + default="data/nyc_weather/raw/noaa_central_park_2024-01.csv", + ) + nyc_weather.add_argument( + "--panel-dir", + default="data/nyc_full/panel/zone_time", + ) + nyc_weather.add_argument( + "--data-manifest", + default="data/nyc_full/manifest.json", + ) + nyc_weather.add_argument( + "--output-dir", + default="artifacts/nyc_full/weather", + ) + nyc_weather.add_argument( + "--refresh", + action="store_true", + help="redownload the pinned NOAA response before validation", + ) + nyc_weather.set_defaults(handler=_run_nyc_weather) + + nyc_events = subparsers.add_parser( + "nyc-events", + help="validate official calendars and describe NYC permitted-event associations", + ) + nyc_events.add_argument( + "--holidays", + default="data/nyc_events/raw/official_holidays_2024-01.csv", + ) + nyc_events.add_argument( + "--events", + default="data/nyc_events/raw/nyc_permitted_events_overlap_2024-01.csv", + ) + nyc_events.add_argument("--panel-dir", default="data/nyc_full/panel/zone_time") + nyc_events.add_argument("--data-manifest", default="data/nyc_full/manifest.json") + nyc_events.add_argument("--output-dir", default="artifacts/nyc_full/events") + nyc_events.add_argument( + "--refresh", + action="store_true", + help="redownload the pinned NYC permitted-events response before validation", + ) + nyc_events.set_defaults(handler=_run_nyc_events) + + nyc_income = subparsers.add_parser( + "nyc-income", + help="build ecological NYC Taxi Zone income descriptions from pinned sources", + ) + nyc_income.add_argument( + "--taxi-zones", default="data/nyc_income/raw/taxi_zones.zip" + ) + nyc_income.add_argument( + "--nta", default="data/nyc_income/raw/nyc_nta2020.geojson" + ) + nyc_income.add_argument( + "--tract-to-nta", + default="data/nyc_income/raw/nyc_tract2020_to_nta2020.csv", + ) + nyc_income.add_argument( + "--acs-b19001", + default="data/nyc_income/raw/acs_2022_5yr_b19001_nyc_tracts.dat", + ) + nyc_income.add_argument("--panel-dir", default="data/nyc_full/panel/zone_time") + nyc_income.add_argument("--data-manifest", default="data/nyc_full/manifest.json") + nyc_income.add_argument("--output-dir", default="artifacts/nyc_full/income") + nyc_income.set_defaults(handler=_run_nyc_income) + + nyc_benchmark = subparsers.add_parser( + "nyc-benchmark", + help="run a known-truth benchmark initialized from the validated NYC anchor", + ) + nyc_benchmark.add_argument( + "--anchor", + default="artifacts/nyc_full/simulation_anchor/nyc_simulation_anchor.json", + ) + nyc_benchmark.add_argument( + "--anchor-manifest", + default="artifacts/nyc_full/simulation_anchor/manifest.json", + ) + nyc_benchmark.add_argument("--replications", type=int, default=6) + nyc_benchmark.add_argument("--seed", type=int, default=870221) + nyc_benchmark.add_argument("--n-zones", type=int, default=16) + nyc_benchmark.add_argument("--n-periods", type=int, default=48) + nyc_benchmark.add_argument( + "--output-dir", default="artifacts/benchmarks/nyc_informed" + ) + nyc_benchmark.set_defaults(handler=_run_nyc_benchmark) + + nyc_graph = subparsers.add_parser( + "nyc-graph-benchmark", + help="run a known-truth exposure benchmark on the validated NYC OD graph", + ) + nyc_graph.add_argument( + "--bundle", + default="artifacts/nyc_full/calibration_network", + ) + nyc_graph.add_argument("--replications", type=int, default=12) + nyc_graph.add_argument("--seed", type=int, default=912731) + nyc_graph.add_argument("--n-zones", type=int, default=16) + nyc_graph.add_argument("--n-periods", type=int, default=24) + nyc_graph.add_argument( + "--output-dir", default="artifacts/benchmarks/nyc_graph" + ) + nyc_graph.set_defaults(handler=_run_nyc_graph_benchmark) + + equilibrium = subparsers.add_parser( + "equilibrium-benchmark", + help="solve a theoretical two-sided fixed-point equilibrium benchmark", + ) + equilibrium.add_argument("--n-zones", type=int, default=2) + equilibrium.add_argument("--seed", type=int, default=202503) + equilibrium.add_argument( + "--treatment-version", + choices=("rider_discount", "driver_incentive", "bundled"), + default="bundled", + ) + equilibrium.add_argument("--budget", type=float) + equilibrium.add_argument("--treatment-intensity", type=float, default=1.0) + equilibrium.add_argument( + "--output-dir", default="artifacts/benchmarks/equilibrium" + ) + equilibrium.set_defaults(handler=_run_equilibrium_benchmark) + + report = subparsers.add_parser("report", help="generate reports from computed artifacts") + report.add_argument("--benchmark", default="artifacts/benchmarks/benchmark_results.csv") + report.add_argument("--policy", default="artifacts/benchmarks/policy_results.csv") + report.add_argument("--output-dir", default="artifacts/reports") + report.add_argument( + "--descriptive", + default="artifacts/reports/descriptive/descriptive_moments.json", + ) + report.add_argument("--calibration", default="artifacts/reports/calibration.json") + report.add_argument("--failures", default="artifacts/benchmarks/benchmark_failures.csv") + report.add_argument( + "--hte-summary", + default="artifacts/benchmarks/heterogeneity/hte_recovery.json", + ) + report.add_argument( + "--hte-calibration", + default="artifacts/benchmarks/heterogeneity/hte_calibration_by_score.csv", + ) + report.add_argument( + "--hte-stability", + default="artifacts/benchmarks/heterogeneity/hte_fold_stability.csv", + ) + report.add_argument( + "--nyc-full-validation", + default="artifacts/nyc_full/validation.json", + help="optional verified NYC full-month validation artifact", + ) + report.add_argument( + "--nyc-full-manifest", + default="artifacts/nyc_full/manifest.json", + help="lineage manifest paired with --nyc-full-validation", + ) + report.add_argument( + "--treatment-version-policy", + default="artifacts/benchmarks/treatment_version_policy_results.csv", + help="optional rider/driver/bundled policy sensitivity summary", + ) + report.add_argument( + "--treatment-version-policy-manifest", + default="artifacts/benchmarks/treatment_version_policy_manifest.json", + help="lineage manifest paired with --treatment-version-policy", + ) + report.add_argument( + "--interference-summary", + default="artifacts/benchmarks/interference_summary.csv", + help="optional known-truth mapped-exposure benchmark summary", + ) + report.add_argument( + "--interference-manifest", + default="artifacts/benchmarks/interference_manifest.json", + help="lineage manifest paired with --interference-summary", + ) + report.add_argument( + "--nyc-simulation-anchor", + default="artifacts/nyc_full/simulation_anchor/nyc_simulation_anchor.json", + help="optional validated NYC descriptive simulator anchor", + ) + report.add_argument( + "--nyc-simulation-anchor-manifest", + default="artifacts/nyc_full/simulation_anchor/manifest.json", + help="lineage manifest paired with --nyc-simulation-anchor", + ) + report.add_argument( + "--nyc-benchmark-manifest", + default="artifacts/benchmarks/nyc_informed/manifest.json", + help="optional NYC-informed known-truth benchmark manifest", + ) + report.add_argument( + "--nyc-graph-benchmark-manifest", + default="artifacts/benchmarks/nyc_graph/manifest.json", + help="optional NYC OD-graph known-truth benchmark manifest", + ) + report.add_argument( + "--equilibrium-manifest", + default="artifacts/benchmarks/equilibrium/manifest.json", + help="optional theoretical fixed-point equilibrium benchmark manifest", + ) + report.add_argument( + "--nyc-weather-manifest", + default="artifacts/nyc_full/weather/manifest.json", + help="optional descriptive NOAA weather association manifest", + ) + report.add_argument( + "--nyc-events-manifest", + default="artifacts/nyc_full/events/manifest.json", + help="optional descriptive official-calendar/permitted-event manifest", + ) + report.add_argument( + "--nyc-income-manifest", + default="artifacts/nyc_full/income/manifest.json", + help="optional ecological NYC neighborhood-income manifest", + ) + report.add_argument("--target-estimand") + report.set_defaults(handler=_run_report) + + reproduce = subparsers.add_parser( + "reproduce-sample", + help="rebuild the complete offline vertical slice", + ) + reproduce.add_argument("--config", default="configs/sample.yaml") + reproduce.add_argument("--simulation-config", default="configs/simulation.yaml") + reproduce.add_argument("--benchmark-config", default="configs/benchmark.yaml") + reproduce.add_argument("--policy-config", default="configs/policy.yaml") + reproduce.add_argument("--output-root", default="artifacts") + reproduce.add_argument( + "--nyc-full-validation", + default="artifacts/nyc_full/validation.json", + help="reuse an already-validated NYC full month without downloading it", + ) + reproduce.add_argument( + "--nyc-full-manifest", + default="artifacts/nyc_full/manifest.json", + help="lineage manifest paired with --nyc-full-validation", + ) + reproduce.add_argument("--refresh", action="store_true") + reproduce.set_defaults(handler=_run_reproduce) + return parser + + +def main(argv: Sequence[str] | None = None) -> int: + parser = build_parser() + args = parser.parse_args(argv) + paths = args.handler(args) + for path in paths: + print(path) + return 0 diff --git a/CasualLab/src/casuallab/config.py b/CasualLab/src/casuallab/config.py new file mode 100644 index 0000000000000000000000000000000000000000..1ec75788ad482533c3c5ebc389d790fcb3d3befe --- /dev/null +++ b/CasualLab/src/casuallab/config.py @@ -0,0 +1,415 @@ +"""Typed, serializable configuration for the causal marketplace lab. + +The configuration objects intentionally contain assumptions, not results. They can +be created directly in Python or loaded from YAML without requiring a global config +singleton, which keeps simulations and Monte Carlo runs reproducible. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import asdict, dataclass, field, fields +from enum import Enum, StrEnum +from math import isfinite +from numbers import Integral, Real +from pathlib import Path +from typing import Any, ClassVar, Self, get_type_hints + +import yaml + + +class DesignName(StrEnum): + """Supported assignment mechanisms.""" + + INDIVIDUAL = "individual" + GEO_CLUSTER = "geo_cluster" + TIME_BLOCK = "time_block" + SWITCHBACK = "switchback" + GEO_TIME = "geo_time" + + @classmethod + def parse(cls, value: str | DesignName) -> DesignName: + if isinstance(value, cls): + return value + normalized = str(value).strip().lower().replace("-", "_").replace(" ", "_") + aliases = { + "geo": cls.GEO_CLUSTER.value, + "geographic": cls.GEO_CLUSTER.value, + "geographic_cluster": cls.GEO_CLUSTER.value, + "cluster": cls.GEO_CLUSTER.value, + "time": cls.TIME_BLOCK.value, + "temporal": cls.TIME_BLOCK.value, + "geo_x_time": cls.GEO_TIME.value, + "geo_by_time": cls.GEO_TIME.value, + "geotime": cls.GEO_TIME.value, + "geo_time_clustered": cls.GEO_TIME.value, + } + try: + return cls(aliases.get(normalized, normalized)) + except ValueError as exc: + choices = ", ".join(member.value for member in cls) + raise ValueError(f"unknown design {value!r}; choose one of: {choices}") from exc + + +class TreatmentVersion(StrEnum): + """Supported marketplace intervention versions.""" + + RIDER_DISCOUNT = "rider_discount" + DRIVER_INCENTIVE = "driver_incentive" + BUNDLED = "bundled" + + @classmethod + def parse(cls, value: str | TreatmentVersion) -> TreatmentVersion: + if isinstance(value, cls): + return value + normalized = str(value).strip().lower().replace("-", "_").replace(" ", "_") + aliases = { + "rider": cls.RIDER_DISCOUNT.value, + "discount": cls.RIDER_DISCOUNT.value, + "rider_only": cls.RIDER_DISCOUNT.value, + "driver": cls.DRIVER_INCENTIVE.value, + "incentive": cls.DRIVER_INCENTIVE.value, + "driver_only": cls.DRIVER_INCENTIVE.value, + "both": cls.BUNDLED.value, + "bundle": cls.BUNDLED.value, + } + try: + return cls(aliases.get(normalized, normalized)) + except ValueError as exc: + choices = ", ".join(member.value for member in cls) + raise ValueError( + f"unknown treatment version {value!r}; choose one of: {choices}" + ) from exc + + +class _ConfigMixin: + """Small dataclass serialization helper used by all public configs.""" + + _ALIASES: ClassVar[Mapping[str, str]] = {} + + @classmethod + def from_dict(cls, values: Mapping[str, Any]) -> Self: + if not isinstance(values, Mapping): + raise TypeError(f"{cls.__name__}.from_dict expects a mapping") + known = {item.name for item in fields(cls) if item.init} + normalized: dict[str, Any] = {} + for raw_key, value in values.items(): + key = cls._ALIASES.get(str(raw_key), str(raw_key)) + if key not in known: + raise ValueError(f"unknown {cls.__name__} field: {raw_key!r}") + normalized[key] = value + + hints = get_type_hints(cls) + if "design" in normalized and isinstance(normalized["design"], Mapping): + normalized["design"] = DesignConfig.from_dict(normalized["design"]) + if "name" in normalized and hints.get("name") in {DesignName, "DesignName"}: + normalized["name"] = DesignName.parse(normalized["name"]) + if "treatment_version" in normalized: + normalized["treatment_version"] = TreatmentVersion.parse( + normalized["treatment_version"] + ) + if "covariates" in normalized and isinstance(normalized["covariates"], list): + normalized["covariates"] = tuple(str(item) for item in normalized["covariates"]) + return cls(**normalized) + + @classmethod + def from_yaml(cls, path: str | Path, *, section: str | None = None) -> Self: + source = Path(path) + payload = yaml.safe_load(source.read_text(encoding="utf-8")) or {} + if not isinstance(payload, Mapping): + raise ValueError(f"YAML root in {source} must be a mapping") + if section is not None: + try: + payload = payload[section] + except KeyError as exc: + raise ValueError(f"YAML file {source} has no {section!r} section") from exc + if not isinstance(payload, Mapping): + raise ValueError(f"YAML section {section!r} must be a mapping") + return cls.from_dict(payload) + + def to_dict(self) -> dict[str, Any]: + payload = asdict(self) + for key, value in tuple(payload.items()): + if isinstance(value, Enum): + payload[key] = value.value + if isinstance(payload.get("design"), dict): + name = payload["design"].get("name") + if isinstance(name, Enum): + payload["design"]["name"] = name.value + return payload + + +@dataclass(frozen=True, slots=True) +class DesignConfig(_ConfigMixin): + """Assignment settings shared by design generators and the simulator. + + ``treatment_probability`` controls assignment to the treatment arm. + ``treatment_saturation`` controls the exposure intensity inside treated arms. + They are separate so partial-saturation experiments remain explicit. + """ + + name: DesignName = DesignName.GEO_CLUSTER + treatment_probability: float = 0.5 + treatment_saturation: float = 1.0 + n_clusters: int | None = None + cluster_size: int = 1 + treatment_duration: int = 4 + washout_periods: int = 0 + budget: float | None = None + seed: int | None = None + + _ALIASES: ClassVar[Mapping[str, str]] = { + "design": "name", + "design_name": "name", + "randomization_unit": "name", + "probability": "treatment_probability", + "treatment_share": "treatment_probability", + "saturation": "treatment_saturation", + "block_length": "treatment_duration", + "washout": "washout_periods", + } + + def __post_init__(self) -> None: + object.__setattr__(self, "name", DesignName.parse(self.name)) + numeric_values = { + "treatment_probability": self.treatment_probability, + "treatment_saturation": self.treatment_saturation, + } + if self.budget is not None: + numeric_values["budget"] = self.budget + for name, value in numeric_values.items(): + if not isinstance(value, Real) or not isfinite(float(value)): + raise ValueError(f"{name} must be a finite number") + integer_values = { + "cluster_size": self.cluster_size, + "treatment_duration": self.treatment_duration, + "washout_periods": self.washout_periods, + } + if self.n_clusters is not None: + integer_values["n_clusters"] = self.n_clusters + if self.seed is not None: + integer_values["seed"] = self.seed + for name, value in integer_values.items(): + if isinstance(value, bool) or not isinstance(value, Integral): + raise ValueError(f"{name} must be an integer") + if not 0 < self.treatment_probability < 1: + raise ValueError("treatment_probability must be strictly between 0 and 1") + if not 0 <= self.treatment_saturation <= 1: + raise ValueError("treatment_saturation must lie in [0, 1]") + if self.n_clusters is not None and self.n_clusters < 1: + raise ValueError("n_clusters must be positive when supplied") + if self.cluster_size < 1: + raise ValueError("cluster_size must be positive") + if self.treatment_duration < 1: + raise ValueError("treatment_duration must be positive") + if self.washout_periods < 0: + raise ValueError("washout_periods cannot be negative") + if self.washout_periods >= self.treatment_duration: + raise ValueError("washout_periods must be shorter than treatment_duration") + if self.budget is not None and self.budget < 0: + raise ValueError("budget cannot be negative") + + +@dataclass(frozen=True, slots=True) +class SimulationConfig(_ConfigMixin): + """Structural assumptions for a deterministic semi-synthetic market. + + Effects are log changes in latent demand or available supply. Monetary fields + are expressed in arbitrary but internally consistent currency units. The model + is deliberately compact enough for a laptop while retaining congestion, + cross-zone movement, temporal persistence, and a binding-spend mechanism. + A common assignment intensity scales the selected treatment version: rider + discount, driver incentive, or their bundle. This makes the intervention version + explicit while retaining a single binary/partial-saturation arm per experiment. + """ + + n_zones: int = 4 + n_periods: int = 48 + periods_per_day: int = 24 + individuals_per_cell: int = 100 + base_demand: float = 80.0 + base_supply: float = 62.0 + capacity_per_driver: float = 1.35 + matching_efficiency: float = 0.94 + base_fare: float = 18.0 + rider_value: float = 28.0 + operating_cost_per_trip: float = 8.0 + base_wait_minutes: float = 5.0 + wait_disutility_per_minute: float = 0.25 + treatment_version: TreatmentVersion = TreatmentVersion.BUNDLED + discount_rate: float = 0.10 + incentive_per_driver: float = 1.50 + reference_incentive_per_driver: float = 1.50 + direct_demand_effect: float = 0.16 + direct_supply_effect: float = 0.10 + spillover_strength: float = 0.0 + persistence: float = 0.0 + rider_substitution: float = 0.04 + driver_mobility: float = 0.06 + zone_heterogeneity_sd: float = 0.12 + demand_noise_sd: float = 0.06 + supply_noise_sd: float = 0.05 + time_pattern_strength: float = 0.22 + budget: float | None = None + seed: int = 202503 + design: DesignConfig = field(default_factory=DesignConfig) + + _ALIASES: ClassVar[Mapping[str, str]] = { + "zones": "n_zones", + "periods": "n_periods", + "n_times": "n_periods", + "riders_per_cell": "individuals_per_cell", + "driver_incentive": "incentive_per_driver", + "incentive": "incentive_per_driver", + "discount": "discount_rate", + "demand_effect": "direct_demand_effect", + "supply_effect": "direct_supply_effect", + "interference": "spillover_strength", + "persistence_rate": "persistence", + "driver_movement": "driver_mobility", + "random_seed": "seed", + } + + def __post_init__(self) -> None: + if isinstance(self.design, Mapping): + object.__setattr__(self, "design", DesignConfig.from_dict(self.design)) + object.__setattr__( + self, + "treatment_version", + TreatmentVersion.parse(self.treatment_version), + ) + positive_ints = { + "n_zones": self.n_zones, + "n_periods": self.n_periods, + "periods_per_day": self.periods_per_day, + "individuals_per_cell": self.individuals_per_cell, + } + for name, value in positive_ints.items(): + if isinstance(value, bool) or not isinstance(value, Integral): + raise ValueError(f"{name} must be an integer") + if value < 1: + raise ValueError(f"{name} must be positive") + if isinstance(self.seed, bool) or not isinstance(self.seed, Integral): + raise ValueError("seed must be an integer") + numeric_values = { + item.name: getattr(self, item.name) + for item in fields(self) + if item.init + and item.name not in {*positive_ints, "seed", "design", "treatment_version"} + } + for name, value in numeric_values.items(): + if value is not None and ( + not isinstance(value, Real) or not isfinite(float(value)) + ): + raise ValueError(f"{name} must be a finite number") + positive = { + "base_demand": self.base_demand, + "base_supply": self.base_supply, + "capacity_per_driver": self.capacity_per_driver, + "matching_efficiency": self.matching_efficiency, + "base_fare": self.base_fare, + "rider_value": self.rider_value, + "base_wait_minutes": self.base_wait_minutes, + "reference_incentive_per_driver": self.reference_incentive_per_driver, + } + for name, value in positive.items(): + if value <= 0: + raise ValueError(f"{name} must be positive") + nonnegative = { + "operating_cost_per_trip": self.operating_cost_per_trip, + "wait_disutility_per_minute": self.wait_disutility_per_minute, + "incentive_per_driver": self.incentive_per_driver, + "spillover_strength": self.spillover_strength, + "persistence": self.persistence, + "rider_substitution": self.rider_substitution, + "driver_mobility": self.driver_mobility, + "zone_heterogeneity_sd": self.zone_heterogeneity_sd, + "demand_noise_sd": self.demand_noise_sd, + "supply_noise_sd": self.supply_noise_sd, + "time_pattern_strength": self.time_pattern_strength, + } + for name, value in nonnegative.items(): + if value < 0: + raise ValueError(f"{name} cannot be negative") + if not 0 < self.matching_efficiency <= 1: + raise ValueError("matching_efficiency must lie in (0, 1]") + if not 0 <= self.discount_rate <= 1: + raise ValueError("discount_rate must lie in [0, 1]") + if not 0 <= self.persistence < 1: + raise ValueError("persistence must lie in [0, 1)") + if self.budget is not None and self.budget < 0: + raise ValueError("budget cannot be negative") + + @property + def effective_budget(self) -> float | None: + """Simulation-level budget takes precedence over the design budget.""" + + return self.budget if self.budget is not None else self.design.budget + + +# Common names retained as explicit aliases for a compact public API. +MarketConfig = SimulationConfig +SimulatorConfig = SimulationConfig + + +@dataclass(frozen=True, slots=True) +class EstimatorConfig(_ConfigMixin): + """Configuration for the transparent estimator dispatcher.""" + + method: str = "difference_in_means" + outcome: str = "outcome" + treatment: str = "assigned_treatment" + covariates: tuple[str, ...] = () + cluster: str | None = None + unit: str | None = None + time: str | None = None + post: str | None = None + propensity: str | None = None + target_estimand: str = "intent_to_treat" + alpha: float = 0.05 + filter_eligible: bool = True + crossfit_folds: int = 2 + seed: int = 202503 + + _ALIASES: ClassVar[Mapping[str, str]] = { + "estimator": "method", + "outcome_col": "outcome", + "treatment_col": "treatment", + "cluster_col": "cluster", + "unit_col": "unit", + "time_col": "time", + "post_col": "post", + "estimand": "target_estimand", + } + + def __post_init__(self) -> None: + object.__setattr__(self, "covariates", tuple(self.covariates)) + if not isinstance(self.alpha, Real) or not isfinite(float(self.alpha)): + raise ValueError("alpha must be a finite number") + for name, value in {"crossfit_folds": self.crossfit_folds, "seed": self.seed}.items(): + if isinstance(value, bool) or not isinstance(value, Integral): + raise ValueError(f"{name} must be an integer") + if not self.method.strip(): + raise ValueError("method cannot be empty") + if not self.outcome or not self.treatment: + raise ValueError("outcome and treatment column names are required") + if not 0 < self.alpha < 1: + raise ValueError("alpha must lie in (0, 1)") + if self.crossfit_folds < 2: + raise ValueError("crossfit_folds must be at least 2") + + +def load_simulation_config(path: str | Path, *, section: str | None = None) -> SimulationConfig: + """Load a simulation config, accepting a conventional ``simulation`` section.""" + + source = Path(path) + payload = yaml.safe_load(source.read_text(encoding="utf-8")) or {} + if not isinstance(payload, Mapping): + raise ValueError(f"YAML root in {source} must be a mapping") + if section is not None: + payload = payload.get(section, {}) + elif "simulation" in payload: + payload = payload["simulation"] + if not isinstance(payload, Mapping): + raise ValueError("simulation configuration must be a mapping") + return SimulationConfig.from_dict(payload) diff --git a/CasualLab/src/casuallab/dashboard.py b/CasualLab/src/casuallab/dashboard.py new file mode 100644 index 0000000000000000000000000000000000000000..1562996e5aee4b0f512cc15754cfc0e6e3f74705 --- /dev/null +++ b/CasualLab/src/casuallab/dashboard.py @@ -0,0 +1,2698 @@ +"""Interactive experiment-design decision interface. + +The Streamlit renderer in this module is deliberately thin. Configuration, +simulation, benchmark matching, and recommendation logic are ordinary Python +functions so they can be tested without starting a web server. Every numerical +quantity shown by the app is either read from a provenance-labelled benchmark +artifact or generated on demand by the semi-synthetic simulator. +""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, replace +from functools import lru_cache +from pathlib import Path +from typing import Any, Final + +import numpy as np +import pandas as pd + +from casuallab.config import ( + DesignConfig, + DesignName, + EstimatorConfig, + SimulationConfig, + TreatmentVersion, +) +from casuallab.estimands import EstimandName, get_estimand, identification_assessment +from casuallab.reporting import choose_recommendation, design_limitations +from casuallab.simulator import SimulationResult, simulate_market + +TARGET_ESTIMAND: Final[str] = EstimandName.MARKET_TOTAL.value +SUPPORTED_DESIGNS: Final[tuple[str, ...]] = tuple(member.value for member in DesignName) +DESIGN_LABELS: Final[Mapping[str, str]] = { + DesignName.INDIVIDUAL.value: "Individual assignment", + DesignName.GEO_CLUSTER.value: "Geographic clusters", + DesignName.TIME_BLOCK.value: "Marketplace time blocks", + DesignName.SWITCHBACK.value: "Marketplace switchback", + DesignName.GEO_TIME.value: "Geo × time clusters", +} +TREATMENT_VERSION_LABELS: Final[Mapping[str, str]] = { + TreatmentVersion.RIDER_DISCOUNT.value: "Rider discount only", + TreatmentVersion.DRIVER_INCENTIVE.value: "Driver incentive only", + TreatmentVersion.BUNDLED.value: "Bundled rider + driver treatment", +} +CALIBRATION_EVIDENCE_TYPES: Final[frozenset[str]] = frozenset( + { + "empirical_association_for_semisynthetic_calibration", + "illustrative_empirical_scale_anchor", + } +) + + +@dataclass(frozen=True, slots=True) +class DashboardControls: + """User-editable assumptions for one decision scenario. + + ``experiment_duration`` is the full evaluation horizon, while + ``treatment_duration`` is the assignment-block length used by temporal designs. + Geographic scenarios use two zones per requested cluster so that the number of + independent assignment groups is explicit without adding another UI control. + """ + + randomization_unit: str = DesignName.GEO_CLUSTER.value + treatment_version: str = TreatmentVersion.BUNDLED.value + experiment_duration: int = 48 + # These defaults deliberately match the precomputed ``cluster_count_variant`` + # benchmark cell. The dashboard therefore opens with auditable recovery + # evidence instead of an arbitrary scenario for which no Monte Carlo artifact + # exists; every control remains editable. + n_clusters: int = 8 + spillover_strength: float = 0.0 + persistence: float = 0.0 + incentive_size: float = 1.50 + budget: float = 10_000.0 + treatment_duration: int = 4 + washout_periods: int = 0 + treatment_saturation: float = 1.0 + treatment_probability: float = 0.5 + replications: int = 5 + seed: int = 202_503 + target_estimand: str = TARGET_ESTIMAND + + def __post_init__(self) -> None: + design = DesignName.parse(self.randomization_unit).value + target = EstimandName.parse(self.target_estimand).value + treatment_version = TreatmentVersion.parse(self.treatment_version).value + object.__setattr__(self, "randomization_unit", design) + object.__setattr__(self, "target_estimand", target) + object.__setattr__(self, "treatment_version", treatment_version) + if target != TARGET_ESTIMAND: + raise ValueError( + "the dashboard benchmark currently targets market_total_effect; " + "other structural truths remain available through casuallab.estimands" + ) + if self.experiment_duration < 4: + raise ValueError("experiment_duration must be at least 4 periods") + if self.n_clusters < 2: + raise ValueError("n_clusters must be at least 2") + if self.treatment_duration < 1: + raise ValueError("treatment_duration must be positive") + if self.treatment_duration * 2 > self.experiment_duration: + raise ValueError("experiment_duration must contain at least two treatment blocks") + if not 0 <= self.washout_periods < self.treatment_duration: + raise ValueError("washout_periods must be shorter than treatment_duration") + if not 0 <= self.spillover_strength <= 1: + raise ValueError("spillover_strength must lie in [0, 1]") + if not 0 <= self.persistence < 1: + raise ValueError("persistence must lie in [0, 1)") + if self.incentive_size < 0: + raise ValueError("incentive_size cannot be negative") + if self.budget < 0: + raise ValueError("budget cannot be negative") + if not 0 < self.treatment_saturation <= 1: + raise ValueError("treatment_saturation must lie in (0, 1]") + if not 0 < self.treatment_probability < 1: + raise ValueError("treatment_probability must lie in (0, 1)") + if self.replications < 2: + raise ValueError("replications must be at least 2") + + +@dataclass(frozen=True) +class ScenarioBenchmark: + """On-demand structural outcomes and assignment-contrast diagnostics.""" + + controls: DashboardControls + records: pd.DataFrame + summary: pd.DataFrame + limitations: tuple[str, ...] + calibration_path: Path | None = None + calibration_sha256: str | None = None + evidence_type: str = "semi_synthetic_structural_scenario" + + @property + def selected(self) -> pd.Series: + rows = self.summary.loc[self.summary["design"] == self.controls.randomization_unit] + if len(rows) != 1: + raise ValueError("scenario summary must contain one row for the selected design") + return rows.iloc[0] + + +@dataclass(frozen=True) +class BenchmarkArtifact: + """A validated generated benchmark and its file provenance.""" + + path: Path + summary: pd.DataFrame + declared_scenarios: tuple[str, ...] + lineage_validated: bool = False + + +@dataclass(frozen=True) +class ArtifactDecision: + """Artifact rows matched on available fields and an identification-safe choice.""" + + rows: pd.DataFrame + recommendation: pd.Series + missing_dimensions: tuple[str, ...] + recommendation_scope: str + matched_scenarios: tuple[str, ...] + unmatched_scenarios: tuple[str, ...] + + +@dataclass(frozen=True) +class CalibrationTemplate: + """Validated descriptive calibration used as a simulation template.""" + + path: Path + config: SimulationConfig + sha256: str + evidence_type: str + + +@dataclass(frozen=True, slots=True) +class EvidenceLayerStatus: + """Read-only availability and interpretation of one lineage-verified evidence layer.""" + + key: str + title: str + classification: str + interpretation: str + available: bool + detail: str + manifest_path: Path | None = None + manifest_sha256: str | None = None + + +@dataclass(frozen=True, slots=True) +class _EvidenceLayerSpec: + key: str + title: str + relative_manifest: str + classification: str + interpretation: str + + +_EVIDENCE_LAYER_SPECS: Final[tuple[_EvidenceLayerSpec, ...]] = ( + _EvidenceLayerSpec( + key="nyc_informed", + title="NYC-informed marketplace benchmark", + relative_manifest="artifacts/benchmarks/nyc_informed/manifest.json", + classification="Semi-synthetic known truth", + interpretation=( + "NYC descriptive moments initialize the simulator; treatment effects are known " + "only inside the declared simulator and are not NYC causal estimates." + ), + ), + _EvidenceLayerSpec( + key="nyc_graph", + title="NYC OD-graph interference benchmark", + relative_manifest="artifacts/benchmarks/nyc_graph/manifest.json", + classification="Semi-synthetic known truth", + interpretation=( + "Observed NYC OD weights define exposure geometry only; spillover coefficients " + "and outcomes come from a declared known-truth DGP." + ), + ), + _EvidenceLayerSpec( + key="equilibrium", + title="Two-sided fixed-point equilibrium benchmark", + relative_manifest="artifacts/benchmarks/equilibrium/manifest.json", + classification="Theoretical equilibrium known truth", + interpretation=( + "A transparent theoretical fixed point under assumed parameters; explicitly not " + "an NYC structural estimate." + ), + ), + _EvidenceLayerSpec( + key="weather", + title="NYC observed weather enrichment", + relative_manifest="artifacts/nyc_full/weather/manifest.json", + classification="Descriptive observed data — non-causal", + interpretation=( + "Verified NOAA weather is joined to published NYC completed trips for descriptive " + "associations only; it does not identify a causal weather shock." + ), + ), + _EvidenceLayerSpec( + key="events", + title="NYC official-calendar and permitted-event enrichment", + relative_manifest="artifacts/nyc_full/events/manifest.json", + classification="Descriptive observed data — non-causal", + interpretation=( + "Official holiday dates and permitted-event windows define citywide daily " + "descriptors only. Permits are not attendance or zone/hour exposure, and " + "weekend composition confounds the raw contrast." + ), + ), + _EvidenceLayerSpec( + key="income", + title="NYC neighborhood-income heterogeneity", + relative_manifest="artifacts/nyc_full/income/manifest.json", + classification="Descriptive ecological data — non-causal", + interpretation=( + "Official geometry and ACS B19001 distributions describe Taxi Zone groups. " + "Area income is not rider or driver income and does not identify an income effect." + ), + ), +) + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def _source_tree_sha256(project_root: Path) -> str: + """Hash executable source/config inputs using the reproduction contract.""" + + digest = hashlib.sha256() + candidates = [ + *project_root.joinpath("src").rglob("*.py"), + *project_root.joinpath("configs").rglob("*.yaml"), + project_root / "pyproject.toml", + project_root / "constraints.txt", + project_root / "Makefile", + ] + for path in sorted({item for item in candidates if item.is_file()}): + digest.update(str(path.relative_to(project_root)).encode("utf-8")) + digest.update(b"\0") + digest.update(path.read_bytes()) + digest.update(b"\0") + return digest.hexdigest() + + +@lru_cache(maxsize=4) +def load_calibration_template( + path: str | Path | None = None, +) -> CalibrationTemplate | None: + """Load the generated descriptive calibration without treating it as causal evidence.""" + + source = ( + _project_root() / "artifacts" / "reports" / "calibration.json" + if path is None + else Path(path) + ) + if not source.is_file(): + return None + payload = json.loads(source.read_text(encoding="utf-8")) + if not isinstance(payload, Mapping): + raise ValueError("calibration artifact root must be a mapping") + evidence_type = str(payload.get("evidence_type", "")) + if evidence_type not in CALIBRATION_EVIDENCE_TYPES: + raise ValueError( + "calibration artifact must carry an approved descriptive scale-anchor label" + ) + raw_config = payload.get("simulation_config") + if not isinstance(raw_config, Mapping): + raise ValueError("calibration artifact has no simulation_config mapping") + return CalibrationTemplate( + path=source.resolve(), + config=SimulationConfig.from_dict(raw_config), + sha256=_sha256(source), + evidence_type=evidence_type, + ) + + +def build_simulation_config( + controls: DashboardControls, + *, + design: str | DesignName | None = None, + seed: int | None = None, + base_config: SimulationConfig | None = None, +) -> SimulationConfig: + """Translate inputs onto a calibrated template, or package defaults if absent.""" + + design_name = DesignName.parse(design or controls.randomization_unit) + simulation_seed = controls.seed if seed is None else int(seed) + if base_config is None: + calibration = load_calibration_template() + base_config = calibration.config if calibration is not None else SimulationConfig() + n_zones = max(4, controls.n_clusters * 2) + cluster_size = max(1, int(np.ceil(n_zones / controls.n_clusters))) + effective_washout = ( + controls.washout_periods + if design_name in {DesignName.TIME_BLOCK, DesignName.SWITCHBACK, DesignName.GEO_TIME} + else 0 + ) + design_config = DesignConfig( + name=design_name, + treatment_probability=controls.treatment_probability, + treatment_saturation=controls.treatment_saturation, + n_clusters=controls.n_clusters, + cluster_size=cluster_size, + treatment_duration=controls.treatment_duration, + washout_periods=effective_washout, + budget=controls.budget, + seed=simulation_seed + 1, + ) + return replace( + base_config, + n_zones=n_zones, + n_periods=controls.experiment_duration, + treatment_version=TreatmentVersion.parse(controls.treatment_version), + incentive_per_driver=controls.incentive_size, + spillover_strength=controls.spillover_strength, + persistence=controls.persistence, + budget=controls.budget, + seed=simulation_seed, + design=design_config, + ) + + +def _estimator_config(design: str, target_estimand: str, seed: int) -> EstimatorConfig: + """Use assignment-scale regression for individual saturation and clustered ITT otherwise.""" + + if design == DesignName.INDIVIDUAL.value: + return EstimatorConfig( + method="regression_adjustment", + outcome="outcome", + treatment="assigned_treatment", + covariates=( + "baseline_demand", + "baseline_supply", + "hour_sin", + "hour_cos", + ), + target_estimand=target_estimand, + seed=seed, + ) + return EstimatorConfig( + method="cluster_robust", + outcome="outcome", + treatment="assigned_treatment", + cluster="randomization_cluster", + target_estimand=target_estimand, + seed=seed, + ) + + +def _estimate_simulation( + result: SimulationResult, controls: DashboardControls +) -> Mapping[str, Any]: + """Return structural truth and a separate, target-mismatched assignment diagnostic.""" + + # Import lazily so reading configuration or benchmark artifacts does not require + # the estimation stack to initialize (and keeps dashboard import side-effect free). + from casuallab.estimators import estimate_effect + + design = str(result.metadata["design"]) + config = _estimator_config( + design, controls.target_estimand, int(result.metadata["simulation_seed"]) + ) + estimate = estimate_effect(result.panel, config) + full_policy_effect = result.ground_truth.get(controls.target_estimand) + if full_policy_effect is None or not np.isfinite(full_policy_effect): + raise ValueError(f"simulator did not produce finite truth for {controls.target_estimand!r}") + standard_error = float(estimate.standard_error) + if not np.isfinite(standard_error) or standard_error <= 0: + raise ValueError( + f"{estimate.method} produced invalid uncertainty for {design}; " + "increase clusters or experiment duration" + ) + + incremental = float(result.ground_truth["incremental_trips"]) + incremental_welfare = float(result.ground_truth["incremental_welfare"]) + full_policy_spend = float(result.ground_truth["full_policy_spend"]) + efficiency = incremental / full_policy_spend if full_policy_spend > 1e-12 else np.nan + welfare_efficiency = ( + incremental_welfare / full_policy_spend if full_policy_spend > 1e-12 else np.nan + ) + realized_spend = float(result.metadata["realized_spend"]) + return { + "assignment_estimate": float(estimate.estimate), + "assignment_std_error": standard_error, + "assignment_p_value": float(estimate.p_value), + "full_policy_truth": float(full_policy_effect), + "target_estimand": controls.target_estimand, + "treatment_version": str(result.metadata["treatment_version"]), + "treatment_version_limitation": str( + result.metadata["treatment_version_limitation"] + ), + "estimator": str(estimate.method), + "expected_incremental_outcome": incremental, + "modeled_incremental_welfare": incremental_welfare, + "full_policy_spend": full_policy_spend, + "realized_schedule_spend": realized_spend, + "budget_efficiency": efficiency, + "modeled_welfare_per_dollar": welfare_efficiency, + "realized_schedule_budget_scale": float(result.metadata["budget_scale"]), + "full_policy_budget_scale": float(result.metadata["all_treated_budget_scale"]), + "effective_clusters": int(estimate.diagnostics.get("n_clusters", estimate.n_obs)), + "target_alignment": "target_mismatch_assignment_diagnostic", + "evidence_type": "semi_synthetic_structural_known_truth", + } + + +def _paired_replication_seeds(seed: int, replications: int) -> tuple[int, ...]: + sequence = np.random.SeedSequence(seed) + return tuple( + int(child.generate_state(1, dtype=np.uint32)[0]) for child in sequence.spawn(replications) + ) + + +def _roll_up_decision_metrics(records: pd.DataFrame) -> pd.DataFrame: + rows: list[dict[str, float | int | str]] = [] + for design, group in records.groupby("design", sort=True): + mean_spend = float(group["full_policy_spend"].mean()) + mean_incremental = float(group["expected_incremental_outcome"].mean()) + mean_welfare = float(group["modeled_incremental_welfare"].mean()) + rejection_rate = float((group["assignment_p_value"] < 0.05).mean()) + n_replications = int(len(group)) + rows.append( + { + "design": str(design), + "target_estimand": str(group["target_estimand"].iloc[0]), + "treatment_version": str(group["treatment_version"].iloc[0]), + "treatment_version_limitation": str( + group["treatment_version_limitation"].iloc[0] + ), + "estimator": str(group["estimator"].iloc[0]), + "full_policy_truth": float(group["full_policy_truth"].mean()), + "expected_incremental_outcome": mean_incremental, + "incremental_outcome_mc_sd": float( + group["expected_incremental_outcome"].std(ddof=1) + ), + "mean_full_policy_spend": mean_spend, + "budget_efficiency": ( + mean_incremental / mean_spend if mean_spend > 1e-12 else np.nan + ), + "modeled_incremental_welfare": mean_welfare, + "modeled_welfare_mc_sd": float(group["modeled_incremental_welfare"].std(ddof=1)), + "modeled_welfare_per_dollar": ( + mean_welfare / mean_spend if mean_spend > 1e-12 else np.nan + ), + "mean_full_policy_budget_scale": float(group["full_policy_budget_scale"].mean()), + "mean_realized_schedule_budget_scale": float( + group["realized_schedule_budget_scale"].mean() + ), + "mean_assignment_estimate": float(group["assignment_estimate"].mean()), + "assignment_estimate_mc_sd": float(group["assignment_estimate"].std(ddof=1)), + "mean_assignment_std_error": float(group["assignment_std_error"].mean()), + "assignment_rejection_rate": rejection_rate, + "assignment_rejection_mcse": float( + np.sqrt(rejection_rate * (1.0 - rejection_rate) / n_replications) + ), + "effective_clusters": int(round(group["effective_clusters"].mean())), + "replications": n_replications, + "target_alignment": "target_mismatch_assignment_diagnostic", + "scenario_evidence": "on_demand_semi_synthetic_known_truth", + } + ) + return pd.DataFrame(rows) + + +def run_scenario_benchmark( + controls: DashboardControls, + *, + designs: Sequence[str | DesignName] | None = None, +) -> ScenarioBenchmark: + """Run an on-demand structural scenario and assignment diagnostic. + + The full-policy outcomes are known simulator counterfactuals. The observed + assignment coefficient has its own uncertainty and rejection diagnostic, but is + deliberately *not* compared with full-policy truth as if that gap were bias. + """ + + designs = (controls.randomization_unit,) if designs is None else designs + normalized_designs = tuple(dict.fromkeys(DesignName.parse(item).value for item in designs)) + if controls.randomization_unit not in normalized_designs: + normalized_designs = (*normalized_designs, controls.randomization_unit) + seeds = _paired_replication_seeds(controls.seed, controls.replications) + rows: list[dict[str, Any]] = [] + for design in normalized_designs: + for replication, seed in enumerate(seeds): + config = build_simulation_config(controls, design=design, seed=seed) + simulation = simulate_market(config) + metrics = dict(_estimate_simulation(simulation, controls)) + metrics.update( + { + "design": design, + "replication": replication, + "seed": seed, + "spillover_strength": controls.spillover_strength, + "persistence": controls.persistence, + "duration": controls.experiment_duration, + "budget": controls.budget, + } + ) + rows.append(metrics) + + records = pd.DataFrame(rows) + summary = _roll_up_decision_metrics(records) + summary["compatible_with_estimand"] = summary["design"].map( + lambda design: _design_is_compatible(str(design), controls) + ) + limitations = scenario_limitations(controls, summary) + calibration = load_calibration_template() + return ScenarioBenchmark( + controls=controls, + records=records, + summary=summary, + limitations=limitations, + calibration_path=calibration.path if calibration is not None else None, + calibration_sha256=calibration.sha256 if calibration is not None else None, + evidence_type=( + "semi_synthetic_structural_scenario" + if calibration is not None + else "configured_synthetic_structural_scenario" + ), + ) + + +def _interference_present(config: SimulationConfig) -> bool: + return any( + value > 0 + for value in ( + config.spillover_strength, + config.rider_substitution, + config.driver_mobility, + ) + ) + + +def _design_is_compatible(design: str, controls: DashboardControls) -> bool: + definition = get_estimand(controls.target_estimand) + if design not in definition.compatible_designs: + return False + config = build_simulation_config(controls, design=design) + identified, _ = identification_assessment( + controls.target_estimand, + design=design, + interference_present=_interference_present(config), + exposure_mapped=design == DesignName.GEO_TIME.value, + histories_observed=True, + ) + return identified + + +def recommend_design( + summary: pd.DataFrame, + controls: DashboardControls, + *, + require_declared_scenarios: bool = True, +) -> pd.Series: + """Choose only among complete, identified rows with valid finite inference.""" + + required = { + "declared_scenario_count", + "declared_scenario_set", + "design", + "estimator", + "target_estimand", + "bias", + "rmse", + "coverage", + "power", + "identified", + "inference_valid", + "fit_complete", + "applicable", + "attempted_fits", + "successful_fits", + } + missing = required.difference(summary.columns) + if missing: + raise ValueError(f"scenario summary missing recommendation columns: {sorted(missing)}") + eligible = summary.loc[summary["target_estimand"] == controls.target_estimand].copy() + for column in ("bias", "rmse", "coverage", "power"): + eligible[column] = pd.to_numeric(eligible[column], errors="coerce") + return choose_recommendation( + eligible, + controls.target_estimand, + require_declared_scenarios=require_declared_scenarios, + ) + + +def scenario_limitations( + controls: DashboardControls, + summary: pd.DataFrame, +) -> tuple[str, ...]: + """Return scenario-specific caveats, never numerical causal claims.""" + + design = controls.randomization_unit + selected = summary.loc[summary["design"] == design] + if len(selected) != 1: + raise ValueError("scenario limitations require one selected-design summary row") + selected_row = selected.iloc[0] + limitations = [ + ( + "All displayed causal quantities are semi-synthetic outputs under the declared " + "structural model; public trip data only calibrate broad moments and do not supply " + "an empirical treatment effect." + ), + ( + "The simulator uses a row-normalized ring exposure map. Production leakage, " + "platform equilibrium responses, and strategic behavior can differ." + ), + ( + "The incentive control changes payment cost and linearly scales the configured " + "driver-response channels relative to the reference dose. That mapping is a " + "semi-synthetic assumption, not an empirically estimated dose-response curve." + ), + ( + "The observed assignment coefficient is a design diagnostic, not automatically the " + "full-policy market-total estimand; the dashboard therefore never labels their gap " + "as bias." + ), + ( + "Modeled welfare is incomplete: its configured rider value, operating cost, wait " + "disutility, and transfers omit distributional weights and externalities." + ), + ] + treatment_version = TreatmentVersion.parse(controls.treatment_version) + limitations.append(str(selected_row["treatment_version_limitation"])) + if treatment_version is TreatmentVersion.RIDER_DISCOUNT: + limitations.append( + "The driver-incentive size control is inactive for rider-discount-only treatment; " + "the configured discount rate is the operative monetary dose." + ) + elif treatment_version is TreatmentVersion.DRIVER_INCENTIVE: + limitations.append( + "Driver-incentive-only treatment activates the supply and incentive-cost pathways; " + "the rider discount and direct demand pathway are inactive." + ) + else: + limitations.append( + "The bundled arm identifies only the joint rider-plus-driver intervention. A " + "factorial experiment is required to separate component effects or interactions." + ) + if controls.n_clusters < 8 and design in { + DesignName.GEO_CLUSTER.value, + DesignName.GEO_TIME.value, + }: + limitations.append( + "Fewer than eight geographic clusters make cluster-robust uncertainty and power " + "especially fragile; use randomization inference and small-cluster corrections." + ) + if ( + controls.persistence > 0 + and controls.washout_periods == 0 + and design + in { + DesignName.TIME_BLOCK.value, + DesignName.SWITCHBACK.value, + DesignName.GEO_TIME.value, + } + ): + limitations.append( + "Positive persistence with no washout can contaminate post-switch observations." + ) + if controls.treatment_saturation < 1: + limitations.append( + "Partial saturation identifies the selected exposure policy; extrapolation to full " + "market saturation requires additional structural assumptions." + ) + if float(selected_row.get("mean_full_policy_budget_scale", 1.0)) < 0.999: + limitations.append( + "The budget binds in generated assignments, so randomized assignment and received " + "intensity differ; report both the ITT and the exposure first stage." + ) + if controls.replications < 100: + limitations.append( + "The on-demand structural averages use fewer than 100 simulator draws and retain " + "material Monte Carlo error; benchmark bias, coverage, and power come only from the " + "separately generated artifact." + ) + if not selected.empty and not bool(selected.iloc[0]["compatible_with_estimand"]): + limitations.append( + f"{DESIGN_LABELS[controls.randomization_unit]} is not eligible for the selected " + "market-total estimand under the registry's identification screen." + ) + return tuple(dict.fromkeys(limitations)) + + +_ARTIFACT_CANDIDATES: Final[tuple[str, ...]] = ( + "benchmark_results.csv", + "monte_carlo_summary.csv", + "benchmark_summary.csv", +) + + +def _project_root() -> Path: + return Path(__file__).resolve().parents[2] + + +def _manifest_file_entries(payload: Mapping[str, Any]) -> list[Mapping[str, Any]]: + raw = payload.get("files", payload.get("artifacts", [])) + if isinstance(raw, list): + return [entry for entry in raw if isinstance(entry, Mapping)] + if isinstance(raw, Mapping): + entries: list[Mapping[str, Any]] = [] + for path, metadata in raw.items(): + if isinstance(metadata, Mapping): + entries.append({"path": path, **metadata}) + return entries + return [] + + +def _validate_reproduce_lineage(source: Path, *, project_root: Path | None = None) -> None: + """Require a complete top-level reproduction manifest for default artifacts.""" + + root = _project_root() if project_root is None else project_root + artifact_root = root / "artifacts" + incomplete = artifact_root / "REPRODUCE_INCOMPLETE.json" + if incomplete.exists(): + raise ValueError( + "reproduction is marked incomplete; generated benchmark artifacts are unavailable" + ) + manifest_path = artifact_root / "reproduce_manifest.json" + if not manifest_path.is_file(): + raise ValueError("top-level artifacts/reproduce_manifest.json is missing") + payload = json.loads(manifest_path.read_text(encoding="utf-8")) + if not isinstance(payload, Mapping): + raise ValueError("top-level reproduction manifest root must be a mapping") + metadata = payload.get("metadata") + if not isinstance(metadata, Mapping): + raise ValueError("top-level reproduction manifest has no metadata mapping") + expected_source_hash = str(metadata.get("source_tree_sha256", "")) + if not expected_source_hash: + raise ValueError("top-level reproduction manifest has no source-tree SHA-256") + actual_source_hash = _source_tree_sha256(root) + if actual_source_hash != expected_source_hash: + raise ValueError( + "current source/config tree differs from the completed reproduction manifest" + ) + + resolved_source = source.resolve() + matched: Mapping[str, Any] | None = None + for entry in _manifest_file_entries(payload): + raw_path = entry.get("path") + if raw_path is None: + continue + declared = Path(str(raw_path)) + candidates = ( + (declared.resolve(),) + if declared.is_absolute() + else ((root / declared).resolve(), (artifact_root / declared).resolve()) + ) + if resolved_source in candidates: + matched = entry + break + if matched is None: + raise ValueError("benchmark artifact has no entry in the top-level reproduction manifest") + + expected_hash = str(matched.get("sha256", "")) + raw_bytes = matched.get("bytes", matched.get("size")) + try: + expected_bytes = int(raw_bytes) + except (TypeError, ValueError) as exc: + raise ValueError("benchmark manifest entry has no valid byte count") from exc + if not expected_hash: + raise ValueError("benchmark manifest entry has no SHA-256") + actual_bytes = resolved_source.stat().st_size + if actual_bytes != expected_bytes: + raise ValueError( + f"benchmark artifact byte count differs from reproduction manifest " + f"({actual_bytes} != {expected_bytes})" + ) + if _sha256(resolved_source) != expected_hash: + raise ValueError("benchmark artifact SHA-256 differs from reproduction manifest") + + +def _read_json_mapping(path: Path, label: str) -> Mapping[str, Any]: + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise ValueError(f"{label} is not readable strict JSON") from exc + if not isinstance(payload, Mapping): + raise ValueError(f"{label} root must be a mapping") + return payload + + +def _resolve_child_entry_path( + raw_path: object, + *, + manifest_path: Path, + project_root: Path, +) -> Path: + if not isinstance(raw_path, str) or not raw_path: + raise ValueError("child manifest file entry has no path") + declared = Path(raw_path) + if declared.is_absolute() or ".." in declared.parts: + raise ValueError("child manifest paths must be portable and traversal-free") + candidates = { + (project_root / declared).resolve(), + (manifest_path.parent / declared).resolve(), + } + contained: list[Path] = [] + for candidate in candidates: + try: + candidate.relative_to(project_root) + except ValueError as exc: + raise ValueError("child manifest file resolves outside project root") from exc + if candidate.is_file(): + contained.append(candidate) + unique = sorted(set(contained)) + if not unique: + raise ValueError(f"child manifest file is missing: {declared.as_posix()}") + if len(unique) != 1: + raise ValueError(f"child manifest file path is ambiguous: {declared.as_posix()}") + return unique[0] + + +def _validated_child_files( + payload: Mapping[str, Any], + *, + manifest_path: Path, + project_root: Path, +) -> tuple[tuple[Mapping[str, Any], Path], ...]: + if payload.get("portable_paths") is not True: + raise ValueError("child manifest does not certify portable paths") + raw_entries = payload.get("files") + if not isinstance(raw_entries, list) or not raw_entries: + raise ValueError("child manifest must declare a nonempty files list") + entries: list[tuple[Mapping[str, Any], Path]] = [] + declared_paths: set[str] = set() + resolved_paths: set[Path] = set() + for raw_entry in raw_entries: + if not isinstance(raw_entry, Mapping): + raise ValueError("child manifest file entries must be mappings") + raw_path = raw_entry.get("path") + if not isinstance(raw_path, str) or raw_path in declared_paths: + raise ValueError("child manifest file paths must be unique strings") + declared_paths.add(raw_path) + path = _resolve_child_entry_path( + raw_path, + manifest_path=manifest_path, + project_root=project_root, + ) + if path in resolved_paths: + raise ValueError("child manifest paths resolve to a duplicate file") + resolved_paths.add(path) + raw_bytes = raw_entry.get("bytes") + if isinstance(raw_bytes, bool): + raise ValueError("child manifest file has no valid byte count") + try: + expected_bytes = int(raw_bytes) + except (TypeError, ValueError) as exc: + raise ValueError("child manifest file has no valid byte count") from exc + expected_hash = raw_entry.get("sha256") + if ( + not isinstance(expected_hash, str) + or len(expected_hash) != 64 + or any(character not in "0123456789abcdef" for character in expected_hash) + ): + raise ValueError("child manifest file has no valid SHA-256") + if path.stat().st_size != expected_bytes: + raise ValueError("child manifest file byte count mismatch") + if _sha256(path) != expected_hash: + raise ValueError("child manifest file SHA-256 mismatch") + entries.append((raw_entry, path)) + + declared_digest = payload.get("declared_file_set_sha256") + if declared_digest is not None: + if not isinstance(declared_digest, str) or len(declared_digest) != 64: + raise ValueError("child manifest declared file-set digest is invalid") + recomputed = hashlib.sha256( + json.dumps(raw_entries, sort_keys=True, separators=(",", ":")).encode( + "utf-8" + ) + ).hexdigest() + if recomputed != declared_digest: + raise ValueError("child manifest declared file-set digest mismatch") + return tuple(entries) + + +def _validated_child_inputs( + payload: Mapping[str, Any], + *, + project_root: Path, +) -> tuple[tuple[Mapping[str, Any], Path], ...]: + """Validate immutable upstream inputs declared by a child manifest. + + Unlike bundle files, inputs are always interpreted relative to the project root; + accepting manifest-relative fallbacks here could silently validate the wrong + upstream artifact after a bundle is moved. + """ + + raw_entries = payload.get("inputs", []) + if not isinstance(raw_entries, list): + raise ValueError("child manifest inputs must be a list") + entries: list[tuple[Mapping[str, Any], Path]] = [] + declared_paths: set[str] = set() + resolved_paths: set[Path] = set() + for raw_entry in raw_entries: + if not isinstance(raw_entry, Mapping): + raise ValueError("child manifest input entries must be mappings") + raw_path = raw_entry.get("path") + if not isinstance(raw_path, str) or not raw_path or raw_path in declared_paths: + raise ValueError("child manifest input paths must be unique strings") + declared = Path(raw_path) + if declared.is_absolute() or ".." in declared.parts: + raise ValueError( + "child manifest input paths must be project-root relative and traversal-free" + ) + declared_paths.add(raw_path) + path = (project_root / declared).resolve() + try: + path.relative_to(project_root) + except ValueError as exc: + raise ValueError("child manifest input resolves outside project root") from exc + if not path.is_file(): + raise ValueError(f"child manifest input is missing: {declared.as_posix()}") + if path in resolved_paths: + raise ValueError("child manifest input paths resolve to a duplicate file") + resolved_paths.add(path) + + role = raw_entry.get("role") + if not isinstance(role, str) or not role: + raise ValueError("child manifest input roles must be nonempty strings") + evidence_types = raw_entry.get("evidence_types") + if evidence_types is not None and ( + not isinstance(evidence_types, list) + or not evidence_types + or any(not isinstance(value, str) or not value for value in evidence_types) + ): + raise ValueError("child manifest input has invalid evidence labels") + + raw_bytes = raw_entry.get("bytes") + if isinstance(raw_bytes, bool): + raise ValueError("child manifest input has no valid byte count") + try: + expected_bytes = int(raw_bytes) + except (TypeError, ValueError) as exc: + raise ValueError("child manifest input has no valid byte count") from exc + expected_hash = raw_entry.get("sha256") + if ( + not isinstance(expected_hash, str) + or len(expected_hash) != 64 + or any(character not in "0123456789abcdef" for character in expected_hash) + ): + raise ValueError("child manifest input has no valid SHA-256") + if path.stat().st_size != expected_bytes: + raise ValueError("child manifest input byte count mismatch") + if _sha256(path) != expected_hash: + raise ValueError("child manifest input SHA-256 mismatch") + entries.append((raw_entry, path)) + declared_digest = payload.get("declared_input_set_sha256") + if declared_digest is not None: + if not isinstance(declared_digest, str) or len(declared_digest) != 64: + raise ValueError("child manifest declared input-set digest is invalid") + recomputed = hashlib.sha256( + json.dumps(raw_entries, sort_keys=True, separators=(",", ":")).encode( + "utf-8" + ) + ).hexdigest() + if recomputed != declared_digest: + raise ValueError("child manifest declared input-set digest mismatch") + return tuple(entries) + + +def _child_file_by_role( + files: Sequence[tuple[Mapping[str, Any], Path]], role: str +) -> tuple[Mapping[str, Any], Path]: + matches = [(entry, path) for entry, path in files if entry.get("role") == role] + if len(matches) != 1: + raise ValueError(f"child manifest must declare exactly one {role} file") + return matches[0] + + +def _child_file_by_name( + files: Sequence[tuple[Mapping[str, Any], Path]], name: str +) -> tuple[Mapping[str, Any], Path]: + matches = [(entry, path) for entry, path in files if path.name == name] + if len(matches) != 1: + raise ValueError(f"child manifest must declare exactly one {name}") + return matches[0] + + +def _validate_nyc_informed_layer( + payload: Mapping[str, Any], + files: Sequence[tuple[Mapping[str, Any], Path]], + _inputs: Sequence[tuple[Mapping[str, Any], Path]], + _project_root: Path, +) -> str: + evidence = "semi_synthetic_nyc_informed_known_truth_monte_carlo" + if ( + payload.get("schema_version") != "1.0.0" + or payload.get("artifact_type") != "nyc_informed_marketplace_benchmark" + or payload.get("evidence_type") != evidence + or payload.get("causal_claim") is not False + or payload.get("causal_claim_from_nyc_data") is not False + or payload.get("simulator_known_truth") is not True + ): + raise ValueError("NYC-informed benchmark manifest has invalid scientific schema") + roles = {str(entry.get("role")) for entry, _ in files} + if roles != {"records", "summary", "fit_ledger", "failures", "metadata"}: + raise ValueError("NYC-informed benchmark manifest has an incomplete file-role set") + summary_entry, summary_path = _child_file_by_role(files, "summary") + evidence_types = summary_entry.get("evidence_types") + if not isinstance(evidence_types, list) or evidence not in evidence_types: + raise ValueError("NYC-informed summary has no known-truth evidence label") + summary = pd.read_csv(summary_path) + if summary.empty or set(summary["evidence_type"].astype(str)) != {evidence}: + raise ValueError("NYC-informed summary evidence labels are invalid") + _, metadata_path = _child_file_by_role(files, "metadata") + metadata = _read_json_mapping(metadata_path, "NYC-informed benchmark metadata") + bundle = metadata.get("artifact_bundle") + if ( + metadata.get("evidence_type") != evidence + or metadata.get("nyc_empirical_causal_effect") is not False + or metadata.get("simulator_known_truth") is not True + or not isinstance(bundle, Mapping) + or bundle.get("schema_version") != "1.0.0" + or bundle.get("evidence_type") != evidence + ): + raise ValueError("NYC-informed benchmark metadata has invalid evidence provenance") + return f"{len(summary):,} verified summary rows; simulator truth, not NYC effects" + + +def _validate_nyc_graph_layer( + payload: Mapping[str, Any], + files: Sequence[tuple[Mapping[str, Any], Path]], + _inputs: Sequence[tuple[Mapping[str, Any], Path]], + _project_root: Path, +) -> str: + evidence = "semi_synthetic_known_truth_on_descriptive_nyc_graph" + summary_evidence = "semi_synthetic_nyc_graph_known_truth_monte_carlo" + if ( + payload.get("schema_version") != "1.0.0" + or payload.get("artifact_type") != "nyc_graph_interference_benchmark" + or payload.get("evidence_type") != evidence + or payload.get("causal_claim") is not False + or payload.get("causal_claim_from_nyc_data") is not False + or payload.get("input_graph_evidence_label") != "descriptive_real_data" + ): + raise ValueError("NYC graph benchmark manifest has invalid scientific schema") + roles = {str(entry.get("role")) for entry, _ in files} + if roles != {"records", "summary", "fit_ledger", "failures", "metadata"}: + raise ValueError("NYC graph benchmark manifest has an incomplete file-role set") + summary_entry, summary_path = _child_file_by_role(files, "summary") + evidence_types = summary_entry.get("evidence_types") + if not isinstance(evidence_types, list) or summary_evidence not in evidence_types: + raise ValueError("NYC graph summary has no known-truth evidence label") + summary = pd.read_csv(summary_path) + observed_labels = set(summary["evidence_type"].dropna().astype(str)) + if ( + summary.empty + or summary_evidence not in observed_labels + or any(not value.startswith("semi_synthetic") for value in observed_labels) + ): + raise ValueError("NYC graph summary evidence labels are invalid") + _, metadata_path = _child_file_by_role(files, "metadata") + metadata = _read_json_mapping(metadata_path, "NYC graph benchmark metadata") + bundle = metadata.get("artifact_bundle") + if ( + metadata.get("evidence_type") != evidence + or metadata.get("causal_claim_from_nyc_data") is not False + or metadata.get("input_graph_evidence_label") != "descriptive_real_data" + or not isinstance(bundle, Mapping) + or bundle.get("schema_version") != "1.0.0" + or bundle.get("evidence_type") != evidence + ): + raise ValueError("NYC graph benchmark metadata has invalid evidence provenance") + return f"{len(summary):,} verified summary rows on descriptive NYC OD geometry" + + +def _validate_equilibrium_layer( + payload: Mapping[str, Any], + files: Sequence[tuple[Mapping[str, Any], Path]], + _inputs: Sequence[tuple[Mapping[str, Any], Path]], + _project_root: Path, +) -> str: + evidence = "theoretical_simulation_known_ground_truth" + if ( + payload.get("schema_version") != 1 + or payload.get("bundle_type") + != "two_sided_fixed_point_equilibrium_benchmark" + or payload.get("evidence_type") != evidence + or payload.get("causal_scope") != "within_declared_equilibrium_model_only" + or payload.get("empirical_calibration_status") + != "not_an_empirical_or_nyc_structural_estimate" + or payload.get("is_nyc_structural_estimate") is not False + ): + raise ValueError("equilibrium manifest has invalid theoretical evidence schema") + required_names = {"summary.json", "zone_effects.csv", "ledger.csv"} + if {path.name for _, path in files} != required_names: + raise ValueError("equilibrium manifest has an incomplete file set") + checks = payload.get("checks") + required_checks = { + "control_equilibrium_converged", + "treatment_equilibrium_converged", + "residuals_within_tolerance", + "sufficient_uniqueness_condition_satisfied", + "common_random_numbers_verified", + "budget_feasible", + "welfare_accounting_balanced", + "ground_truth_recomputed", + "hashes_recomputed", + } + if not isinstance(checks, Mapping) or any( + checks.get(key) is not True for key in required_checks + ): + raise ValueError("equilibrium manifest has an unpassed scientific check") + _, summary_path = _child_file_by_name(files, "summary.json") + summary = _read_json_mapping(summary_path, "equilibrium summary") + equations = summary.get("equations") + if ( + summary.get("schema_version") != 1 + or summary.get("evidence_type") != evidence + or summary.get("common_random_numbers") is not True + or summary.get("is_nyc_structural_estimate") is not False + or not isinstance(equations, Mapping) + or not {"rider_demand", "driver_supply", "wait_fixed_point"}.issubset( + equations + ) + ): + raise ValueError("equilibrium summary has invalid evidence or equation schema") + return "fixed-point residual, budget, welfare, and common-state checks verified" + + +def _validate_weather_layer( + payload: Mapping[str, Any], + files: Sequence[tuple[Mapping[str, Any], Path]], + _inputs: Sequence[tuple[Mapping[str, Any], Path]], + _project_root: Path, +) -> str: + evidence = "descriptive_observed_external_weather" + if ( + payload.get("schema_version") != "1.0.0" + or payload.get("evidence_label") != evidence + or payload.get("causal_claim") is not False + ): + raise ValueError("weather manifest has invalid descriptive evidence schema") + checks = payload.get("checks") + if not isinstance(checks, Mapping) or any( + checks.get(key) is not True + for key in ( + "noaa_raw_hash_matches", + "calendar_complete", + "nyc_source_manifest_valid", + "trip_conservation", + ) + ): + raise ValueError("weather manifest has an unpassed source or conservation check") + _, summary_path = _child_file_by_name(files, "weather_associations.json") + summary = _read_json_mapping(summary_path, "weather association summary") + scope = summary.get("scope") + if ( + summary.get("schema_version") != "1.0.0" + or summary.get("evidence_label") != evidence + or summary.get("causal_claim") is not False + or not isinstance(scope, Mapping) + or scope.get("city") != "New York City" + or scope.get("population_claim") is not False + ): + raise ValueError("weather summary has invalid descriptive scope") + return f"{scope.get('pickup_month', 'NYC month')} observed weather-trip associations" + + +def _validate_events_layer( + payload: Mapping[str, Any], + files: Sequence[tuple[Mapping[str, Any], Path]], + inputs: Sequence[tuple[Mapping[str, Any], Path]], + _project_root: Path, +) -> str: + evidence = "descriptive_observed_external_calendar_events" + checks = payload.get("checks") + required_true = { + "holiday_snapshot_hash_matches", + "event_snapshot_hash_matches", + "calendar_complete", + "holiday_schedule_coverage_complete", + "event_source_rows_verified", + "event_source_unique_ids_verified", + "invalid_source_intervals_retained_and_excluded", + "zero_duration_source_intervals_retained_and_excluded", + "daily_signal_is_citywide_not_zone_exposure", + "hourly_profiles_repeat_daily_signal_not_event_hour_exposure", + "major_event_is_researcher_defined", + "nyc_source_manifest_valid", + "trip_conservation", + "causal_claim_is_false", + } + if ( + payload.get("schema_version") != "1.0.0" + or payload.get("evidence_label") != evidence + or payload.get("causal_claim") is not False + or not isinstance(checks, Mapping) + or any(checks.get(key) is not True for key in required_true) + or checks.get("major_event_contrast_separately_identified") is not False + ): + raise ValueError("calendar/event manifest has invalid descriptive evidence schema") + expected_files = { + "normalized_daily_calendar", + "normalized_permit_records", + "daily_permit_type_counts", + "joined_daily_trip_panel", + "descriptive_hourly_profiles", + "descriptive_summary", + } + file_roles = [str(entry.get("role")) for entry, _ in files] + if set(file_roles) != expected_files or len(file_roles) != 6: + raise ValueError("calendar/event manifest has an incomplete file-role set") + input_roles = [str(entry.get("role")) for entry, _ in inputs] + singleton_roles = { + "official_holiday_snapshot", + "official_nyc_permitted_events_snapshot", + "nyc_full_data_manifest", + } + panel_count = checks.get("panel_files_verified") + if ( + isinstance(panel_count, bool) + or not isinstance(panel_count, int) + or panel_count < 1 + or any(input_roles.count(role) != 1 for role in singleton_roles) + or input_roles.count("nyc_full_zone_time_panel") != panel_count + or set(input_roles) != singleton_roles | {"nyc_full_zone_time_panel"} + ): + raise ValueError("calendar/event manifest has an incomplete input-role set") + summary_matches = [ + path for entry, path in files if entry.get("role") == "descriptive_summary" + ] + if len(summary_matches) != 1: + raise ValueError("calendar/event manifest has no unique descriptive summary") + summary = _read_json_mapping(summary_matches[0], "calendar/event summary") + scope = summary.get("scope") + coverage = summary.get("coverage") + associations = summary.get("associations") + identification = summary.get("identification_checks") + conservation = summary.get("conservation") + if not all( + isinstance(value, Mapping) + for value in (scope, coverage, associations, identification, conservation) + ): + raise ValueError("calendar/event summary is incomplete") + weekday = associations.get( + "above_vs_at_or_below_median_permit_intensity_weekdays_only" + ) + if ( + summary.get("schema_version") != "1.0.0" + or summary.get("evidence_label") != evidence + or summary.get("causal_claim") is not False + or scope.get("city") != "New York City" + or scope.get("event_signal_spatial_granularity") != "citywide" + or scope.get("event_signal_temporal_granularity") != "service_date" + or scope.get("population_claim") is not False + or identification.get("causal_effect_identified") is not False + or identification.get("major_event_contrast_separately_identifies_event_effect") + is not False + or identification.get("all_weekend_days_are_above_median_permit_intensity") + is not True + or coverage.get("above_median_permit_intensity_weekend_days") + != coverage.get("weekend_days") + or coverage.get("at_or_below_median_permit_intensity_weekend_days") != 0 + or not isinstance(weekday, Mapping) + or conservation.get("passes") is not True + or conservation.get("daily_trip_sum") != conservation.get("zone_time_trip_sum") + ): + raise ValueError("calendar/event summary violates its non-causal scope") + permit_rows = coverage.get("source_permit_rows") + unique_ids = coverage.get("source_unique_event_ids") + invalid_rows = coverage.get("invalid_interval_rows_retained_but_not_expanded") + zero_duration_rows = coverage.get( + "zero_duration_interval_rows_retained_but_not_expanded" + ) + nonpositive_rows = coverage.get( + "all_nonpositive_interval_rows_retained_but_not_expanded" + ) + valid_rows = coverage.get("valid_interval_rows") + valid_unique_ids = coverage.get("valid_unique_event_ids") + expanded_event_days = coverage.get("expanded_unique_event_days") + count_values = ( + permit_rows, + unique_ids, + invalid_rows, + zero_duration_rows, + nonpositive_rows, + valid_rows, + valid_unique_ids, + expanded_event_days, + ) + if ( + any( + isinstance(value, bool) or not isinstance(value, int) + for value in count_values + ) + or permit_rows < unique_ids + or unique_ids < 1 + or invalid_rows < 0 + or zero_duration_rows < 0 + or nonpositive_rows != invalid_rows + zero_duration_rows + or valid_rows != permit_rows - nonpositive_rows + or not 1 <= valid_unique_ids <= unique_ids + or expanded_event_days < valid_unique_ids + ): + raise ValueError("calendar/event summary has inconsistent interval counts") + return ( + f"{permit_rows} permit rows / {unique_ids} IDs; {zero_duration_rows} zero-duration " + "intervals retained but excluded; weekend composition " + "and weekday-only diagnostic verified" + ) + + +def _validate_income_layer( + payload: Mapping[str, Any], + files: Sequence[tuple[Mapping[str, Any], Path]], + inputs: Sequence[tuple[Mapping[str, Any], Path]], + project_root: Path, +) -> str: + evidence = "descriptive_observed_external_neighborhood_income" + checks = payload.get("checks") + required_true = { + "official_source_hashes_match", + "taxi_location_ids_unique_and_complete", + "tract_b19001_totals_equal_sixteen_bins", + "household_distribution_conserved", + "published_trip_conservation", + "ecological_noncausal_contract", + "dominant_nonresidential_primary_unclassified", + "all_zone_classification_is_sensitivity_only", + } + if ( + payload.get("schema_version") != "1.0.0" + or payload.get("artifact_type") != "nyc_income_descriptive_bundle" + or payload.get("evidence_label") != evidence + or payload.get("causal_claim") is not False + or not isinstance(checks, Mapping) + or any(checks.get(key) is not True for key in required_true) + or checks.get("median_of_medians_used") is not False + or checks.get("equal_area_crs") != "EPSG:6933" + or checks.get("dominant_nonresidential_primary_classified_zones") != 0 + or checks.get("minimum_allocated_households") != 1.0 + or checks.get("minimum_residential_taxi_zone_area_share") != 0.5 + or checks.get("residential_nta_type_codes") != ["0"] + or checks.get("zone_grouped_medians_are_point_estimates") is not True + or checks.get("zone_level_margin_of_error_propagated") is not False + ): + raise ValueError("income manifest has invalid ecological evidence schema") + expected_files = { + "taxi_zone_nta_crosswalk", + "nta_b19001_distribution_summary", + "taxi_zone_income_and_trip_summary", + "daily_income_group_description", + "monthly_income_group_description", + "income_association_summary", + } + if ( + {str(entry.get("role")) for entry, _ in files} != expected_files + or len(files) != 6 + or any( + entry.get("evidence_label") != evidence + or entry.get("causal_claim") is not False + for entry, _ in files + ) + ): + raise ValueError("income manifest has an incomplete or unsafe file-role set") + expected_input_types = { + "official_tlc_taxi_zone_geometry": "official_observed_geometry", + "official_nyc_nta2020_geometry": "official_observed_geometry", + "official_nyc_tract2020_to_nta2020_mapping": "official_observed_crosswalk", + "official_census_acs_2022_5yr_b19001_nyc_tract_slice": ( + "official_observed_estimates" + ), + "verified_nyc_full_data_manifest": "descriptive_real_data_lineage", + } + input_by_role = { + str(entry.get("role")): (entry, path) + for entry, path in inputs + if entry.get("role") != "nyc_full_zone_time_panel" + } + panel_inputs = [ + (entry, path) + for entry, path in inputs + if entry.get("role") == "nyc_full_zone_time_panel" + ] + panel_count = checks.get("panel_files_verified") + if ( + set(input_by_role) != set(expected_input_types) + or isinstance(panel_count, bool) + or not isinstance(panel_count, int) + or len(panel_inputs) != panel_count + or len(inputs) != 5 + panel_count + ): + raise ValueError("income manifest has an incomplete input-role set") + if any( + input_by_role[role][0].get("source_type") != source_type + for role, source_type in expected_input_types.items() + ) or any( + entry.get("source_type") != "descriptive_real_data_panel" + for entry, _ in panel_inputs + ): + raise ValueError("income manifest has invalid input evidence types") + summary_matches = [ + path for entry, path in files if entry.get("role") == "income_association_summary" + ] + if len(summary_matches) != 1: + raise ValueError("income manifest has no unique association summary") + summary = _read_json_mapping(summary_matches[0], "income association summary") + scope = summary.get("scope") + coverage = summary.get("coverage") + associations = summary.get("associations") + conservation = summary.get("conservation") + spatial = summary.get("spatial_mapping") + acs = summary.get("acs_aggregation") + allocation = summary.get("zone_allocation") + primary_classification = summary.get("primary_classification") + uncertainty = summary.get("classification_uncertainty") + sensitivity = summary.get("sensitivity") + if not all( + isinstance(value, Mapping) + for value in ( + scope, + coverage, + associations, + conservation, + spatial, + acs, + allocation, + primary_classification, + uncertainty, + sensitivity, + ) + ): + raise ValueError("income association summary is incomplete") + if ( + summary.get("schema_version") != "1.0.0" + or summary.get("evidence_label") != evidence + or summary.get("causal_claim") is not False + or scope.get("city") != "New York City" + or scope.get("population_claim") is not False + or scope.get("individual_income_claim") is not False + or spatial.get("equal_area_crs") != "EPSG:6933" + or acs.get("median_of_medians_used") is not False + or allocation.get("all_sixteen_bins_conserved") is not True + or allocation.get("households_conserved") is not True + or allocation.get("minimum_allocated_households") != 1.0 + or allocation.get("minimum_residential_taxi_zone_area_share") != 0.5 + or allocation.get("residential_nta_type_codes") != ["0"] + or primary_classification.get("primary_result") is not True + or primary_classification.get("minimum_allocated_households") != 1.0 + or primary_classification.get("minimum_residential_taxi_zone_area_share") + != 0.5 + or primary_classification.get("residential_nta_type_codes") != ["0"] + or uncertainty.get("nta_b19001_margins_of_error_retained") is not True + or uncertainty.get("zone_grouped_medians_are_point_estimates") is not True + or uncertainty.get("zone_level_margin_of_error_propagated") is not False + or "not a confidence interval" + not in str(uncertainty.get("interpretation", "")).lower() + or conservation.get("passes") is not True + ): + raise ValueError("income association summary violates its ecological scope") + total = coverage.get("published_completed_trips") + classified = coverage.get("classified_published_completed_trips") + unclassified = coverage.get("unclassified_published_completed_trips") + classified_zones = coverage.get("classified_panel_zones") + panel_zones = coverage.get("panel_zone_rows") + allocated_high_zones = allocation.get("high_income_zone_rows") + allocated_low_zones = allocation.get("low_income_zone_rows") + ratio = coverage.get("classified_trip_coverage") + if ( + isinstance(total, bool) + or not isinstance(total, int) + or total <= 0 + or isinstance(classified, bool) + or not isinstance(classified, int) + or isinstance(unclassified, bool) + or not isinstance(unclassified, int) + or classified + unclassified != total + or isinstance(classified_zones, bool) + or not isinstance(classified_zones, int) + or isinstance(panel_zones, bool) + or not isinstance(panel_zones, int) + or isinstance(allocated_high_zones, bool) + or not isinstance(allocated_high_zones, int) + or isinstance(allocated_low_zones, bool) + or not isinstance(allocated_low_zones, int) + or not 0 < classified_zones <= panel_zones + or isinstance(ratio, bool) + or not isinstance(ratio, (int, float)) + or not np.isfinite(ratio) + or not np.isclose(ratio, classified / total) + or allocation.get("classified_zone_rows") != classified_zones + or allocated_high_zones + allocated_low_zones != classified_zones + or conservation.get("primary_classified_plus_unclassified_trip_sum") != total + or conservation.get("primary_nonresidential_classified_zones") != 0 + or any( + conservation.get(key) != total + for key in ("zone_trip_sum", "daily_group_trip_sum", "monthly_group_trip_sum") + ) + ): + raise ValueError("income association summary has inconsistent coverage") + high_rate = associations.get( + "mean_published_completed_trips_per_zone_hour_high_income_area" + ) + low_rate = associations.get( + "mean_published_completed_trips_per_zone_hour_low_income_area" + ) + difference = associations.get( + "high_minus_low_mean_published_completed_trips_per_zone_hour" + ) + rate_ratio = associations.get( + "high_to_low_mean_published_completed_trips_per_zone_hour_ratio" + ) + association_values = (high_rate, low_rate, difference, rate_ratio) + if ( + any(isinstance(value, bool) for value in association_values) + or not all(isinstance(value, (int, float)) for value in association_values) + or not np.isfinite(association_values).all() + or low_rate <= 0 + or not np.isclose(difference, high_rate - low_rate) + or not np.isclose(rate_ratio, high_rate / low_rate) + ): + raise ValueError("income association summary has inconsistent primary arithmetic") + primary_groups = primary_classification.get("groups") + if ( + not isinstance(primary_groups, Mapping) + or set(primary_groups) + != {"high_income_area", "low_income_area", "unclassified"} + or any(not isinstance(group, Mapping) for group in primary_groups.values()) + ): + raise ValueError("income association summary has incomplete primary groups") + primary_high = primary_groups["high_income_area"] + primary_low = primary_groups["low_income_area"] + primary_unclassified = primary_groups["unclassified"] + primary_group_zones = tuple( + group.get("panel_zones") + for group in (primary_high, primary_low, primary_unclassified) + ) + primary_group_trips = tuple( + group.get("published_completed_trips") + for group in (primary_high, primary_low, primary_unclassified) + ) + primary_high_mean = primary_high.get( + "mean_published_completed_trips_per_zone_hour" + ) + primary_low_mean = primary_low.get( + "mean_published_completed_trips_per_zone_hour" + ) + if ( + any( + isinstance(value, bool) or not isinstance(value, int) + for value in (*primary_group_zones, *primary_group_trips) + ) + or any(value < 0 for value in (*primary_group_zones, *primary_group_trips)) + or any( + isinstance(value, bool) or not isinstance(value, (int, float)) + for value in (primary_high_mean, primary_low_mean) + ) + or not np.isfinite([primary_high_mean, primary_low_mean]).all() + or sum(primary_group_zones[:2]) != classified_zones + or sum(primary_group_trips[:2]) != classified + or sum(primary_group_zones) != panel_zones + or sum(primary_group_trips) != total + or not np.isclose(primary_high_mean, high_rate) + or not np.isclose(primary_low_mean, low_rate) + ): + raise ValueError("income association summary has inconsistent primary groups") + proximity = uncertainty.get("threshold_proximity") + proximity_keys = ( + "within_1000_usd", + "within_2500_usd", + "within_5000_usd", + "within_10000_usd", + ) + if not isinstance(proximity, Mapping) or any( + not isinstance(proximity.get(key), Mapping) for key in proximity_keys + ): + raise ValueError("income association summary has an incomplete uncertainty audit") + prior_zones = -1 + prior_trips = -1 + for key in proximity_keys: + item = proximity[key] + zones = item.get("primary_eligible_panel_zones") + trips = item.get("published_completed_trips") + share = item.get("share_of_primary_classified_trips") + if ( + isinstance(zones, bool) + or not isinstance(zones, int) + or isinstance(trips, bool) + or not isinstance(trips, int) + or isinstance(share, bool) + or not isinstance(share, (int, float)) + or zones < prior_zones + or trips < prior_trips + or not np.isfinite(share) + or not 0 <= share <= 1 + or not np.isclose(share, trips / classified) + ): + raise ValueError("income association summary has an unsafe uncertainty audit") + prior_zones, prior_trips = zones, trips + + all_zone_sensitivity = sensitivity.get("all_zone_area_allocation") + groups = ( + all_zone_sensitivity.get("groups") + if isinstance(all_zone_sensitivity, Mapping) + else None + ) + if ( + not isinstance(all_zone_sensitivity, Mapping) + or not isinstance(groups, Mapping) + or set(groups) != {"high_income_area", "low_income_area", "unclassified"} + or any(not isinstance(group, Mapping) for group in groups.values()) + ): + raise ValueError("income association summary has an incomplete sensitivity") + high_group = groups["high_income_area"] + low_group = groups["low_income_area"] + unclassified_group = groups["unclassified"] + group_zone_counts = tuple( + group.get("panel_zones") for group in (high_group, low_group, unclassified_group) + ) + group_trip_counts = tuple( + group.get("published_completed_trips") + for group in (high_group, low_group, unclassified_group) + ) + sensitivity_classified_zones = all_zone_sensitivity.get("classified_panel_zones") + sensitivity_classified_trips = all_zone_sensitivity.get( + "classified_published_completed_trips" + ) + sensitivity_coverage = all_zone_sensitivity.get("classified_trip_coverage") + sensitivity_high = all_zone_sensitivity.get( + "mean_published_completed_trips_per_zone_hour_high_income_area" + ) + sensitivity_low = all_zone_sensitivity.get( + "mean_published_completed_trips_per_zone_hour_low_income_area" + ) + sensitivity_difference = all_zone_sensitivity.get( + "high_minus_low_mean_published_completed_trips_per_zone_hour" + ) + sensitivity_ratio = all_zone_sensitivity.get( + "high_to_low_mean_published_completed_trips_per_zone_hour_ratio" + ) + high_group_mean = high_group.get("mean_published_completed_trips_per_zone_hour") + low_group_mean = low_group.get("mean_published_completed_trips_per_zone_hour") + sensitivity_numeric = ( + sensitivity_coverage, + sensitivity_high, + sensitivity_low, + sensitivity_difference, + sensitivity_ratio, + high_group_mean, + low_group_mean, + ) + if ( + all_zone_sensitivity.get("primary_result") is not False + or all_zone_sensitivity.get( + "ignored_primary_residential_taxi_zone_area_share_threshold" + ) + != 0.5 + or any( + isinstance(value, bool) or not isinstance(value, int) + for value in ( + *group_zone_counts, + *group_trip_counts, + sensitivity_classified_zones, + sensitivity_classified_trips, + ) + ) + or any(isinstance(value, bool) for value in sensitivity_numeric) + or not all(isinstance(value, (int, float)) for value in sensitivity_numeric) + or not np.isfinite(sensitivity_numeric).all() + or any(value < 0 for value in (*group_zone_counts, *group_trip_counts)) + or sensitivity_low <= 0 + or sensitivity_classified_zones != sum(group_zone_counts[:2]) + or sensitivity_classified_trips != sum(group_trip_counts[:2]) + or panel_zones != sum(group_zone_counts) + or total != sum(group_trip_counts) + or not np.isclose(sensitivity_coverage, sensitivity_classified_trips / total) + or not np.isclose(sensitivity_high, high_group_mean) + or not np.isclose(sensitivity_low, low_group_mean) + or not np.isclose(sensitivity_difference, sensitivity_high - sensitivity_low) + or not np.isclose(sensitivity_ratio, sensitivity_high / sensitivity_low) + or conservation.get("sensitivity_group_trip_sum") != total + ): + raise ValueError("income association summary has inconsistent sensitivity arithmetic") + source_entry, source_path = input_by_role["verified_nyc_full_data_manifest"] + source = _read_json_mapping(source_path, "income source-data manifest") + source_metadata = source.get("metadata") + source_config = source.get("config") + if ( + not isinstance(source_metadata, Mapping) + or not isinstance(source_config, Mapping) + or source_config.get("source") != "nyc_hvfhv" + or source_config.get("mode") != "full" + or source_metadata.get("evidence_label") != "descriptive_real_data" + or source_metadata.get("causal_claim") is not False + ): + raise ValueError("income source-data manifest has unsafe evidence metadata") + panel_entries = [ + entry + for entry in source.get("files", []) + if isinstance(entry, Mapping) + and isinstance(entry.get("path"), str) + and "panel/zone_time" in entry["path"] + and entry["path"].endswith(".parquet") + ] + if ( + len(panel_entries) != panel_count + ): + raise ValueError("income source-data panel file set is incomplete") + for entry in panel_entries: + declared = Path(str(entry["path"])) + if declared.is_absolute() or ".." in declared.parts: + raise ValueError("income source-data panel path is nonportable") + panel_path = (project_root / declared).resolve() + try: + panel_path.relative_to(project_root) + except ValueError as exc: + raise ValueError("income source-data panel path escapes project root") from exc + if ( + not panel_path.is_file() + or panel_path.stat().st_size != entry.get("bytes") + or _sha256(panel_path) != entry.get("sha256") + ): + raise ValueError("income source-data panel lineage mismatch") + source_trip_sum = ( + source_metadata.get("full_month_processing", {}) + .get("row_conservation", {}) + .get("zone_time_trip_sum") + ) + if ( + {path for _, path in panel_inputs} + != {(project_root / Path(str(entry["path"]))).resolve() for entry in panel_entries} + or source_trip_sum != total + or source_entry.get("source_type") != "descriptive_real_data_lineage" + ): + raise ValueError("income trip total disagrees with source lineage") + return ( + f"{classified_zones} primary residential-eligible zones; " + f"{float(ratio):.2%} of published trips covered; nonresidential zones remain " + "unclassified in the primary result and all-zone allocation is sensitivity-only" + ) + + +_EVIDENCE_LAYER_VALIDATORS: Final[ + Mapping[ + str, + Any, + ] +] = { + "nyc_informed": _validate_nyc_informed_layer, + "nyc_graph": _validate_nyc_graph_layer, + "equilibrium": _validate_equilibrium_layer, + "weather": _validate_weather_layer, + "events": _validate_events_layer, + "income": _validate_income_layer, +} + +_EVIDENCE_LAYER_INPUT_ROLES: Final[Mapping[str, Mapping[str, str]]] = { + "nyc_informed": { + "anchor": "semi_synthetic_descriptive_anchor", + "anchor_manifest": "semi_synthetic_descriptive_anchor", + }, + "nyc_graph": { + "calibration_manifest": "descriptive_real_data", + "exposure_mapping": "descriptive_real_data", + }, +} + + +def load_evidence_layers( + project_root: str | Path | None = None, +) -> tuple[EvidenceLayerStatus, ...]: + """Load read-only evidence layers through top and child lineage gates. + + Missing, stale, malformed, or scientifically mislabeled artifacts are returned + as unavailable. These statuses are informational and are never passed into the + experiment-design recommendation functions. + """ + + root = (_project_root() if project_root is None else Path(project_root)).resolve() + statuses: list[EvidenceLayerStatus] = [] + for spec in _EVIDENCE_LAYER_SPECS: + manifest_path = (root / spec.relative_manifest).resolve() + if not manifest_path.is_file(): + statuses.append( + EvidenceLayerStatus( + key=spec.key, + title=spec.title, + classification=spec.classification, + interpretation=spec.interpretation, + available=False, + detail="unavailable: manifest is absent", + ) + ) + continue + try: + _validate_reproduce_lineage(manifest_path, project_root=root) + if list(manifest_path.parent.glob("*INCOMPLETE*.json")): + raise ValueError("child bundle is marked incomplete") + payload = _read_json_mapping(manifest_path, f"{spec.title} manifest") + files = _validated_child_files( + payload, + manifest_path=manifest_path, + project_root=root, + ) + inputs = _validated_child_inputs(payload, project_root=root) + expected_inputs = _EVIDENCE_LAYER_INPUT_ROLES.get(spec.key) + if expected_inputs is not None: + observed_inputs = { + str(entry.get("role")): entry for entry, _ in inputs + } + if set(observed_inputs) != set(expected_inputs): + raise ValueError("child manifest has an incomplete input-role set") + if any( + entry.get("evidence_types") != [evidence] + for role, evidence in expected_inputs.items() + for entry in (observed_inputs[role],) + ): + raise ValueError("child manifest input evidence labels are invalid") + detail = _EVIDENCE_LAYER_VALIDATORS[spec.key](payload, files, inputs, root) + except (KeyError, OSError, TypeError, ValueError) as exc: + statuses.append( + EvidenceLayerStatus( + key=spec.key, + title=spec.title, + classification=spec.classification, + interpretation=spec.interpretation, + available=False, + detail=f"unavailable: {exc}", + ) + ) + else: + statuses.append( + EvidenceLayerStatus( + key=spec.key, + title=spec.title, + classification=spec.classification, + interpretation=spec.interpretation, + available=True, + detail=detail, + manifest_path=manifest_path, + manifest_sha256=_sha256(manifest_path), + ) + ) + return tuple(statuses) + + +def evidence_layer_rows( + statuses: Sequence[EvidenceLayerStatus], +) -> tuple[Mapping[str, str], ...]: + """Return a deterministic display schema without changing decision state.""" + + return tuple( + { + "Evidence layer": status.title, + "Status": "Available" if status.available else "Unavailable", + "Classification": status.classification, + "Interpretation": status.interpretation, + "Validation": status.detail, + } + for status in statuses + ) + + +def _validate_declared_scenario_coverage(frame: pd.DataFrame) -> tuple[str, ...]: + """Validate that the artifact contains every predeclared sensitivity scenario.""" + + required = {"scenario", "declared_scenario_set", "declared_scenario_count"} + missing = required.difference(frame.columns) + if missing: + raise ValueError(f"benchmark artifact missing columns: {sorted(missing)}") + declarations = frame["declared_scenario_set"].dropna().astype(str).unique() + if len(declarations) != 1 or frame["declared_scenario_set"].isna().any(): + raise ValueError("benchmark rows do not share one declared scenario set") + try: + raw_declared = json.loads(declarations[0]) + except json.JSONDecodeError as exc: + raise ValueError("benchmark declared scenario set is malformed JSON") from exc + if ( + not isinstance(raw_declared, list) + or not raw_declared + or not all(isinstance(item, str) and item for item in raw_declared) + or len(raw_declared) != len(set(raw_declared)) + ): + raise ValueError("benchmark declared scenario set must be a nonempty unique string list") + declared = tuple(raw_declared) + counts = pd.to_numeric(frame["declared_scenario_count"], errors="coerce") + if counts.isna().any() or not counts.eq(len(declared)).all(): + raise ValueError("benchmark declared scenario count is inconsistent") + observed_values = frame["scenario"].dropna().astype(str) + if len(observed_values) != len(frame) or set(observed_values) != set(declared): + raise ValueError("benchmark rows do not cover the complete declared scenario set") + return declared + + +def load_benchmark_artifact(path: str | Path | None = None) -> BenchmarkArtifact | None: + """Load a generated benchmark, rejecting missing causal provenance labels.""" + + lineage_validated = path is None + if path is None: + directory = _project_root() / "artifacts" / "benchmarks" + incomplete = _project_root() / "artifacts" / "REPRODUCE_INCOMPLETE.json" + manifest = _project_root() / "artifacts" / "reproduce_manifest.json" + if incomplete.exists(): + raise ValueError( + "reproduction is marked incomplete; generated benchmark artifacts are unavailable" + ) + if not manifest.is_file(): + raise ValueError("top-level artifacts/reproduce_manifest.json is missing") + source = next( + (directory / name for name in _ARTIFACT_CANDIDATES if (directory / name).is_file()), + None, + ) + if source is None: + return None + _validate_reproduce_lineage(source) + else: + source = Path(path) + if not source.is_file(): + return None + + frame = pd.read_csv(source) + required = { + "declared_scenario_count", + "declared_scenario_set", + "design", + "estimator", + "target_estimand", + "bias", + "rmse", + "coverage", + "power", + "scenario", + "identified", + "inference_valid", + "fit_complete", + "applicable", + "attempted_fits", + "successful_fits", + "evidence_type", + } + missing = required.difference(frame.columns) + if missing: + raise ValueError(f"benchmark artifact missing columns: {sorted(missing)}") + if frame.empty: + raise ValueError("benchmark artifact is empty") + provenance = frame["evidence_type"].astype(str) + if not provenance.str.startswith("semi_synthetic").all(): + raise ValueError("dashboard causal benchmarks must be explicitly labelled semi-synthetic") + declared_scenarios = _validate_declared_scenario_coverage(frame) + return BenchmarkArtifact( + path=source.resolve(), + summary=frame, + declared_scenarios=declared_scenarios, + lineage_validated=lineage_validated, + ) + + +_SCENARIO_COLUMNS: Final[Mapping[str, tuple[str, ...]]] = { + "treatment_version": ("treatment_version", "intervention_version"), + "spillover_strength": ("spillover_strength",), + "persistence": ("persistence",), + "experiment_duration": ("duration", "experiment_duration", "n_periods"), + "n_zones": ("n_zones",), + "treatment_duration": ("treatment_duration", "block_length"), + "n_clusters": ("configured_geo_clusters", "n_clusters"), + "treatment_saturation": ("treatment_saturation", "saturation"), + "washout_periods": ("washout_periods", "washout"), + "incentive_size": ("incentive_size", "incentive_per_driver"), + "treatment_probability": ("treatment_probability", "assignment_probability"), +} + +_TEMPORAL_DESIGNS: Final[frozenset[str]] = frozenset( + {DesignName.TIME_BLOCK.value, DesignName.SWITCHBACK.value, DesignName.GEO_TIME.value} +) +_GEO_DESIGNS: Final[frozenset[str]] = frozenset( + {DesignName.GEO_CLUSTER.value, DesignName.GEO_TIME.value} +) + + +def match_benchmark_artifact( + artifact: BenchmarkArtifact, + controls: DashboardControls, +) -> tuple[pd.DataFrame, tuple[str, ...]]: + """Filter an artifact and report scenario dimensions absent from its metadata.""" + + frame = artifact.summary.loc[ + artifact.summary["target_estimand"].astype(str) == controls.target_estimand + ].copy() + missing_dimensions: list[str] = [] + for field, aliases in _SCENARIO_COLUMNS.items(): + column = next((candidate for candidate in aliases if candidate in frame.columns), None) + if column is None: + missing_dimensions.append(field) + continue + if field == "treatment_version": + version = artifact.summary[column].dropna().astype(str) + if version.empty: + missing_dimensions.append(field) + continue + expected_version = TreatmentVersion.parse(controls.treatment_version).value + normalized_version = ( + frame[column] + .astype(str) + .str.strip() + .str.lower() + .str.replace("-", "_", regex=False) + .str.replace(" ", "_", regex=False) + ) + frame = frame.loc[normalized_version == expected_version] + continue + artifact_numeric = pd.to_numeric(artifact.summary[column], errors="coerce") + if ( + field == "n_clusters" + and not artifact.summary["design"].astype(str).isin(_GEO_DESIGNS).any() + ): + # Cluster count is explicitly not applicable to purely temporal or + # individual assignment families. + continue + if not artifact_numeric.notna().any(): + missing_dimensions.append(field) + continue + numeric = pd.to_numeric(frame[column], errors="coerce") + if field == "n_clusters": + geo = frame["design"].astype(str).isin(_GEO_DESIGNS) + matches = ~geo | np.isclose(numeric, float(controls.n_clusters), rtol=1e-9, atol=1e-9) + elif field == "washout_periods": + temporal = frame["design"].astype(str).isin(_TEMPORAL_DESIGNS) + expected = np.where(temporal, controls.washout_periods, 0.0) + matches = np.isclose(numeric, expected, rtol=1e-9, atol=1e-9) + elif field == "n_zones": + expected = float(max(4, controls.n_clusters * 2)) + matches = np.isclose(numeric, expected, rtol=1e-9, atol=1e-9) + else: + expected = float(getattr(controls, field)) + matches = np.isclose(numeric, expected, rtol=1e-9, atol=1e-9) + frame = frame.loc[matches] + + budget = ( + pd.to_numeric(frame["budget"], errors="coerce") + if "budget" in frame + else pd.Series(np.nan, index=frame.index, dtype=float) + ) + finite_budget = np.isfinite(budget) + budget_matches = finite_budget & np.isclose( + budget, + float(controls.budget), + rtol=1e-9, + atol=1e-9, + ) + interpretable_budget = bool(finite_budget.any()) + if {"budget_scope", "nonbinding_budget_threshold"}.issubset(frame.columns): + threshold = pd.to_numeric(frame["nonbinding_budget_threshold"], errors="coerce") + if {"max_full_policy_spend", "max_realized_schedule_spend"}.issubset( + frame.columns + ): + local_threshold = pd.concat( + [ + pd.to_numeric(frame["max_full_policy_spend"], errors="coerce"), + pd.to_numeric(frame["max_realized_schedule_spend"], errors="coerce"), + ], + axis=1, + ).max(axis=1, skipna=True) + # Per-scenario/design maxima are both safer and less over-conservative + # than a global maximum driven by a different market geometry. The + # global threshold remains the fail-safe fallback for legacy artifacts. + threshold = local_threshold.where(np.isfinite(local_threshold), threshold) + scope = frame["budget_scope"].astype(str).str.lower() + certified_unconstrained = ( + ~finite_budget + & scope.str.contains("unconstrained", na=False) + & np.isfinite(threshold) + ) + interpretable_budget = interpretable_budget or bool(certified_unconstrained.any()) + budget_matches |= certified_unconstrained & ( + float(controls.budget) + 1e-9 >= threshold + ) + if not interpretable_budget: + missing_dimensions.append("budget") + frame = frame.loc[budget_matches] + return frame.reset_index(drop=True), tuple(dict.fromkeys(missing_dimensions)) + + +def artifact_decision( + artifact: BenchmarkArtifact, + controls: DashboardControls, +) -> ArtifactDecision | None: + """Return an identification-safe recommendation for the artifact's declared scenario.""" + + try: + declared_scenarios = _validate_declared_scenario_coverage(artifact.summary) + except ValueError: + return None + rows, missing = match_benchmark_artifact(artifact, controls) + if rows.empty or missing: + return None + matched_scenarios = tuple(sorted(rows["scenario"].dropna().astype(str).unique())) + unmatched_scenarios = tuple( + sorted(set(declared_scenarios).difference(matched_scenarios)) + ) + is_conditional = bool(unmatched_scenarios) + if is_conditional and not artifact.lineage_validated: + # A subset recommendation is safe only when the complete source artifact + # was tied to the current source/config tree by the top reproduction manifest. + return None + try: + recommendation = recommend_design( + rows, + controls, + require_declared_scenarios=not is_conditional, + ) + except ValueError: + return None + return ArtifactDecision( + rows=rows, + recommendation=recommendation, + missing_dimensions=missing, + recommendation_scope=( + "selected_scenario_conditional" + if is_conditional + else "declared_sensitivity_set" + ), + matched_scenarios=matched_scenarios, + unmatched_scenarios=unmatched_scenarios, + ) + + +def _format_number(value: Any, *, digits: int = 3) -> str: + if value is None: + return "—" + try: + numeric = float(value) + except (TypeError, ValueError): + return str(value) + if not np.isfinite(numeric): + return "—" + return f"{numeric:,.{digits}f}" + + +def _recommended_design_caveat(decision: ArtifactDecision) -> str: + """Build the caveat shown alongside the artifact-recommended design.""" + + design = DesignName.parse(str(decision.recommendation["design"])).value + return f"Recommended-design caveat ({DESIGN_LABELS[design]}): {design_limitations(design)}" + + +def _same_dashboard_controls(left: object, right: DashboardControls) -> bool: + """Compare cached controls across Streamlit script-class reloads.""" + + try: + return all( + getattr(left, field) == getattr(right, field) + for field in DashboardControls.__dataclass_fields__ + ) + except AttributeError: + return False + + +def _render_controls(st: Any) -> DashboardControls: + defaults = DashboardControls() + st.sidebar.header("Experiment scenario") + design = st.sidebar.selectbox( + "Randomization unit", + options=SUPPORTED_DESIGNS, + index=SUPPORTED_DESIGNS.index(defaults.randomization_unit), + format_func=lambda value: DESIGN_LABELS[value], + ) + treatment_version = st.sidebar.selectbox( + "Treatment version", + options=tuple(version.value for version in TreatmentVersion), + index=tuple(version.value for version in TreatmentVersion).index( + defaults.treatment_version + ), + format_func=lambda value: TREATMENT_VERSION_LABELS[value], + ) + duration = int( + st.sidebar.slider( + "Experiment duration (periods)", + 12, + 168, + defaults.experiment_duration, + step=4, + ) + ) + clusters = int( + st.sidebar.slider( + "Geographic clusters", + 2, + 16, + defaults.n_clusters, + help=( + "Controls independent geographic assignment groups for geo designs. " + "For individual or temporal designs it controls simulated market size, not " + "their effective randomized-unit count." + ), + ) + ) + spillover = float( + st.sidebar.slider( + "Neighbor spillover strength", 0.0, 0.6, defaults.spillover_strength, 0.05 + ) + ) + persistence = float( + st.sidebar.slider("Persistence", 0.0, 0.9, defaults.persistence, 0.05) + ) + incentive = float( + st.sidebar.number_input( + "Driver incentive per treated driver (driver/bundled)", + 0.0, + 10.0, + defaults.incentive_size, + 0.5, + ) + ) + budget = float( + st.sidebar.number_input( + "Experiment budget", 0.0, 100_000.0, defaults.budget, 500.0 + ) + ) + + with st.sidebar.expander("Assignment details"): + max_block = max(1, duration // 2) + block = int( + st.slider( + "Treatment block duration", + 1, + max_block, + min(defaults.treatment_duration, max_block), + ) + ) + washout = int( + st.slider( + "Washout periods", + 0, + max(0, block - 1), + min(defaults.washout_periods, block - 1), + ) + ) + saturation = float( + st.slider( + "Treatment saturation", + 0.1, + 1.0, + defaults.treatment_saturation, + 0.05, + ) + ) + treatment_probability = float( + st.slider( + "Treatment probability", + 0.1, + 0.9, + defaults.treatment_probability, + 0.05, + ) + ) + replications = int( + st.slider("Scenario replications", 2, 100, defaults.replications, 1) + ) + seed = int( + st.number_input("Deterministic seed", 0, 2**31 - 1, defaults.seed, 1) + ) + + return DashboardControls( + randomization_unit=design, + treatment_version=treatment_version, + experiment_duration=duration, + n_clusters=clusters, + spillover_strength=spillover, + persistence=persistence, + incentive_size=incentive, + budget=budget, + treatment_duration=block, + washout_periods=washout, + treatment_saturation=saturation, + treatment_probability=treatment_probability, + replications=replications, + seed=seed, + ) + + +def _render_estimand(st: Any, controls: DashboardControls) -> None: + definition = get_estimand(controls.target_estimand) + registry_compatible = controls.randomization_unit in definition.compatible_designs + implemented_reasons: list[str] = [] + if controls.randomization_unit == DesignName.INDIVIDUAL.value: + implemented_reasons.append( + "individual assignment does not target a connected market's full-policy total effect" + ) + if controls.spillover_strength > 0 and controls.randomization_unit in { + DesignName.GEO_CLUSTER.value, + DesignName.GEO_TIME.value, + }: + implemented_reasons.append( + "the displayed assignment regression has no modeled neighbor-exposure term or " + "isolated-market contrast" + ) + if controls.persistence > 0 and controls.randomization_unit in _TEMPORAL_DESIGNS: + implemented_reasons.append( + "the displayed assignment regression has no treatment-history or carryover term" + ) + st.subheader("Pre-specified target estimand") + st.markdown(f"**{definition.label}** (`{definition.name.value}`) ") + st.write(definition.contrast) + st.caption( + f"Unit: {definition.unit}. Registry-level design compatibility: " + f"{'compatible' if registry_compatible else 'incompatible'}. This registry screen is " + "theoretical and is not evidence that the implemented estimator identifies the target." + ) + if implemented_reasons: + st.error( + "Implemented target-identification check fails for this scenario: " + + "; ".join(implemented_reasons) + + "." + ) + else: + st.warning( + "The on-demand estimator is displayed only as an assignment diagnostic. Target " + "identification and inferential validity must come from an exact-scenario benchmark " + "row that passes all artifact safety gates." + ) + + +def _render_evidence_layers(st: Any) -> None: + statuses = load_evidence_layers() + st.subheader("Evidence layers") + st.caption( + "Read-only provenance view. Availability requires the current source/config hash, " + "top-manifest bytes and SHA-256, and every child-manifest scientific and file-hash " + "gate. These layers do not alter the design recommendation." + ) + st.dataframe( + pd.DataFrame(evidence_layer_rows(statuses)), + use_container_width=True, + hide_index=True, + ) + + +def _best_artifact_row( + decision: ArtifactDecision, + controls: DashboardControls, + design: str, +) -> pd.Series | None: + candidates = decision.rows.loc[decision.rows["design"].astype(str) == design] + if candidates.empty: + return None + try: + return recommend_design( + candidates, + controls, + require_declared_scenarios=( + decision.recommendation_scope != "selected_scenario_conditional" + ), + ) + except ValueError: + return None + + +def _render_artifact_status( + st: Any, + controls: DashboardControls, +) -> ArtifactDecision | None: + try: + artifact = load_benchmark_artifact() + except ValueError as exc: + st.error(f"Generated benchmark artifact was rejected: {exc}") + return None + if artifact is None: + st.info( + "No generated benchmark artifact is available for this scenario. " + "Bias, uncertainty, power, and a benchmark-ranked recommendation remain unavailable; " + "the dashboard will not invent them." + ) + return None + matched_rows, missing_dimensions = match_benchmark_artifact(artifact, controls) + decision = artifact_decision(artifact, controls) + if decision is None: + if missing_dimensions: + st.info( + f"Benchmark artifact `{artifact.path.name}` cannot support this dashboard " + "scenario because it omits causally relevant dimensions: " + f"{', '.join(missing_dimensions)}. Recovery benchmarks with an unconstrained " + "budget are not reused for a binding-budget decision." + ) + elif matched_rows.empty: + st.info( + f"Benchmark artifact `{artifact.path.name}` contains no exact row for all " + "declared scenario controls." + ) + else: + st.info( + f"Benchmark artifact `{artifact.path.name}` has exact scenario rows, but none " + "passes identification, inference-validity, complete-fit, finite-metric, and " + "coverage gates." + ) + return None + if decision.missing_dimensions: + st.warning( + f"`{artifact.path.name}` matches available fields but omits scenario metadata for: " + f"{', '.join(decision.missing_dimensions)}. Its inferential metrics and recommendation " + "are conditional on the artifact's declared scenario, not an exact match to every " + "dashboard control." + ) + else: + if decision.recommendation_scope == "selected_scenario_conditional": + st.warning( + f"Loaded an exact-control benchmark subset from `{artifact.path.name}`. The " + "recommendation is conditional on the matched scenario(s), not robust across " + "the artifact's full declared sensitivity set. Matched: " + f"{', '.join(decision.matched_scenarios)}. Unmatched mechanisms/scenarios: " + f"{', '.join(decision.unmatched_scenarios)}." + ) + else: + st.success( + f"Loaded an exact-scenario generated benchmark covering its full declared " + f"sensitivity set: `{artifact.path.name}`" + ) + if "nonbinding_budget_threshold" in decision.rows: + threshold = float( + pd.to_numeric(decision.rows["nonbinding_budget_threshold"], errors="coerce").max() + ) + st.caption( + f"The recovery run disabled budget enforcement, but its recorded maximum " + f"treatment spend was {_format_number(threshold, digits=0)} at the same incentive " + f"dose. The selected budget {_format_number(controls.budget, digits=0)} is at or " + "above that conservative nonbinding threshold." + ) + with st.expander("Generated benchmark artifact rows"): + st.dataframe(decision.rows, use_container_width=True, hide_index=True) + return decision + + +def _render_result( + st: Any, + scenario: ScenarioBenchmark, + benchmark_decision: ArtifactDecision | None, +) -> None: + selected = scenario.selected + st.markdown( + "> **Evidence separation:** on-demand values below are structural simulator " + "counterfactuals with known truth. The calibration uses descriptive public-trip moments; " + "it does not identify any treatment, spillover, persistence, or dose-response parameter." + ) + + st.subheader("Validated Monte Carlo benchmark evidence") + selected_artifact = ( + _best_artifact_row( + benchmark_decision, + scenario.controls, + scenario.controls.randomization_unit, + ) + if benchmark_decision is not None + else None + ) + inference = st.columns(3) + if selected_artifact is None: + inference[0].metric("Estimated bias", "Unavailable") + inference[1].metric("Estimated uncertainty", "Unavailable") + inference[2].metric("Estimated power", "Unavailable") + st.caption( + "No identified generated benchmark row matches the selected design and recorded " + "scenario fields. On-demand assignment diagnostics are not relabelled as bias or " + "power for the market-total target." + ) + else: + inference[0].metric("Estimated bias", _format_number(selected_artifact["bias"])) + inference[1].metric( + "Mean standard error", + _format_number(selected_artifact.get("mean_std_error")), + ) + inference[2].metric( + "Estimated power", + _format_number(selected_artifact["power"], digits=3), + ) + st.caption( + f"Artifact estimator `{selected_artifact['estimator']}`; bias MCSE " + f"{_format_number(selected_artifact.get('bias_mcse'))}; " + f"{int(selected_artifact.get('replications', 0)) or '—'} replications; " + f"evidence `{selected_artifact['evidence_type']}`." + ) + + st.subheader("On-demand full-policy structural scenario") + st.caption( + f"Treatment version: {TREATMENT_VERSION_LABELS[str(selected['treatment_version'])]}. " + "Only the declared market-side pathways and costs are active." + ) + structural = st.columns(4) + structural[0].metric( + "Target effect per zone-period", + _format_number(selected["full_policy_truth"]), + ) + structural[1].metric( + "Expected incremental trips", + _format_number(selected["expected_incremental_outcome"], digits=1), + ) + structural[2].metric( + "Full-policy spend", + _format_number(selected["mean_full_policy_spend"], digits=0), + ) + structural[3].metric( + "Incremental trips per dollar", + _format_number(selected["budget_efficiency"], digits=4), + ) + welfare = st.columns(2) + welfare[0].metric( + "Modeled incremental welfare", + _format_number(selected["modeled_incremental_welfare"], digits=1), + ) + welfare[1].metric( + "Modeled welfare per dollar", + _format_number(selected["modeled_welfare_per_dollar"], digits=4), + ) + st.caption( + f"Averages over {int(selected['replications'])} configured simulator draws. Incremental " + f"outcome MC SD: {_format_number(selected['incremental_outcome_mc_sd'])}; mean full-policy " + f"budget scale: {_format_number(selected['mean_full_policy_budget_scale'])}. The numerator " + "and denominator both use the feasible all-zone policy, never the mixed experiment path." + ) + st.caption( + "Welfare is an incomplete modeled construct using configured rider value, operating cost, " + "wait disutility, and transfers. It omits distributional weights and unmodeled externalities." + ) + + st.subheader("Conditional experiment recommendation") + if benchmark_decision is None: + st.warning( + "No benchmark-supported design recommendation is available. Generate an identified " + "Monte Carlo artifact for the declared estimand before choosing a launch design." + ) + else: + recommendation = benchmark_decision.recommendation + recommendation_text = ( + f"For the exactly matched scenario, conditionally prefer " + f"**{DESIGN_LABELS[str(recommendation['design'])]}** with " + f"`{recommendation['estimator']}` for `{scenario.controls.target_estimand}`. " + "This is not a sensitivity-robust recommendation. Unmatched declared " + f"mechanisms/scenarios: {', '.join(benchmark_decision.unmatched_scenarios)}." + if benchmark_decision.recommendation_scope + == "selected_scenario_conditional" + else f"Across the artifact's full declared sensitivity set, prefer " + f"**{DESIGN_LABELS[str(recommendation['design'])]}** with " + f"`{recommendation['estimator']}` for `{scenario.controls.target_estimand}`." + ) + st.success(recommendation_text) + st.warning(_recommended_design_caveat(benchmark_decision)) + qualifier = ( + " Missing dashboard dimensions: " + + ", ".join(benchmark_decision.missing_dimensions) + + "." + if benchmark_decision.missing_dimensions + else "" + ) + st.caption( + "The ranking minimizes generated RMSE with a coverage penalty after excluding " + f"unidentified and estimand-incompatible rows. Recommendation scope: " + f"`{benchmark_decision.recommendation_scope}`.{qualifier}" + ) + + st.subheader("Observed assignment diagnostic — not the target estimand") + diagnostic = st.columns(4) + diagnostic[0].metric( + "Mean assignment coefficient", + _format_number(selected["mean_assignment_estimate"]), + ) + diagnostic[1].metric( + "Mean assignment SE", + _format_number(selected["mean_assignment_std_error"]), + ) + diagnostic[2].metric( + "Assignment coefficient MC SD", + _format_number(selected["assignment_estimate_mc_sd"]), + ) + diagnostic[3].metric( + "Null-rejection diagnostic", + _format_number(selected["assignment_rejection_rate"], digits=3), + ) + st.warning( + "This coefficient generally does not equal the feasible full-policy market-total effect " + "under interference, carryover, nonlinear saturation, washout filtering, or a binding " + "shared budget. Its coefficient-minus-truth gap is therefore not reported as bias, and " + "its rejection rate is not reported as power for the target estimand." + ) + st.caption( + f"Effective randomized clusters/units recorded by the estimator: " + f"{int(selected['effective_clusters'])}. The geographic-cluster control changes this " + "count only for geo-randomized designs." + ) + + st.subheader("Limitations and decision guardrails") + for limitation in scenario.limitations: + st.markdown(f"- {limitation}") + + with st.expander("Reproducibility metadata"): + st.json( + { + "evidence_type": scenario.evidence_type, + "target_estimand": scenario.controls.target_estimand, + "calibration_path": ( + str(scenario.calibration_path) if scenario.calibration_path else None + ), + "calibration_sha256": scenario.calibration_sha256, + "controls": { + field: getattr(scenario.controls, field) + for field in scenario.controls.__dataclass_fields__ + }, + } + ) + + +def render_dashboard() -> None: + """Render the Streamlit app; importing this module never starts the UI.""" + + try: + import streamlit as st + except ImportError as exc: # pragma: no cover - depends on optional installation + raise RuntimeError( + "The dashboard extra is not installed. Install the project with '[dashboard]'." + ) from exc + + st.set_page_config(page_title="Causal Marketplace Lab", page_icon="🧪", layout="wide") + st.title("Causal Marketplace Lab") + st.write( + "Stress-test marketplace experiment designs under configurable interference, " + "persistence, and incentive budgets." + ) + _render_evidence_layers(st) + controls = _render_controls(st) + _render_estimand(st, controls) + benchmark_decision = _render_artifact_status(st, controls) + + run = st.button("Run on-demand structural scenario", type="primary") + if run: + with st.spinner( + f"Generating {controls.replications} deterministic-seed draws for " + f"{DESIGN_LABELS[controls.randomization_unit]}…" + ): + try: + scenario = run_scenario_benchmark(controls) + except (ValueError, RuntimeError) as exc: + st.error(f"Scenario could not be estimated: {exc}") + else: + st.session_state["casuallab_scenario"] = scenario + cached = st.session_state.get("casuallab_scenario") + if cached is not None and hasattr(cached, "controls") and hasattr(cached, "summary"): + if not _same_dashboard_controls(cached.controls, controls): + st.warning( + "Controls changed after the prior run. Cached structural results and the current " + "artifact recommendation are hidden until you rerun this scenario." + ) + else: + _render_result(st, cached, benchmark_decision) + + +def main() -> None: + """Console-friendly entry point used by ``streamlit run`` and tests.""" + + render_dashboard() + + +if __name__ == "__main__": # pragma: no cover - Streamlit execution path + main() diff --git a/CasualLab/src/casuallab/data.py b/CasualLab/src/casuallab/data.py new file mode 100644 index 0000000000000000000000000000000000000000..1b0f85bfe326aea744f974171b136c98d61800b4 --- /dev/null +++ b/CasualLab/src/casuallab/data.py @@ -0,0 +1,2492 @@ +"""Reproducible ingestion and panel construction for public ride-hail trips. + +The small-data vertical slice uses a committed, provenance-documented extract from +Chicago's legacy TNP trip dataset. The NYC adapter targets TLC's monthly HVFHV +Parquet files. This module intentionally keeps measurement-quality flags in the +cleaned data: Chicago timestamps, fares, and tips are reported on rounded grids, +and missing census tracts may reflect privacy suppression or out-of-city travel. +""" + +from __future__ import annotations + +import csv +import hashlib +import json +import os +import re +import shutil +import tempfile +from calendar import monthrange +from collections.abc import Callable, Iterable, Mapping, Sequence +from dataclasses import asdict, dataclass, fields +from datetime import UTC, date, datetime, timedelta +from pathlib import Path +from typing import Any, BinaryIO, Literal, TypeAlias +from urllib.parse import urlencode +from urllib.request import urlopen + +import duckdb +import polars as pl +import pyarrow.parquet as pq +import yaml + +Source = Literal["chicago_tnp", "nyc_hvfhv"] +Mode = Literal["sample", "full"] +PathLike: TypeAlias = str | os.PathLike[str] +FrameInput: TypeAlias = pl.DataFrame | PathLike | Sequence[PathLike] + +SCHEMA_VERSION = "1.0.0" +CHICAGO_DATASET_ID = "m6dm-c72p" +CHICAGO_API_ROOT = "https://data.cityofchicago.org/resource" +CHICAGO_DATASET_PAGE = ( + "https://data.cityofchicago.org/Transportation/" + "Transportation-Network-Providers-Trips-2018-2022-/m6dm-c72p" +) +NYC_HVFHV_BASE_URL = "https://d37ci6vzurychx.cloudfront.net/trip-data" +NYC_TLC_TRIP_RECORD_PAGE = "https://www.nyc.gov/site/tlc/about/tlc-trip-record-data.page" +CHICAGO_SAMPLE_HOURS = tuple(range(0, 24, 2)) +MISSING_ZONE_ID = "__MISSING_OR_OUTSIDE__" + +CHICAGO_COLUMNS = ( + "trip_id", + "trip_start_timestamp", + "trip_end_timestamp", + "trip_seconds", + "trip_miles", + "pickup_census_tract", + "dropoff_census_tract", + "pickup_community_area", + "dropoff_community_area", + "fare", + "tip", + "additional_charges", + "trip_total", + "shared_trip_authorized", + "trips_pooled", + "pickup_centroid_latitude", + "pickup_centroid_longitude", + "dropoff_centroid_latitude", + "dropoff_centroid_longitude", +) + +CHICAGO_RAW_SCHEMA = pl.Schema( + { + "trip_id": pl.String, + "trip_start_timestamp": pl.String, + "trip_end_timestamp": pl.String, + "trip_seconds": pl.Int64, + "trip_miles": pl.Float64, + "pickup_census_tract": pl.String, + "dropoff_census_tract": pl.String, + "pickup_community_area": pl.Int64, + "dropoff_community_area": pl.Int64, + "fare": pl.Float64, + "tip": pl.Float64, + "additional_charges": pl.Float64, + "trip_total": pl.Float64, + "shared_trip_authorized": pl.Boolean, + "trips_pooled": pl.Int64, + "pickup_centroid_latitude": pl.Float64, + "pickup_centroid_longitude": pl.Float64, + "dropoff_centroid_latitude": pl.Float64, + "dropoff_centroid_longitude": pl.Float64, + } +) + +NYC_HVFHV_RAW_SCHEMA = pl.Schema( + { + "hvfhs_license_num": pl.String, + "dispatching_base_num": pl.String, + "originating_base_num": pl.String, + "request_datetime": pl.Datetime("us"), + "on_scene_datetime": pl.Datetime("us"), + "pickup_datetime": pl.Datetime("us"), + "dropoff_datetime": pl.Datetime("us"), + "PULocationID": pl.Int64, + "DOLocationID": pl.Int64, + "trip_miles": pl.Float64, + "trip_time": pl.Int64, + "base_passenger_fare": pl.Float64, + "tolls": pl.Float64, + "bcf": pl.Float64, + "sales_tax": pl.Float64, + "congestion_surcharge": pl.Float64, + "airport_fee": pl.Float64, + "tips": pl.Float64, + "driver_pay": pl.Float64, + "shared_request_flag": pl.String, + "shared_match_flag": pl.String, + "access_a_ride_flag": pl.String, + "wav_request_flag": pl.String, + "wav_match_flag": pl.String, + # Added to TLC trip records in 2025; normalization treats it as optional. + "cbd_congestion_fee": pl.Float64, + } +) + +CLEAN_TRIP_SCHEMA = pl.Schema( + { + "source": pl.String, + "source_dataset_id": pl.String, + "trip_id": pl.String, + "record_id_is_surrogate": pl.Boolean, + "provider_id": pl.String, + "dispatching_base_id": pl.String, + "request_datetime": pl.Datetime("us"), + "pickup_datetime": pl.Datetime("us"), + "dropoff_datetime": pl.Datetime("us"), + "pickup_datetime_utc": pl.Datetime("us", "UTC"), + "dropoff_datetime_utc": pl.Datetime("us", "UTC"), + "source_timezone": pl.String, + "service_date": pl.Date, + "service_year": pl.Int32, + "service_month": pl.Int8, + "service_day_of_week": pl.Int8, + "pickup_zone_id": pl.String, + "dropoff_zone_id": pl.String, + "zone_type": pl.String, + "pickup_census_tract": pl.String, + "dropoff_census_tract": pl.String, + "trip_seconds": pl.Int64, + "trip_miles": pl.Float64, + "fare": pl.Float64, + "tips": pl.Float64, + "tolls": pl.Float64, + "taxes_and_surcharges": pl.Float64, + "additional_charges": pl.Float64, + "total_amount": pl.Float64, + "driver_pay": pl.Float64, + "airport_fee": pl.Float64, + "shared_requested": pl.Boolean, + "shared_matched": pl.Boolean, + "trips_pooled": pl.Int64, + "airport_trip": pl.Boolean, + "pickup_zone_missing": pl.Boolean, + "dropoff_zone_missing": pl.Boolean, + "pickup_census_tract_missing_or_suppressed": pl.Boolean, + "dropoff_census_tract_missing_or_suppressed": pl.Boolean, + "reported_timestamp_rounding_minutes": pl.Int16, + "reported_fare_rounding_increment": pl.Float64, + "reported_tip_rounding_increment": pl.Float64, + "pickup_on_15_minute_grid": pl.Boolean, + "fare_on_declared_grid": pl.Boolean, + } +) + +REQUIRED_RAW_COLUMNS: dict[Source, frozenset[str]] = { + "chicago_tnp": frozenset( + { + "trip_id", + "trip_start_timestamp", + "trip_end_timestamp", + "trip_seconds", + "trip_miles", + "pickup_community_area", + "dropoff_community_area", + "fare", + } + ), + "nyc_hvfhv": frozenset( + { + "hvfhs_license_num", + "pickup_datetime", + "dropoff_datetime", + "PULocationID", + "DOLocationID", + "trip_miles", + "trip_time", + "base_passenger_fare", + } + ), +} + +SOURCE_METADATA: dict[Source, dict[str, Any]] = { + "chicago_tnp": { + "publisher": "City of Chicago", + "dataset_id": CHICAGO_DATASET_ID, + "dataset_page": CHICAGO_DATASET_PAGE, + "timezone": "America/Chicago", + "known_measurement": { + "timestamps": "rounded to nearest 15 minutes", + "fare": "rounded to nearest $2.50", + "tips": "rounded to nearest $1.00", + "census_tracts": "may be suppressed; blanks also occur outside Chicago", + "airport_activity": ( + "left unknown when a missing endpoint prevents ruling airport activity in or out" + ), + }, + }, + "nyc_hvfhv": { + "publisher": "New York City Taxi and Limousine Commission", + "dataset_page": NYC_TLC_TRIP_RECORD_PAGE, + "timezone": "America/New_York", + "known_measurement": { + "schema": "monthly HVFHV Parquet; cbd_congestion_fee is optional pre-2025", + "census_tracts": "not published in the monthly HVFHV trip schema", + }, + }, +} + + +@dataclass(frozen=True, slots=True) +class DataConfig: + """Validated data-pipeline configuration. + + Relative paths are resolved by :func:`load_data_config` against ``project_root``. + Direct construction leaves path resolution to the caller, which is convenient in + tests and programmatic use. + """ + + source: Source = "chicago_tnp" + mode: Mode = "sample" + project_root: Path = Path(".") + fixture_path: Path | None = None + raw_dir: Path = Path("data/raw") + clean_dir: Path = Path("data/clean") + panel_dir: Path = Path("data/panel") + manifest_path: Path = Path("data/manifest.json") + diagnostics_path: Path = Path("data/diagnostics.json") + sample_rows: int = 300 + start_datetime: str | None = "2022-01-01T00:00:00" + end_datetime: str | None = "2022-01-01T22:00:00" + chicago_dataset_id: str = CHICAGO_DATASET_ID + nyc_year: int = 2024 + nyc_months: tuple[int, ...] = (1,) + # Spread four valid-in-every-month dates across both the month and weekdays. + nyc_sample_days: tuple[int, ...] = (1, 10, 19, 28) + nyc_sample_hours: tuple[int, ...] = tuple(range(24)) + nyc_batch_rows: int = 100_000 + nyc_expected_rows: int | None = None + nyc_expected_bytes: int | None = None + nyc_expected_sha256: str | None = None + panel_frequency: str = "15m" + complete_panel_grid: bool = False + partition_by: tuple[str, ...] = ("source", "service_year", "service_month") + page_size: int = 50_000 + max_pages: int | None = None + timeout_seconds: int = 120 + + def __post_init__(self) -> None: + source = _canonical_source(self.source) + object.__setattr__(self, "source", source) + if self.mode not in {"sample", "full"}: + raise ValueError("mode must be 'sample' or 'full'") + if self.sample_rows < 1: + raise ValueError("sample_rows must be positive") + if not 2009 <= self.nyc_year <= 2100: + raise ValueError("nyc_year is outside the supported range") + if not self.nyc_months or any(month not in range(1, 13) for month in self.nyc_months): + raise ValueError("nyc_months must contain integers from 1 through 12") + if len(set(self.nyc_months)) != len(self.nyc_months): + raise ValueError("nyc_months must not contain duplicates") + if not self.nyc_sample_days or len(set(self.nyc_sample_days)) != len( + self.nyc_sample_days + ): + raise ValueError("nyc_sample_days must contain unique calendar days") + if any(day < 1 for day in self.nyc_sample_days): + raise ValueError("nyc_sample_days must be positive") + if not self.nyc_sample_hours or any( + hour not in range(24) for hour in self.nyc_sample_hours + ): + raise ValueError("nyc_sample_hours must contain hours from 0 through 23") + if len(set(self.nyc_sample_hours)) != len(self.nyc_sample_hours): + raise ValueError("nyc_sample_hours must not contain duplicates") + if self.nyc_batch_rows < 1: + raise ValueError("nyc_batch_rows must be positive") + if self.nyc_expected_rows is not None and self.nyc_expected_rows < 1: + raise ValueError("nyc_expected_rows must be positive when supplied") + if self.nyc_expected_bytes is not None and self.nyc_expected_bytes < 1: + raise ValueError("nyc_expected_bytes must be positive when supplied") + if self.nyc_expected_sha256 is not None: + normalized_sha = self.nyc_expected_sha256.lower() + if re.fullmatch(r"[0-9a-f]{64}", normalized_sha) is None: + raise ValueError("nyc_expected_sha256 must be a 64-character SHA-256") + object.__setattr__(self, "nyc_expected_sha256", normalized_sha) + has_exact_nyc_expectation = any( + value is not None + for value in ( + self.nyc_expected_rows, + self.nyc_expected_bytes, + self.nyc_expected_sha256, + ) + ) + if has_exact_nyc_expectation and not ( + self.source == "nyc_hvfhv" and self.mode == "full" + ): + raise ValueError("NYC exact raw expectations are only valid in NYC full mode") + if has_exact_nyc_expectation and len(self.nyc_months) != 1: + raise ValueError("NYC exact raw expectations require exactly one configured month") + if self.source == "nyc_hvfhv" and self.mode == "sample": + if len(self.nyc_months) != 1: + raise ValueError("NYC sample mode requires exactly one configured month") + month = self.nyc_months[0] + maximum_day = monthrange(self.nyc_year, month)[1] + if any(day > maximum_day for day in self.nyc_sample_days): + raise ValueError( + "nyc_sample_days contains a day outside the configured month" + ) + strata = len(self.nyc_sample_days) * len(self.nyc_sample_hours) + if self.sample_rows < strata: + raise ValueError( + "NYC sample_rows must be at least the number of configured day-hour strata" + ) + if self.page_size < 1 or self.page_size > 50_000: + raise ValueError("page_size must be between 1 and Socrata's 50,000-row limit") + if self.max_pages is not None and self.max_pages < 1: + raise ValueError("max_pages must be positive when supplied") + if not self.partition_by: + raise ValueError("partition_by must contain at least one column") + + def as_serializable_dict(self) -> dict[str, Any]: + """Return a portable JSON-safe representation for manifests. + + Paths below ``project_root`` are stored relative to it, and the root itself + is represented by ``.``. Paths outside the project (possible in tests or an + explicitly shared cache) remain absolute so their identity is not obscured. + """ + + payload = asdict(self) + root = self.project_root.resolve() + payload["project_root"] = "." + if self.mode == "full": + # These fields configure bounded engineering samples only. Keeping their + # dataclass defaults is API-compatible, but serializing numeric values in + # a full-data manifest would falsely imply a row or stratum bound. + payload["sample_rows"] = None + payload["nyc_sample_days"] = None + payload["nyc_sample_hours"] = None + for key in ( + "fixture_path", + "raw_dir", + "clean_dir", + "panel_dir", + "manifest_path", + "diagnostics_path", + ): + value = payload[key] + if value is None: + continue + path = Path(value).resolve() + try: + payload[key] = str(path.relative_to(root)) + except ValueError: + payload[key] = str(path) + return _json_safe(payload) + + +@dataclass(frozen=True, slots=True) +class PipelineArtifacts: + """Paths and row counts produced by :func:`run_data_pipeline`.""" + + raw_files: tuple[Path, ...] + clean_files: tuple[Path, ...] + panel_files: tuple[Path, ...] + od_flow_files: tuple[Path, ...] + manifest_path: Path + diagnostics_path: Path + trip_rows: int + panel_rows: int + + +def _canonical_source(source: str) -> Source: + aliases = { + "chicago": "chicago_tnp", + "chicago_tnp": "chicago_tnp", + "nyc": "nyc_hvfhv", + "hvfhv": "nyc_hvfhv", + "nyc_hvfhv": "nyc_hvfhv", + } + try: + return aliases[source.lower()] # type: ignore[return-value] + except KeyError as exc: + raise ValueError(f"unsupported data source: {source!r}") from exc + + +def load_data_config(path: PathLike) -> DataConfig: + """Load a YAML data config and resolve all relative paths reproducibly. + + ``project_root`` is resolved relative to the YAML file. Other relative paths + are then resolved relative to that root, not the caller's working directory. + Unknown keys fail fast so configuration typos cannot silently change a run. + """ + + config_path = Path(path).expanduser().resolve() + raw = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {} + if not isinstance(raw, Mapping): + raise TypeError("data configuration must be a YAML mapping") + if "data" in raw: + raw = raw["data"] + if not isinstance(raw, Mapping): + raise TypeError("the YAML 'data' value must be a mapping") + values = dict(raw) + if values.get("mode") == "full" and "sample_rows" in values: + raise ValueError( + "sample_rows does not bound full mode; remove it and use explicit full-data opt-in" + ) + allowed = {field.name for field in fields(DataConfig)} + unknown = sorted(set(values) - allowed) + if unknown: + raise ValueError(f"unknown data configuration keys: {', '.join(unknown)}") + + project_value = Path(values.get("project_root", ".")).expanduser() + project_root = ( + project_value.resolve() + if project_value.is_absolute() + else (config_path.parent / project_value).resolve() + ) + values["project_root"] = project_root + for key in ( + "fixture_path", + "raw_dir", + "clean_dir", + "panel_dir", + "manifest_path", + "diagnostics_path", + ): + if key not in values or values[key] is None: + continue + value = Path(values[key]).expanduser() + values[key] = value if value.is_absolute() else project_root / value + if "nyc_months" in values: + values["nyc_months"] = tuple(int(month) for month in values["nyc_months"]) + if "nyc_sample_days" in values: + values["nyc_sample_days"] = tuple(int(day) for day in values["nyc_sample_days"]) + if "nyc_sample_hours" in values: + values["nyc_sample_hours"] = tuple(int(hour) for hour in values["nyc_sample_hours"]) + if "partition_by" in values: + values["partition_by"] = tuple(str(column) for column in values["partition_by"]) + return DataConfig(**values) + + +def chicago_query_url(config: DataConfig) -> str: + """Build the deterministic Socrata CSV query for a Chicago extraction.""" + + clauses: list[str] = [] + if config.start_datetime: + clauses.append(f"trip_start_timestamp >= '{config.start_datetime}'") + if config.end_datetime: + clauses.append(f"trip_start_timestamp <= '{config.end_datetime}'") + query: dict[str, str | int] = { + "$select": ",".join(CHICAGO_COLUMNS), + "$order": "trip_start_timestamp,trip_id", + } + if clauses: + query["$where"] = " and ".join(clauses) + if config.mode == "sample": + query["$limit"] = config.sample_rows + return f"{CHICAGO_API_ROOT}/{config.chicago_dataset_id}.csv?{urlencode(query)}" + + +def chicago_sample_urls(config: DataConfig) -> tuple[str, ...]: + """Build deterministic hourly-stratum URLs for the Chicago sample. + + The total requested rows equals ``sample_rows``. Rows are distributed over + twelve even-numbered local hours and ordered by ``trip_id`` within each hour, + preventing a 300-row sample from collapsing into a single busy 15-minute cell. + """ + + if not config.start_datetime: + raise ValueError("Chicago sample mode requires start_datetime to select a service date") + service_date = config.start_datetime[:10] + base, remainder = divmod(config.sample_rows, len(CHICAGO_SAMPLE_HOURS)) + urls: list[str] = [] + for index, hour in enumerate(CHICAGO_SAMPLE_HOURS): + limit = base + (1 if index < remainder else 0) + if limit == 0: + continue + timestamp = f"{service_date}T{hour:02d}:00:00" + query: dict[str, str | int] = { + "$select": ",".join(CHICAGO_COLUMNS), + "$where": f"trip_start_timestamp = '{timestamp}'", + "$order": "trip_id", + "$limit": limit, + } + urls.append(f"{CHICAGO_API_ROOT}/{config.chicago_dataset_id}.csv?{urlencode(query)}") + return tuple(urls) + + +def nyc_hvfhv_urls(config: DataConfig) -> tuple[str, ...]: + """Return official TLC monthly HVFHV Parquet URLs in chronological order.""" + + return tuple( + f"{NYC_HVFHV_BASE_URL}/fhvhv_tripdata_{config.nyc_year}-{month:02d}.parquet" + for month in sorted(config.nyc_months) + ) + + +def sha256_file(path: PathLike, *, chunk_size: int = 1 << 20) -> str: + """Compute a file SHA-256 without loading it into memory.""" + + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for chunk in iter(lambda: handle.read(chunk_size), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _copy_if_changed(source: Path, destination: Path) -> Path: + destination.parent.mkdir(parents=True, exist_ok=True) + if destination.exists() and sha256_file(source) == sha256_file(destination): + return destination + temporary = destination.with_name(f".{destination.name}.tmp") + shutil.copyfile(source, temporary) + temporary.replace(destination) + return destination + + +def _download_url( + url: str, + destination: Path, + *, + timeout: int, + opener: Callable[..., BinaryIO] = urlopen, +) -> Path: + destination.parent.mkdir(parents=True, exist_ok=True) + temporary = destination.with_name(f".{destination.name}.tmp") + try: + with opener(url, timeout=timeout) as response, temporary.open("wb") as output: + shutil.copyfileobj(response, output, length=1 << 20) + temporary.replace(destination) + except BaseException: + temporary.unlink(missing_ok=True) + raise + return destination + + +def _download_chicago_sample( + config: DataConfig, + destination: Path, + *, + opener: Callable[..., BinaryIO], +) -> Path: + """Download and concatenate the pinned Chicago hourly strata atomically.""" + + destination.parent.mkdir(parents=True, exist_ok=True) + temporary = destination.with_name(f".{destination.name}.tmp") + expected_header: bytes | None = None + rows_written = 0 + try: + with temporary.open("wb") as output: + for url in chicago_sample_urls(config): + with opener(url, timeout=config.timeout_seconds) as response: + payload = response.read() + lines = payload.splitlines(keepends=True) + if not lines: + raise ValueError(f"Chicago API returned an empty response for {url}") + header = lines[0].rstrip(b"\r\n") + if expected_header is None: + expected_header = header + output.write(header + b"\n") + elif header != expected_header: + raise ValueError("Chicago API schemas differed across hourly sample strata") + for line in lines[1:]: + output.write(line.rstrip(b"\r\n") + b"\n") + rows_written += 1 + if rows_written != config.sample_rows: + raise ValueError( + f"Chicago API returned {rows_written} sample rows; expected {config.sample_rows}" + ) + temporary.replace(destination) + except BaseException: + temporary.unlink(missing_ok=True) + raise + return destination + + +def _nyc_sample_filename(config: DataConfig) -> str: + """Return a cache key that captures every NYC sample-selection dimension.""" + + month = config.nyc_months[0] + signature = json.dumps( + { + "year": config.nyc_year, + "month": month, + "days": sorted(config.nyc_sample_days), + "hours": sorted(config.nyc_sample_hours), + "rows": config.sample_rows, + "strategy": "day_hour_stable_hash_v1", + }, + sort_keys=True, + separators=(",", ":"), + ) + fingerprint = hashlib.sha256(signature.encode("utf-8")).hexdigest()[:12] + return ( + f"fhvhv_tripdata_{config.nyc_year}-{month:02d}_" + f"stratified_{config.sample_rows}_{fingerprint}.parquet" + ) + + +def _nyc_sample_quotas(config: DataConfig) -> dict[tuple[int, int], int]: + """Allocate the requested row bound exactly across configured day-hour strata.""" + + strata = [ + (day, hour) + for day in sorted(config.nyc_sample_days) + for hour in sorted(config.nyc_sample_hours) + ] + base_quota, remainder = divmod(config.sample_rows, len(strata)) + return { + stratum: base_quota + int(index < remainder) + for index, stratum in enumerate(strata) + } + + +def _validate_nyc_sample_cache(path: Path, config: DataConfig) -> None: + """Fail closed when a cached NYC sample does not match its selection contract.""" + + try: + lazy = pl.scan_parquet(path) + schema = lazy.collect_schema() + except Exception as exc: + raise ValueError( + f"cached NYC sample is not readable; rerun with --refresh: {path}" + ) from exc + missing = sorted(REQUIRED_RAW_COLUMNS["nyc_hvfhv"] - set(schema.names())) + if missing: + raise ValueError( + "cached NYC sample is missing required columns; rerun with --refresh: " + + ", ".join(missing) + ) + pickups = lazy.select("pickup_datetime").collect() + if pickups.height != config.sample_rows: + raise ValueError( + f"cached NYC sample has {pickups.height} rows, expected {config.sample_rows}; " + "rerun with --refresh" + ) + observed = ( + pickups.with_columns( + pl.col("pickup_datetime").dt.year().alias("year"), + pl.col("pickup_datetime").dt.month().alias("month"), + pl.col("pickup_datetime").dt.day().alias("day"), + pl.col("pickup_datetime").dt.hour().alias("hour"), + ) + .group_by("year", "month", "day", "hour") + .len() + ) + actual = { + (int(row["day"]), int(row["hour"])): int(row["len"]) + for row in observed.iter_rows(named=True) + if row["year"] == config.nyc_year and row["month"] == config.nyc_months[0] + } + expected = _nyc_sample_quotas(config) + if actual != expected or observed.height != len(expected): + raise ValueError( + "cached NYC sample does not match the configured day-hour quotas; " + "rerun with --refresh" + ) + + +def materialize_nyc_hvfhv_sample( + config: DataConfig, + destination: PathLike | None = None, + *, + source_url: str | None = None, + connection: duckdb.DuckDBPyConnection | None = None, +) -> Path: + """Materialize a bounded, deterministic NYC day-hour sample via range reads. + + TLC publishes monthly Parquet rather than a separate small extract. DuckDB reads + Parquet metadata and predicate-selected row groups over HTTP. Within each + configured day-hour stratum, a stable hash ordering selects a fixed quota. This + avoids both storing the entire monthly file and collapsing a bounded sample into + the upstream object's first hour. It remains a deterministic engineering sample, + not a probability sample. + + ``source_url`` is exposed for mirrors and offline tests; production defaults to + the first month returned by :func:`nyc_hvfhv_urls`. + """ + + if config.source != "nyc_hvfhv" or config.mode != "sample": + raise ValueError("materialize_nyc_hvfhv_sample requires NYC mode='sample'") + url = source_url or nyc_hvfhv_urls(config)[0] + target = ( + Path(destination) + if destination is not None + else config.raw_dir / _nyc_sample_filename(config) + ) + target.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile( + prefix=f".{target.stem}-", suffix=".parquet", dir=target.parent, delete=False + ) as handle: + temporary = Path(handle.name) + temporary.unlink() + owns_connection = connection is None + database = connection or duckdb.connect() + try: + database.execute("SET threads = 1") + database.read_parquet(url).create_view( + "_nyc_hvfhv_sample_source", replace=True + ) + quotas = _nyc_sample_quotas(config) + branches: list[str] = [] + month = config.nyc_months[0] + stable_order = ( + "hash(hvfhs_license_num, pickup_datetime, dropoff_datetime, " + "PULocationID, DOLocationID, trip_miles, trip_time, " + "base_passenger_fare), pickup_datetime, dropoff_datetime, " + "PULocationID, DOLocationID" + ) + for day in sorted(config.nyc_sample_days): + for hour in sorted(config.nyc_sample_hours): + quota = quotas[(day, hour)] + start = datetime(config.nyc_year, month, day, hour) + end = start + timedelta(hours=1) + start_sql = start.strftime("%Y-%m-%d %H:%M:%S") + end_sql = end.strftime("%Y-%m-%d %H:%M:%S") + branches.append( + "SELECT * FROM (" + "SELECT * FROM _nyc_hvfhv_sample_source " + f"WHERE pickup_datetime >= TIMESTAMP '{start_sql}' " + f"AND pickup_datetime < TIMESTAMP '{end_sql}' " + f"ORDER BY {stable_order} LIMIT {quota}" + ")" + ) + sample = database.sql(" UNION ALL ".join(branches)).order( + f"pickup_datetime, {stable_order}" + ) + sample.write_parquet(str(temporary), compression="zstd") + _validate_nyc_sample_cache(temporary, config) + temporary.replace(target) + except BaseException: + temporary.unlink(missing_ok=True) + raise + finally: + if owns_connection: + database.close() + return target + + +def download_sample( + config: DataConfig | PathLike, + *, + refresh: bool = False, + opener: Callable[..., BinaryIO] = urlopen, +) -> Path: + """Materialize one sample raw file, using the committed fixture by default. + + For the default Chicago sample, ``refresh=False`` performs no network access + and copies the immutable fixture into ``raw_dir``. ``refresh=True`` explicitly + reruns the pinned Socrata query. NYC does not publish a small fixture; its + sample mode downloads one configured monthly Parquet and normalization applies + ``sample_rows`` deterministically. + """ + + cfg = load_data_config(config) if not isinstance(config, DataConfig) else config + if cfg.mode != "sample": + raise ValueError("download_sample requires mode='sample'") + cfg.raw_dir.mkdir(parents=True, exist_ok=True) + + if cfg.source == "chicago_tnp": + destination = cfg.raw_dir / "chicago_tnp_sample.csv" + if not refresh: + if cfg.fixture_path is None: + raise FileNotFoundError("sample config has no offline fixture_path") + if not cfg.fixture_path.exists(): + raise FileNotFoundError(f"Chicago fixture does not exist: {cfg.fixture_path}") + return _copy_if_changed(cfg.fixture_path, destination) + return _download_chicago_sample(cfg, destination, opener=opener) + + destination = cfg.raw_dir / _nyc_sample_filename(cfg) + if destination.exists() and not refresh: + _validate_nyc_sample_cache(destination, cfg) + return destination + return materialize_nyc_hvfhv_sample(cfg, destination) + + +def _download_chicago_full( + config: DataConfig, + *, + refresh: bool, + opener: Callable[..., BinaryIO], +) -> tuple[Path, ...]: + if not config.start_datetime or not config.end_datetime: + raise ValueError( + "Chicago full mode requires start_datetime and end_datetime; " + "an unbounded 300M-row request is intentionally refused" + ) + outputs: list[Path] = [] + page = 0 + while config.max_pages is None or page < config.max_pages: + query_url = chicago_query_url(config) + separator = "&" if "?" in query_url else "?" + url = ( + f"{query_url}{separator}" + f"{urlencode({'$limit': config.page_size, '$offset': page * config.page_size})}" + ) + destination = config.raw_dir / f"chicago_tnp_page_{page:05d}.csv" + if refresh or not destination.exists(): + _download_url(url, destination, timeout=config.timeout_seconds, opener=opener) + with destination.open("r", encoding="utf-8", newline="") as handle: + row_count = max(sum(1 for _ in csv.reader(handle)) - 1, 0) + if row_count == 0: + destination.unlink(missing_ok=True) + break + outputs.append(destination) + page += 1 + if row_count < config.page_size: + break + return tuple(outputs) + + +def download_data( + config: DataConfig | PathLike, + *, + refresh: bool = False, + opener: Callable[..., BinaryIO] = urlopen, +) -> tuple[Path, ...]: + """Download or materialize all raw files selected by a data config.""" + + cfg = load_data_config(config) if not isinstance(config, DataConfig) else config + cfg.raw_dir.mkdir(parents=True, exist_ok=True) + if cfg.mode == "sample": + return (download_sample(cfg, refresh=refresh, opener=opener),) + if cfg.source == "chicago_tnp": + return _download_chicago_full(cfg, refresh=refresh, opener=opener) + + outputs: list[Path] = [] + for url in nyc_hvfhv_urls(cfg): + destination = cfg.raw_dir / Path(url).name + if refresh or not destination.exists(): + _download_url(url, destination, timeout=cfg.timeout_seconds, opener=opener) + outputs.append(destination) + return tuple(outputs) + + +def _read_frame(data: FrameInput) -> pl.DataFrame: + if isinstance(data, pl.DataFrame): + return data.clone() + if isinstance(data, (str, os.PathLike)): + paths = (Path(data),) + else: + paths = tuple(Path(path) for path in data) + if not paths: + raise ValueError("at least one input file is required") + frames: list[pl.DataFrame] = [] + for path in paths: + suffix = path.suffix.lower() + if suffix in {".parquet", ".pq"}: + frames.append(pl.read_parquet(path)) + elif suffix in {".csv", ".csv.gz"} or path.name.endswith(".csv.gz"): + frames.append( + pl.read_csv( + path, + null_values=["", "null", "NULL"], + try_parse_dates=False, + infer_schema_length=10_000, + ) + ) + else: + raise ValueError(f"unsupported input format: {path}") + return pl.concat(frames, how="diagonal_relaxed") if len(frames) > 1 else frames[0] + + +def _validate_raw_columns(frame: pl.DataFrame, source: Source) -> None: + missing = sorted(REQUIRED_RAW_COLUMNS[source] - set(frame.columns)) + if missing: + raise ValueError(f"{source} raw data are missing required columns: {', '.join(missing)}") + + +def _ensure_columns(frame: pl.DataFrame, schema: pl.Schema) -> pl.DataFrame: + additions = [ + pl.lit(None, dtype=dtype).alias(name) + for name, dtype in schema.items() + if name not in frame.columns + ] + return frame.with_columns(additions) if additions else frame + + +def _datetime_expr(frame: pl.DataFrame, name: str) -> pl.Expr: + dtype = frame.schema[name] + if dtype == pl.Date or isinstance(dtype, pl.Datetime): + return pl.col(name).cast(pl.Datetime("us"), strict=False) + return pl.col(name).cast(pl.String).str.to_datetime(strict=False).cast(pl.Datetime("us")) + + +def _string_expr(name: str) -> pl.Expr: + return pl.col(name).cast(pl.String, strict=False).str.strip_chars().replace("", None) + + +def _zone_expr(name: str) -> pl.Expr: + return pl.col(name).cast(pl.Int64, strict=False).cast(pl.String) + + +def _boolean_expr(name: str) -> pl.Expr: + normalized = pl.col(name).cast(pl.String, strict=False).str.to_lowercase().str.strip_chars() + return ( + pl.when(normalized.is_in(["true", "t", "1", "yes", "y"])) + .then(pl.lit(True)) + .when(normalized.is_in(["false", "f", "0", "no", "n"])) + .then(pl.lit(False)) + .otherwise(pl.lit(None, dtype=pl.Boolean)) + ) + + +def _flag_expr(name: str) -> pl.Expr: + normalized = pl.col(name).cast(pl.String, strict=False).str.to_uppercase().str.strip_chars() + return ( + pl.when(normalized == "Y") + .then(pl.lit(True)) + .when(normalized == "N") + .then(pl.lit(False)) + .otherwise(pl.lit(None, dtype=pl.Boolean)) + ) + + +def _utc_expr(name: str, timezone: str) -> pl.Expr: + return ( + pl.col(name) + .dt.replace_time_zone(timezone, ambiguous="null", non_existent="null") + .dt.convert_time_zone("UTC") + ) + + +def _grid_15m_expr(name: str) -> pl.Expr: + return ( + (pl.col(name).dt.minute() % 15 == 0) + & (pl.col(name).dt.second() == 0) + & (pl.col(name).dt.millisecond() == 0) + ) + + +def _normalize_chicago(frame: pl.DataFrame) -> pl.DataFrame: + frame = _ensure_columns(frame, CHICAGO_RAW_SCHEMA) + frame = frame.with_columns( + _datetime_expr(frame, "trip_start_timestamp").alias("_pickup_local"), + _datetime_expr(frame, "trip_end_timestamp").alias("_dropoff_local"), + _string_expr("pickup_census_tract").alias("_pickup_tract"), + _string_expr("dropoff_census_tract").alias("_dropoff_tract"), + _zone_expr("pickup_community_area").alias("_pickup_zone"), + _zone_expr("dropoff_community_area").alias("_dropoff_zone"), + pl.col("fare").cast(pl.Float64, strict=False).alias("_fare"), + pl.col("tip").cast(pl.Float64, strict=False).alias("_tips"), + pl.col("additional_charges").cast(pl.Float64, strict=False).alias("_additional"), + pl.col("trips_pooled").cast(pl.Int64, strict=False).alias("_trips_pooled"), + _boolean_expr("shared_trip_authorized").alias("_shared_requested"), + ) + result = frame.select( + pl.lit("chicago_tnp").alias("source"), + pl.lit(CHICAGO_DATASET_ID).alias("source_dataset_id"), + _string_expr("trip_id").alias("trip_id"), + pl.lit(False).alias("record_id_is_surrogate"), + pl.lit(None, dtype=pl.String).alias("provider_id"), + pl.lit(None, dtype=pl.String).alias("dispatching_base_id"), + pl.lit(None, dtype=pl.Datetime("us")).alias("request_datetime"), + pl.col("_pickup_local").alias("pickup_datetime"), + pl.col("_dropoff_local").alias("dropoff_datetime"), + _utc_expr("_pickup_local", "America/Chicago").alias("pickup_datetime_utc"), + _utc_expr("_dropoff_local", "America/Chicago").alias("dropoff_datetime_utc"), + pl.lit("America/Chicago").alias("source_timezone"), + pl.col("_pickup_local").dt.date().alias("service_date"), + pl.col("_pickup_local").dt.year().cast(pl.Int32).alias("service_year"), + pl.col("_pickup_local").dt.month().cast(pl.Int8).alias("service_month"), + pl.col("_pickup_local").dt.weekday().cast(pl.Int8).alias("service_day_of_week"), + pl.col("_pickup_zone").alias("pickup_zone_id"), + pl.col("_dropoff_zone").alias("dropoff_zone_id"), + pl.lit("chicago_community_area").alias("zone_type"), + pl.col("_pickup_tract").alias("pickup_census_tract"), + pl.col("_dropoff_tract").alias("dropoff_census_tract"), + pl.col("trip_seconds").cast(pl.Int64, strict=False).alias("trip_seconds"), + pl.col("trip_miles").cast(pl.Float64, strict=False).alias("trip_miles"), + pl.col("_fare").alias("fare"), + pl.col("_tips").alias("tips"), + pl.lit(None, dtype=pl.Float64).alias("tolls"), + pl.lit(None, dtype=pl.Float64).alias("taxes_and_surcharges"), + pl.col("_additional").alias("additional_charges"), + pl.col("trip_total").cast(pl.Float64, strict=False).alias("total_amount"), + pl.lit(None, dtype=pl.Float64).alias("driver_pay"), + pl.lit(None, dtype=pl.Float64).alias("airport_fee"), + pl.col("_shared_requested").alias("shared_requested"), + (pl.col("_trips_pooled") > 1).alias("shared_matched"), + pl.col("_trips_pooled").alias("trips_pooled"), + ( + pl.col("_pickup_zone").is_in(["56", "76"]) + | pl.col("_dropoff_zone").is_in(["56", "76"]) + ).alias("airport_trip"), + pl.col("_pickup_zone").is_null().alias("pickup_zone_missing"), + pl.col("_dropoff_zone").is_null().alias("dropoff_zone_missing"), + pl.col("_pickup_tract").is_null().alias( + "pickup_census_tract_missing_or_suppressed" + ), + pl.col("_dropoff_tract").is_null().alias( + "dropoff_census_tract_missing_or_suppressed" + ), + pl.lit(15, dtype=pl.Int16).alias("reported_timestamp_rounding_minutes"), + pl.lit(2.5).alias("reported_fare_rounding_increment"), + pl.lit(1.0).alias("reported_tip_rounding_increment"), + _grid_15m_expr("_pickup_local").alias("pickup_on_15_minute_grid"), + (((pl.col("_fare") / 2.5).round() * 2.5 - pl.col("_fare")).abs() <= 1e-8).alias( + "fare_on_declared_grid" + ), + ) + return result.cast(CLEAN_TRIP_SCHEMA, strict=False) + + +def _normalize_nyc( + frame: pl.DataFrame, + *, + source_row_offset: int = 0, +) -> pl.DataFrame: + """Normalize one NYC frame using a caller-supplied global source-row offset. + + The offset is zero for the public eager API. The full-month streaming path + advances it across every record batch and raw file so otherwise identical rows + cannot receive the same surrogate ``trip_id`` merely because a new batch began. + """ + + frame = _ensure_columns(frame, NYC_HVFHV_RAW_SCHEMA).with_row_index( + "_source_row", offset=source_row_offset + ) + frame = frame.with_columns( + _datetime_expr(frame, "request_datetime").alias("_request_local"), + _datetime_expr(frame, "pickup_datetime").alias("_pickup_local"), + _datetime_expr(frame, "dropoff_datetime").alias("_dropoff_local"), + _zone_expr("PULocationID").alias("_pickup_zone"), + _zone_expr("DOLocationID").alias("_dropoff_zone"), + pl.col("base_passenger_fare").cast(pl.Float64, strict=False).alias("_fare"), + pl.col("tips").cast(pl.Float64, strict=False).alias("_tips"), + pl.col("tolls").cast(pl.Float64, strict=False).alias("_tolls"), + pl.col("airport_fee").cast(pl.Float64, strict=False).alias("_airport_fee"), + pl.col("cbd_congestion_fee").cast(pl.Float64, strict=False).alias("_cbd_fee"), + _flag_expr("shared_request_flag").alias("_shared_requested"), + _flag_expr("shared_match_flag").alias("_shared_matched"), + ) + taxes = pl.sum_horizontal( + pl.col("bcf").cast(pl.Float64, strict=False).fill_null(0.0), + pl.col("sales_tax").cast(pl.Float64, strict=False).fill_null(0.0), + pl.col("congestion_surcharge").cast(pl.Float64, strict=False).fill_null(0.0), + pl.col("_cbd_fee").fill_null(0.0), + ) + additional = taxes + pl.col("_tolls").fill_null(0.0) + pl.col("_airport_fee").fill_null(0.0) + trip_id = pl.concat_str( + [ + pl.lit("nyc_hvfhv"), + _string_expr("hvfhs_license_num").fill_null("unknown"), + pl.col("_pickup_local").cast(pl.String), + pl.col("_dropoff_local").cast(pl.String), + pl.col("_pickup_zone").fill_null("unknown"), + pl.col("_dropoff_zone").fill_null("unknown"), + pl.col("_source_row").cast(pl.String), + ], + separator=":", + ) + result = frame.select( + pl.lit("nyc_hvfhv").alias("source"), + pl.lit(f"fhvhv-{SCHEMA_VERSION}").alias("source_dataset_id"), + trip_id.alias("trip_id"), + pl.lit(True).alias("record_id_is_surrogate"), + _string_expr("hvfhs_license_num").alias("provider_id"), + _string_expr("dispatching_base_num").alias("dispatching_base_id"), + pl.col("_request_local").alias("request_datetime"), + pl.col("_pickup_local").alias("pickup_datetime"), + pl.col("_dropoff_local").alias("dropoff_datetime"), + _utc_expr("_pickup_local", "America/New_York").alias("pickup_datetime_utc"), + _utc_expr("_dropoff_local", "America/New_York").alias("dropoff_datetime_utc"), + pl.lit("America/New_York").alias("source_timezone"), + pl.col("_pickup_local").dt.date().alias("service_date"), + pl.col("_pickup_local").dt.year().cast(pl.Int32).alias("service_year"), + pl.col("_pickup_local").dt.month().cast(pl.Int8).alias("service_month"), + pl.col("_pickup_local").dt.weekday().cast(pl.Int8).alias("service_day_of_week"), + pl.col("_pickup_zone").alias("pickup_zone_id"), + pl.col("_dropoff_zone").alias("dropoff_zone_id"), + pl.lit("nyc_taxi_zone").alias("zone_type"), + pl.lit(None, dtype=pl.String).alias("pickup_census_tract"), + pl.lit(None, dtype=pl.String).alias("dropoff_census_tract"), + pl.col("trip_time").cast(pl.Int64, strict=False).alias("trip_seconds"), + pl.col("trip_miles").cast(pl.Float64, strict=False).alias("trip_miles"), + pl.col("_fare").alias("fare"), + pl.col("_tips").alias("tips"), + pl.col("_tolls").alias("tolls"), + taxes.alias("taxes_and_surcharges"), + additional.alias("additional_charges"), + ( + pl.col("_fare").fill_null(0.0) + + pl.col("_tips").fill_null(0.0) + + additional + ).alias("total_amount"), + pl.col("driver_pay").cast(pl.Float64, strict=False).alias("driver_pay"), + pl.col("_airport_fee").alias("airport_fee"), + pl.col("_shared_requested").alias("shared_requested"), + pl.col("_shared_matched").alias("shared_matched"), + pl.lit(None, dtype=pl.Int64).alias("trips_pooled"), + ( + (pl.col("_airport_fee").fill_null(0.0) > 0) + | pl.col("_pickup_zone").is_in(["1", "132", "138"]) + | pl.col("_dropoff_zone").is_in(["1", "132", "138"]) + ).alias("airport_trip"), + pl.col("_pickup_zone").is_null().alias("pickup_zone_missing"), + pl.col("_dropoff_zone").is_null().alias("dropoff_zone_missing"), + pl.lit(None, dtype=pl.Boolean).alias( + "pickup_census_tract_missing_or_suppressed" + ), + pl.lit(None, dtype=pl.Boolean).alias( + "dropoff_census_tract_missing_or_suppressed" + ), + pl.lit(None, dtype=pl.Int16).alias("reported_timestamp_rounding_minutes"), + pl.lit(None, dtype=pl.Float64).alias("reported_fare_rounding_increment"), + pl.lit(None, dtype=pl.Float64).alias("reported_tip_rounding_increment"), + _grid_15m_expr("_pickup_local").alias("pickup_on_15_minute_grid"), + pl.lit(None, dtype=pl.Boolean).alias("fare_on_declared_grid"), + ) + return result.cast(CLEAN_TRIP_SCHEMA, strict=False) + + +def normalize_trips( + data: FrameInput, + source: str | None = None, + *, + config: DataConfig | PathLike | None = None, +) -> pl.DataFrame: + """Normalize Chicago TNP or NYC TLC HVFHV records to ``CLEAN_TRIP_SCHEMA``. + + Sample mode takes the first ``sample_rows`` after deterministic source ordering. + It never random-samples, so rerunning the same pinned input yields identical rows. + Local naive timestamps are retained alongside UTC timestamps. Ambiguous or + nonexistent daylight-saving local times produce null UTC values rather than an + invented offset; the local value remains available for panel construction. + """ + + cfg: DataConfig | None + if config is None: + cfg = None + else: + cfg = load_data_config(config) if not isinstance(config, DataConfig) else config + source_name = _canonical_source(source or (cfg.source if cfg else "")) + frame = _read_frame(data) + _validate_raw_columns(frame, source_name) + if source_name == "chicago_tnp": + frame = frame.sort(["trip_start_timestamp", "trip_id"]) + else: + frame = frame.sort(["pickup_datetime", "dropoff_datetime"]) + if cfg is not None and cfg.mode == "sample": + frame = frame.head(cfg.sample_rows) + return _normalize_chicago(frame) if source_name == "chicago_tnp" else _normalize_nyc(frame) + + +def validate_clean_schema(frame: pl.DataFrame) -> None: + """Raise when columns or dtypes diverge from the canonical cleaned contract.""" + + missing = sorted(set(CLEAN_TRIP_SCHEMA.names()) - set(frame.columns)) + if missing: + raise ValueError(f"cleaned trips are missing columns: {', '.join(missing)}") + mismatches = { + name: {"expected": str(dtype), "actual": str(frame.schema[name])} + for name, dtype in CLEAN_TRIP_SCHEMA.items() + if frame.schema[name] != dtype + } + if mismatches: + raise TypeError(f"cleaned trip schema mismatches: {mismatches}") + + +def _true_count(frame: pl.DataFrame, column: str) -> int: + return int(frame.select(pl.col(column).fill_null(False).sum()).item() or 0) + + +def _known_rate(frame: pl.DataFrame, column: str) -> float | None: + known = frame.select(pl.col(column).drop_nulls().len()).item() + if not known: + return None + return float(frame.select(pl.col(column).drop_nulls().mean()).item()) + + +def data_quality_diagnostics(frame: pl.DataFrame) -> dict[str, Any]: + """Compute JSON-safe missingness, suppression, rounding, and validity checks.""" + + validate_clean_schema(frame) + rows = frame.height + nulls = frame.null_count().row(0, named=True) + missingness = { + column: { + "count": int(nulls[column]), + "rate": (float(nulls[column]) / rows if rows else None), + } + for column in frame.columns + } + sources = sorted(frame.get_column("source").drop_nulls().unique().to_list()) + pickup_indicator = "pickup_census_tract_missing_or_suppressed" + dropoff_indicator = "dropoff_census_tract_missing_or_suppressed" + pickup_suppressed = _true_count(frame, pickup_indicator) + dropoff_suppressed = _true_count(frame, dropoff_indicator) + pickup_known = rows - int(nulls[pickup_indicator]) + dropoff_known = rows - int(nulls[dropoff_indicator]) + trip_ids = frame.get_column("trip_id") + diagnostics = { + "schema_version": SCHEMA_VERSION, + "row_count": rows, + "sources": sources, + "missingness": missingness, + "suppression_or_nonreporting": { + "pickup_census_tract_count": pickup_suppressed, + "pickup_census_tract_rate": ( + pickup_suppressed / pickup_known if pickup_known else None + ), + "pickup_indicator_known_count": pickup_known, + "pickup_indicator_status": ( + "available" + if pickup_known == rows + else "unavailable" + if not pickup_known + else "partial" + ), + "dropoff_census_tract_count": dropoff_suppressed, + "dropoff_census_tract_rate": ( + dropoff_suppressed / dropoff_known if dropoff_known else None + ), + "dropoff_indicator_known_count": dropoff_known, + "dropoff_indicator_status": ( + "available" + if dropoff_known == rows + else "unavailable" + if not dropoff_known + else "partial" + ), + "interpretation": ( + "Null availability indicators mean the source does not report the field; they " + "must not be recoded as unsuppressed. Chicago blank census tracts may be " + "privacy-suppressed or outside Chicago, and no record-level mechanism is claimed." + ), + }, + "rounding": { + "pickup_on_15_minute_grid_rate": _known_rate( + frame, "pickup_on_15_minute_grid" + ), + "fare_on_declared_grid_rate": _known_rate(frame, "fare_on_declared_grid"), + "declared_timestamp_rounding_minutes": sorted( + int(value) + for value in frame.get_column("reported_timestamp_rounding_minutes") + .drop_nulls() + .unique() + .to_list() + ), + "declared_fare_rounding_increments": sorted( + float(value) + for value in frame.get_column("reported_fare_rounding_increment") + .drop_nulls() + .unique() + .to_list() + ), + "interpretation": ( + "Grid conformance verifies reported-value patterns; it does not recover " + "latent exact fares or timestamps." + ), + }, + "validity": { + "duplicate_trip_id_count": rows - trip_ids.n_unique(), + "missing_trip_id_count": trip_ids.null_count(), + "nonpositive_trip_seconds_count": int( + frame.select((pl.col("trip_seconds") <= 0).fill_null(False).sum()).item() or 0 + ), + "negative_trip_miles_count": int( + frame.select((pl.col("trip_miles") < 0).fill_null(False).sum()).item() or 0 + ), + "negative_fare_count": int( + frame.select((pl.col("fare") < 0).fill_null(False).sum()).item() or 0 + ), + "utc_conversion_null_count": int( + frame.select(pl.col("pickup_datetime_utc").is_null().sum()).item() or 0 + ), + }, + "source_caveats": {source: SOURCE_METADATA[source]["known_measurement"] for source in sources}, + } + return _json_safe(diagnostics) + + +def build_zone_time_panel( + trips: pl.DataFrame, + *, + frequency: str = "15m", + complete_grid: bool = False, +) -> pl.DataFrame: + """Aggregate cleaned trips to pickup-zone × local-time cells. + + ``avg_fare`` is descriptive and inherits source rounding/selection. It must not + be interpreted as an exogenous price or a causal demand elasticity. OD structure + appears as outbound counts and distinct destinations; use + :func:`build_od_flow_panel` for the full origin-destination panel. + """ + + validate_clean_schema(trips) + usable = trips.filter(pl.col("pickup_datetime").is_not_null()).with_columns( + pl.col("pickup_datetime").dt.truncate(frequency).alias("time_bin"), + ( + pl.col("pickup_zone_id").is_not_null() + & pl.col("dropoff_zone_id").is_not_null() + ).alias("_od_pair_observed"), + pl.col("pickup_zone_id").fill_null(MISSING_ZONE_ID), + pl.col("dropoff_zone_id").fill_null(MISSING_ZONE_ID), + ) + panel = ( + usable.group_by(["source", "zone_type", "pickup_zone_id", "time_bin"]) + .agg( + pl.len().cast(pl.Int64).alias("trip_count"), + pl.when(pl.col("_od_pair_observed").sum() > 0) + .then( + pl.col("dropoff_zone_id") + .filter(pl.col("_od_pair_observed")) + .n_unique() + .cast(pl.Int64) + ) + .otherwise(None) + .alias("distinct_dropoff_zones"), + pl.when(pl.col("_od_pair_observed").sum() > 0) + .then( + (pl.col("pickup_zone_id") != pl.col("dropoff_zone_id")) + .filter(pl.col("_od_pair_observed")) + .sum() + .cast(pl.Int64) + ) + .otherwise(None) + .alias("outbound_trip_count"), + pl.when(pl.col("_od_pair_observed")) + .then(pl.col("pickup_zone_id") == pl.col("dropoff_zone_id")) + .otherwise(None) + .mean() + .alias("intra_zone_share"), + pl.col("_od_pair_observed").sum().cast(pl.Int64).alias("od_pair_observed_count"), + pl.col("_od_pair_observed").mean().alias("od_pair_observed_share"), + pl.col("fare").mean().alias("avg_fare"), + pl.col("fare").median().alias("median_fare"), + pl.col("fare").sum().alias("total_fare"), + pl.col("trip_seconds").mean().alias("avg_trip_seconds"), + pl.col("trip_miles").mean().alias("avg_trip_miles"), + pl.col("trip_miles").sum().alias("total_trip_miles"), + pl.col("shared_requested").mean().alias("shared_requested_share"), + pl.col("shared_matched").mean().alias("shared_matched_share"), + pl.col("airport_trip").mean().alias("airport_trip_share"), + pl.col("pickup_census_tract_missing_or_suppressed") + .mean() + .alias("pickup_geography_missing_or_suppressed_share"), + pl.col("reported_timestamp_rounding_minutes") + .is_not_null() + .mean() + .alias("timestamp_rounded_measurement_share"), + pl.col("reported_fare_rounding_increment") + .is_not_null() + .mean() + .alias("fare_rounded_measurement_share"), + ) + .rename({"pickup_zone_id": "zone_id"}) + .with_columns( + pl.col("time_bin").dt.date().alias("service_date"), + pl.col("time_bin").dt.year().cast(pl.Int32).alias("year"), + pl.col("time_bin").dt.month().cast(pl.Int8).alias("month"), + pl.col("time_bin").dt.weekday().cast(pl.Int8).alias("day_of_week"), + pl.col("time_bin").dt.hour().cast(pl.Int8).alias("hour"), + pl.col("time_bin").dt.minute().cast(pl.Int8).alias("minute"), + (pl.col("time_bin").dt.weekday() >= 6).alias("is_weekend"), + pl.lit(f"pickup_zone_x_{frequency}").alias("panel_grain"), + pl.lit("descriptive_real_data").alias("evidence_label"), + ) + .sort(["source", "zone_type", "zone_id", "time_bin"]) + ) + return _complete_zone_time_grid(panel, frequency) if complete_grid else panel + + +def _complete_zone_time_grid(panel: pl.DataFrame, frequency: str) -> pl.DataFrame: + if panel.is_empty(): + return panel + frames: list[pl.DataFrame] = [] + for key, group in panel.partition_by(["source", "zone_type"], as_dict=True).items(): + source, zone_type = key if isinstance(key, tuple) else (key, "unknown") + observed = group.with_columns(pl.lit(True).alias("_observed_cell")) + times = pl.DataFrame( + { + "time_bin": pl.datetime_range( + observed.get_column("time_bin").min(), + observed.get_column("time_bin").max(), + interval=frequency, + eager=True, + ) + } + ) + zones = observed.select("zone_id").unique().sort("zone_id") + grid = ( + zones.join(times, how="cross") + .with_columns( + pl.lit(source).alias("source"), + pl.lit(zone_type).alias("zone_type"), + ) + .join( + observed, + on=["source", "zone_type", "zone_id", "time_bin"], + how="left", + ) + ) + # A synthesized cell is a known zero-trip cell. An observed trip cell whose + # destinations are all unavailable is different: its OD summaries remain + # unknown instead of being silently recoded to zero. + synthetic_zero_columns = [ + "trip_count", + "distinct_dropoff_zones", + "outbound_trip_count", + "od_pair_observed_count", + "total_fare", + "total_trip_miles", + ] + grid = ( + grid.with_columns( + *[ + pl.when(pl.col("_observed_cell").is_null()) + .then(0) + .otherwise(pl.col(column)) + .alias(column) + for column in synthetic_zero_columns + ], + pl.col("time_bin").dt.date().alias("service_date"), + pl.col("time_bin").dt.year().cast(pl.Int32).alias("year"), + pl.col("time_bin").dt.month().cast(pl.Int8).alias("month"), + pl.col("time_bin").dt.weekday().cast(pl.Int8).alias("day_of_week"), + pl.col("time_bin").dt.hour().cast(pl.Int8).alias("hour"), + pl.col("time_bin").dt.minute().cast(pl.Int8).alias("minute"), + (pl.col("time_bin").dt.weekday() >= 6).alias("is_weekend"), + pl.lit(f"pickup_zone_x_{frequency}").alias("panel_grain"), + pl.lit("descriptive_real_data").alias("evidence_label"), + ).drop("_observed_cell") + ) + frames.append(grid) + return pl.concat(frames, how="diagonal_relaxed").sort( + ["source", "zone_type", "zone_id", "time_bin"] + ) + + +def build_od_flow_panel(trips: pl.DataFrame, *, frequency: str = "15m") -> pl.DataFrame: + """Build origin × destination × local-time trip-flow counts.""" + + validate_clean_schema(trips) + return ( + trips.filter(pl.col("pickup_datetime").is_not_null()) + .with_columns( + pl.col("pickup_datetime").dt.truncate(frequency).alias("time_bin"), + pl.col("pickup_zone_id").fill_null(MISSING_ZONE_ID), + pl.col("dropoff_zone_id").fill_null(MISSING_ZONE_ID), + ) + .group_by( + ["source", "zone_type", "pickup_zone_id", "dropoff_zone_id", "time_bin"] + ) + .agg( + pl.len().cast(pl.Int64).alias("trip_count"), + pl.col("fare").mean().alias("avg_fare"), + pl.col("trip_miles").mean().alias("avg_trip_miles"), + ) + .rename( + {"pickup_zone_id": "origin_zone_id", "dropoff_zone_id": "destination_zone_id"} + ) + .with_columns( + pl.lit("descriptive_real_data").alias("evidence_label"), + pl.col("time_bin").dt.date().alias("service_date"), + pl.col("time_bin").dt.year().cast(pl.Int32).alias("year"), + pl.col("time_bin").dt.month().cast(pl.Int8).alias("month"), + ) + .sort(["source", "origin_zone_id", "destination_zone_id", "time_bin"]) + ) + + +def _partition_value(value: Any) -> str: + if value is None: + return "__HIVE_DEFAULT_PARTITION__" + rendered = str(value) + return "".join(character if character.isalnum() or character in "-_." else "_" for character in rendered) + + +def write_partitioned_parquet( + frame: pl.DataFrame, + output_dir: PathLike, + *, + partition_by: Sequence[str] = ("source", "service_year", "service_month"), + basename: str = "part-00000.parquet", + overwrite: bool = True, +) -> tuple[Path, ...]: + """Write a deterministic Hive-style Parquet dataset with atomic part writes.""" + + if not basename.endswith(".parquet") or Path(basename).name != basename: + raise ValueError("basename must be a simple .parquet filename") + missing = sorted(set(partition_by) - set(frame.columns)) + if missing: + raise ValueError(f"partition columns are missing: {', '.join(missing)}") + root = Path(output_dir) + root.mkdir(parents=True, exist_ok=True) + if frame.is_empty(): + if overwrite: + for stale in root.rglob("*.parquet"): + stale.unlink() + return () + groups = frame.partition_by(list(partition_by), as_dict=True, maintain_order=True) + outputs: list[Path] = [] + for raw_key, partition in sorted(groups.items(), key=lambda item: str(item[0])): + key = raw_key if isinstance(raw_key, tuple) else (raw_key,) + directory = root + for column, value in zip(partition_by, key, strict=True): + directory = directory / f"{column}={_partition_value(value)}" + directory.mkdir(parents=True, exist_ok=True) + destination = directory / basename + if destination.exists() and not overwrite: + raise FileExistsError(destination) + sort_columns = [ + column + for column in ("pickup_datetime", "time_bin", "zone_id", "trip_id") + if column in partition.columns + ] + payload = partition.sort(sort_columns) if sort_columns else partition + with tempfile.NamedTemporaryFile( + prefix=f".{destination.stem}-", suffix=".parquet", dir=directory, delete=False + ) as handle: + temporary = Path(handle.name) + try: + payload.write_parquet(temporary, compression="zstd", statistics=True) + temporary.replace(destination) + except BaseException: + temporary.unlink(missing_ok=True) + raise + outputs.append(destination) + if overwrite: + expected = {path.resolve() for path in outputs} + for stale in root.rglob("*.parquet"): + if stale.resolve() not in expected: + stale.unlink() + for directory in sorted( + (path for path in root.rglob("*") if path.is_dir()), + key=lambda path: len(path.parts), + reverse=True, + ): + try: + directory.rmdir() + except OSError: + pass + return tuple(sorted(outputs)) + + +def read_partitioned_parquet(path: PathLike) -> pl.DataFrame: + """Read all Parquet parts below a partitioned-dataset directory.""" + + root = Path(path) + files = sorted(root.rglob("*.parquet")) + if not files: + raise FileNotFoundError(f"no Parquet parts under {root}") + return pl.concat([pl.read_parquet(file) for file in files], how="diagonal_relaxed") + + +def _json_safe(value: Any) -> Any: + if isinstance(value, Path): + return str(value) + if isinstance(value, datetime): + return value.isoformat() + if isinstance(value, Mapping): + return {str(key): _json_safe(item) for key, item in value.items()} + if isinstance(value, (list, tuple, set, frozenset)): + return [_json_safe(item) for item in value] + return value + + +def _atomic_json(payload: Mapping[str, Any], destination: Path) -> Path: + destination.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + prefix=f".{destination.stem}-", + suffix=".json", + dir=destination.parent, + delete=False, + ) as handle: + temporary = Path(handle.name) + json.dump(_json_safe(payload), handle, indent=2, sort_keys=True, allow_nan=False) + handle.write("\n") + temporary.replace(destination) + return destination + + +def write_diagnostics(frame: pl.DataFrame, destination: PathLike) -> Path: + """Write :func:`data_quality_diagnostics` as strict JSON.""" + + return _atomic_json(data_quality_diagnostics(frame), Path(destination)) + + +def write_manifest( + files: Iterable[PathLike], + destination: PathLike, + *, + config: DataConfig | None = None, + metadata: Mapping[str, Any] | None = None, + root: PathLike | None = None, +) -> Path: + """Write an input/output manifest with byte sizes and SHA-256 checksums.""" + + paths = tuple(sorted({Path(path).resolve() for path in files})) + relative_root = Path(root).resolve() if root is not None else None + entries: list[dict[str, Any]] = [] + for path in paths: + if not path.is_file(): + raise FileNotFoundError(path) + try: + rendered_path = str(path.relative_to(relative_root)) if relative_root else str(path) + except ValueError: + rendered_path = str(path) + entries.append( + { + "path": rendered_path, + "bytes": path.stat().st_size, + "sha256": sha256_file(path), + } + ) + payload: dict[str, Any] = { + "schema_version": SCHEMA_VERSION, + "generated_at_utc": datetime.now(UTC).isoformat(), + "files": entries, + } + if config is not None: + payload["config"] = config.as_serializable_dict() + payload["source_metadata"] = SOURCE_METADATA[config.source] + payload["source_urls"] = ( + list(chicago_sample_urls(config)) + if config.source == "chicago_tnp" and config.mode == "sample" + else [chicago_query_url(config)] + if config.source == "chicago_tnp" + else list(nyc_hvfhv_urls(config)) + ) + if metadata: + payload["metadata"] = _json_safe(metadata) + return _atomic_json(payload, Path(destination)) + + +def _sql_string(value: str) -> str: + """Return a DuckDB string literal for a trusted local value.""" + + return "'" + value.replace("'", "''") + "'" + + +def _parquet_scan_sql(files: Sequence[PathLike]) -> str: + paths = tuple(Path(path).resolve() for path in files) + if not paths: + raise ValueError("at least one Parquet file is required") + rendered = ", ".join(_sql_string(str(path)) for path in paths) + return ( + f"read_parquet([{rendered}], union_by_name=true, " + "hive_partitioning=false)" + ) + + +def _duckdb_interval(frequency: str) -> str: + """Translate the bounded Polars frequency syntax used by configs to SQL.""" + + match = re.fullmatch(r"([1-9][0-9]*)(ms|s|m|h|d|w)", frequency.strip()) + if match is None: + raise ValueError( + "streaming NYC full mode requires panel_frequency like 15m, 1h, or 1d" + ) + amount, abbreviation = match.groups() + units = { + "ms": "milliseconds", + "s": "seconds", + "m": "minutes", + "h": "hours", + "d": "days", + "w": "weeks", + } + return f"INTERVAL '{amount} {units[abbreviation]}'" + + +def _new_staging_directory(destination: Path) -> Path: + destination.parent.mkdir(parents=True, exist_ok=True) + return Path( + tempfile.mkdtemp( + prefix=f".{destination.name}-streaming-", + dir=destination.parent, + ) + ) + + +def _replace_directory(staging: Path, destination: Path) -> None: + """Install a completed staged directory while retaining rollback on failure.""" + + if not staging.is_dir(): + raise FileNotFoundError(staging) + destination.parent.mkdir(parents=True, exist_ok=True) + backup_root: Path | None = None + backup: Path | None = None + if destination.exists(): + if not destination.is_dir(): + raise NotADirectoryError(destination) + backup_root = Path( + tempfile.mkdtemp( + prefix=f".{destination.name}-previous-", + dir=destination.parent, + ) + ) + backup = backup_root / "dataset" + destination.replace(backup) + try: + staging.replace(destination) + except BaseException: + if backup is not None: + backup.replace(destination) + raise + finally: + if backup_root is not None and backup_root.exists(): + shutil.rmtree(backup_root) + + +def _stream_normalize_nyc_full( + raw_files: Sequence[Path], + config: DataConfig, + output_dir: Path, +) -> tuple[tuple[Path, ...], dict[str, Any]]: + """Normalize NYC Parquet record batches to unique staged clean parts.""" + + if not raw_files: + raise ValueError("NYC full mode requires at least one raw monthly Parquet file") + if any( + value is not None + for value in ( + config.nyc_expected_rows, + config.nyc_expected_bytes, + config.nyc_expected_sha256, + ) + ) and len(raw_files) != 1: + raise ValueError("NYC exact raw expectations require exactly one raw file") + if config.nyc_expected_bytes is not None: + actual_bytes = raw_files[0].stat().st_size + if actual_bytes != config.nyc_expected_bytes: + raise ValueError( + "NYC raw byte-size mismatch: " + f"expected {config.nyc_expected_bytes}, found {actual_bytes}" + ) + if config.nyc_expected_sha256 is not None: + actual_sha256 = sha256_file(raw_files[0]) + if actual_sha256 != config.nyc_expected_sha256: + raise ValueError( + "NYC raw SHA-256 mismatch: " + f"expected {config.nyc_expected_sha256}, found {actual_sha256}" + ) + output_dir.mkdir(parents=True, exist_ok=True) + source_row_offset = 0 + batch_index = 0 + total_row_groups = 0 + observed_dates: set[date] = set() + observed_date_hours: set[tuple[date, int]] = set() + pickup_min: datetime | None = None + pickup_max: datetime | None = None + file_validation: list[dict[str, Any]] = [] + + for raw_path in raw_files: + if raw_path.suffix.lower() not in {".parquet", ".pq"}: + raise ValueError(f"NYC full streaming input must be Parquet: {raw_path}") + try: + parquet = pq.ParquetFile(raw_path) + except Exception as exc: + raise ValueError(f"NYC raw Parquet is unreadable: {raw_path}") from exc + metadata = parquet.metadata + raw_rows = int(metadata.num_rows) + row_groups = int(metadata.num_row_groups) + if raw_rows < 1 or row_groups < 1: + raise ValueError(f"NYC raw Parquet has no rows or row groups: {raw_path}") + if config.nyc_expected_rows is not None and raw_rows != config.nyc_expected_rows: + raise ValueError( + "NYC raw row-count mismatch: " + f"expected {config.nyc_expected_rows}, found {raw_rows}" + ) + missing = sorted(REQUIRED_RAW_COLUMNS["nyc_hvfhv"] - set(parquet.schema_arrow.names)) + if missing: + raise ValueError( + "nyc_hvfhv raw data are missing required columns: " + ", ".join(missing) + ) + + file_rows = 0 + file_batches = 0 + file_pickup_min: datetime | None = None + file_pickup_max: datetime | None = None + for arrow_batch in parquet.iter_batches(batch_size=config.nyc_batch_rows): + raw_batch = pl.from_arrow(arrow_batch) + if not isinstance(raw_batch, pl.DataFrame): + raise TypeError("PyArrow record batch did not convert to a Polars DataFrame") + _validate_raw_columns(raw_batch, "nyc_hvfhv") + clean_batch = _normalize_nyc( + raw_batch, + source_row_offset=source_row_offset, + ) + validate_clean_schema(clean_batch) + if clean_batch.height != raw_batch.height: + raise RuntimeError("NYC normalization changed the number of trip records") + + write_partitioned_parquet( + clean_batch, + output_dir, + partition_by=config.partition_by, + basename=f"part-{batch_index:05d}.parquet", + overwrite=False, + ) + pickup = clean_batch.get_column("pickup_datetime").drop_nulls() + if not pickup.is_empty(): + batch_min = pickup.min() + batch_max = pickup.max() + if isinstance(batch_min, datetime): + pickup_min = batch_min if pickup_min is None else min(pickup_min, batch_min) + file_pickup_min = ( + batch_min + if file_pickup_min is None + else min(file_pickup_min, batch_min) + ) + if isinstance(batch_max, datetime): + pickup_max = batch_max if pickup_max is None else max(pickup_max, batch_max) + file_pickup_max = ( + batch_max + if file_pickup_max is None + else max(file_pickup_max, batch_max) + ) + coverage = clean_batch.select( + "service_date", + pl.col("pickup_datetime").dt.hour().alias("pickup_hour"), + ).drop_nulls().unique() + for service_date, pickup_hour in coverage.iter_rows(): + observed_dates.add(service_date) + observed_date_hours.add((service_date, int(pickup_hour))) + + source_row_offset += clean_batch.height + file_rows += clean_batch.height + file_batches += 1 + batch_index += 1 + + if file_rows != raw_rows: + raise RuntimeError( + f"NYC raw metadata reports {raw_rows} rows but streamed {file_rows}: {raw_path}" + ) + total_row_groups += row_groups + try: + rendered_raw_path = str( + raw_path.resolve().relative_to(config.project_root.resolve()) + ) + except ValueError: + rendered_raw_path = str(raw_path.resolve()) + file_validation.append( + { + "path": rendered_raw_path, + "rows": raw_rows, + "row_groups": row_groups, + "batches": file_batches, + "pickup_min": file_pickup_min.isoformat() if file_pickup_min else None, + "pickup_max": file_pickup_max.isoformat() if file_pickup_max else None, + } + ) + + expected_dates = { + date(config.nyc_year, month, day) + for month in config.nyc_months + for day in range(1, monthrange(config.nyc_year, month)[1] + 1) + } + outside_dates = sorted(observed_dates - expected_dates) + if outside_dates: + raise ValueError( + "NYC full raw data include pickup dates outside configured months: " + + ", ".join(value.isoformat() for value in outside_dates[:5]) + ) + missing_dates = sorted(expected_dates - observed_dates) + if missing_dates: + preview = ", ".join(value.isoformat() for value in missing_dates[:5]) + raise ValueError( + f"NYC full raw data are missing {len(missing_dates)} configured calendar days: " + f"{preview}" + ) + expected_date_hours = { + (service_date, hour) for service_date in expected_dates for hour in range(24) + } + missing_date_hours = sorted(expected_date_hours - observed_date_hours) + if missing_date_hours: + preview = ", ".join( + f"{service_date.isoformat()}T{hour:02d}" + for service_date, hour in missing_date_hours[:5] + ) + raise ValueError( + f"NYC full raw data are missing {len(missing_date_hours)} configured date-hours: " + f"{preview}" + ) + + outputs = tuple(sorted(output_dir.rglob("*.parquet"))) + if not outputs: + raise RuntimeError("NYC full streaming normalization produced no clean parts") + return outputs, { + "strategy": "parquet_record_batch_streaming_v1", + "batch_rows": config.nyc_batch_rows, + "raw_rows": source_row_offset, + "clean_rows": source_row_offset, + "raw_row_groups": total_row_groups, + "normalized_batches": batch_index, + "clean_parts": len(outputs), + "raw_file_validation": file_validation, + "pickup_min": pickup_min.isoformat() if pickup_min else None, + "pickup_max": pickup_max.isoformat() if pickup_max else None, + "configured_calendar_days": len(expected_dates), + "observed_calendar_days": len(observed_dates), + "configured_date_hours": len(expected_date_hours), + "observed_date_hours": len(observed_date_hours), + "complete_calendar_coverage": True, + } + + +def _open_streaming_duckdb( + clean_files: Sequence[Path], + temporary_dir: Path, +) -> duckdb.DuckDBPyConnection: + temporary_dir.mkdir(parents=True, exist_ok=True) + connection = duckdb.connect() + connection.execute("SET memory_limit = '1GB'") + # A single aggregation thread makes floating-point reduction order and Parquet + # row-group boundaries reproducible across identical full-month reruns. + connection.execute("SET threads = 1") + connection.execute(f"SET temp_directory = {_sql_string(str(temporary_dir.resolve()))}") + connection.execute( + f"CREATE TEMP VIEW clean_trips AS SELECT * FROM {_parquet_scan_sql(clean_files)}" + ) + return connection + + +def _streaming_zone_query(frequency: str) -> str: + interval = _duckdb_interval(frequency) + missing_zone = _sql_string(MISSING_ZONE_ID) + return f""" + WITH usable AS ( + SELECT + source, + zone_type, + coalesce(pickup_zone_id, {missing_zone}) AS zone_id, + coalesce(dropoff_zone_id, {missing_zone}) AS dropoff_zone_id, + pickup_zone_id IS NOT NULL AND dropoff_zone_id IS NOT NULL + AS od_pair_observed, + time_bucket({interval}, pickup_datetime) AS time_bin, + fare, + trip_seconds, + trip_miles, + shared_requested, + shared_matched, + airport_trip, + pickup_census_tract_missing_or_suppressed, + reported_timestamp_rounding_minutes, + reported_fare_rounding_increment + FROM clean_trips + WHERE pickup_datetime IS NOT NULL + ), grouped AS ( + SELECT + source, + zone_type, + zone_id, + time_bin, + count(*)::BIGINT AS trip_count, + CASE WHEN count(*) FILTER (WHERE od_pair_observed) > 0 + THEN count(DISTINCT dropoff_zone_id) + FILTER (WHERE od_pair_observed)::BIGINT + ELSE NULL END AS distinct_dropoff_zones, + CASE WHEN count(*) FILTER (WHERE od_pair_observed) > 0 + THEN count(*) FILTER ( + WHERE od_pair_observed AND zone_id <> dropoff_zone_id + )::BIGINT + ELSE NULL END AS outbound_trip_count, + avg(CASE WHEN od_pair_observed + THEN (zone_id = dropoff_zone_id)::DOUBLE ELSE NULL END) + AS intra_zone_share, + count(*) FILTER (WHERE od_pair_observed)::BIGINT + AS od_pair_observed_count, + avg(od_pair_observed::DOUBLE) AS od_pair_observed_share, + avg(fare) AS avg_fare, + median(fare) AS median_fare, + sum(fare) AS total_fare, + avg(trip_seconds) AS avg_trip_seconds, + avg(trip_miles) AS avg_trip_miles, + sum(trip_miles) AS total_trip_miles, + avg(shared_requested::DOUBLE) AS shared_requested_share, + avg(shared_matched::DOUBLE) AS shared_matched_share, + avg(airport_trip::DOUBLE) AS airport_trip_share, + avg(pickup_census_tract_missing_or_suppressed::DOUBLE) + AS pickup_geography_missing_or_suppressed_share, + avg((reported_timestamp_rounding_minutes IS NOT NULL)::DOUBLE) + AS timestamp_rounded_measurement_share, + avg((reported_fare_rounding_increment IS NOT NULL)::DOUBLE) + AS fare_rounded_measurement_share + FROM usable + GROUP BY source, zone_type, zone_id, time_bin + ) + SELECT + *, + time_bin::DATE AS service_date, + year(time_bin)::INTEGER AS year, + month(time_bin)::TINYINT AS month, + isodow(time_bin)::TINYINT AS day_of_week, + hour(time_bin)::TINYINT AS hour, + minute(time_bin)::TINYINT AS minute, + (isodow(time_bin) >= 6) AS is_weekend, + {_sql_string(f"pickup_zone_x_{frequency}")} AS panel_grain, + 'descriptive_real_data' AS evidence_label + FROM grouped + ORDER BY source, zone_type, zone_id, time_bin + """ + + +def _streaming_od_query(frequency: str) -> str: + interval = _duckdb_interval(frequency) + missing_zone = _sql_string(MISSING_ZONE_ID) + return f""" + WITH grouped AS ( + SELECT + source, + zone_type, + coalesce(pickup_zone_id, {missing_zone}) AS origin_zone_id, + coalesce(dropoff_zone_id, {missing_zone}) AS destination_zone_id, + time_bucket({interval}, pickup_datetime) AS time_bin, + count(*)::BIGINT AS trip_count, + avg(fare) AS avg_fare, + avg(trip_miles) AS avg_trip_miles + FROM clean_trips + WHERE pickup_datetime IS NOT NULL + GROUP BY source, zone_type, origin_zone_id, destination_zone_id, time_bin + ) + SELECT + *, + 'descriptive_real_data' AS evidence_label, + time_bin::DATE AS service_date, + year(time_bin)::INTEGER AS year, + month(time_bin)::TINYINT AS month + FROM grouped + ORDER BY source, origin_zone_id, destination_zone_id, time_bin + """ + + +def _copy_partitioned_query( + connection: duckdb.DuckDBPyConnection, + query: str, + output_dir: Path, +) -> tuple[Path, ...]: + output_dir.mkdir(parents=True, exist_ok=True) + connection.execute( + f"COPY ({query}) TO {_sql_string(str(output_dir.resolve()))} " + "(FORMAT PARQUET, COMPRESSION ZSTD, " + "PARTITION_BY (source, year, month), WRITE_PARTITION_COLUMNS)" + ) + outputs = tuple(sorted(output_dir.rglob("*.parquet"))) + if not outputs: + raise RuntimeError("streaming aggregation produced no Parquet output") + return outputs + + +def _streaming_diagnostics( + connection: duckdb.DuckDBPyConnection, +) -> dict[str, Any]: + columns = CLEAN_TRIP_SCHEMA.names() + null_expressions = [ + f"count(*) FILTER (WHERE \"{column}\" IS NULL)::BIGINT AS null_{index}" + for index, column in enumerate(columns) + ] + summary = connection.execute( + "SELECT count(*)::BIGINT AS rows, " + + ", ".join(null_expressions) + + ", count(DISTINCT trip_id)::BIGINT AS distinct_trip_ids, " + "count(*) FILTER (WHERE trip_seconds <= 0)::BIGINT AS nonpositive_seconds, " + "count(*) FILTER (WHERE trip_miles < 0)::BIGINT AS negative_miles, " + "count(*) FILTER (WHERE fare < 0)::BIGINT AS negative_fare " + "FROM clean_trips" + ).fetchone() + if summary is None: + raise RuntimeError("streaming diagnostics returned no summary") + rows = int(summary[0]) + null_counts = {column: int(summary[index + 1]) for index, column in enumerate(columns)} + metric_offset = 1 + len(columns) + distinct_trip_ids = int(summary[metric_offset]) + nonpositive_seconds = int(summary[metric_offset + 1]) + negative_miles = int(summary[metric_offset + 2]) + negative_fare = int(summary[metric_offset + 3]) + sources = [ + str(row[0]) + for row in connection.execute( + "SELECT DISTINCT source FROM clean_trips WHERE source IS NOT NULL ORDER BY source" + ).fetchall() + ] + + pickup_indicator = "pickup_census_tract_missing_or_suppressed" + dropoff_indicator = "dropoff_census_tract_missing_or_suppressed" + availability = connection.execute( + f""" + SELECT + count({pickup_indicator})::BIGINT, + count(*) FILTER (WHERE {pickup_indicator} IS TRUE)::BIGINT, + count({dropoff_indicator})::BIGINT, + count(*) FILTER (WHERE {dropoff_indicator} IS TRUE)::BIGINT, + avg(pickup_on_15_minute_grid::DOUBLE), + avg(fare_on_declared_grid::DOUBLE) + FROM clean_trips + """ + ).fetchone() + if availability is None: + raise RuntimeError("streaming diagnostics returned no availability summary") + pickup_known, pickup_suppressed, dropoff_known, dropoff_suppressed = ( + int(value) for value in availability[:4] + ) + timestamp_increments = [ + int(row[0]) + for row in connection.execute( + "SELECT DISTINCT reported_timestamp_rounding_minutes FROM clean_trips " + "WHERE reported_timestamp_rounding_minutes IS NOT NULL ORDER BY 1" + ).fetchall() + ] + fare_increments = [ + float(row[0]) + for row in connection.execute( + "SELECT DISTINCT reported_fare_rounding_increment FROM clean_trips " + "WHERE reported_fare_rounding_increment IS NOT NULL ORDER BY 1" + ).fetchall() + ] + missingness = { + column: { + "count": null_counts[column], + "rate": (null_counts[column] / rows if rows else None), + } + for column in columns + } + diagnostics = { + "schema_version": SCHEMA_VERSION, + "row_count": rows, + "sources": sources, + "missingness": missingness, + "suppression_or_nonreporting": { + "pickup_census_tract_count": pickup_suppressed, + "pickup_census_tract_rate": ( + pickup_suppressed / pickup_known if pickup_known else None + ), + "pickup_indicator_known_count": pickup_known, + "pickup_indicator_status": ( + "available" + if pickup_known == rows + else "unavailable" + if not pickup_known + else "partial" + ), + "dropoff_census_tract_count": dropoff_suppressed, + "dropoff_census_tract_rate": ( + dropoff_suppressed / dropoff_known if dropoff_known else None + ), + "dropoff_indicator_known_count": dropoff_known, + "dropoff_indicator_status": ( + "available" + if dropoff_known == rows + else "unavailable" + if not dropoff_known + else "partial" + ), + "interpretation": ( + "Null availability indicators mean the source does not report the field; they " + "must not be recoded as unsuppressed. Chicago blank census tracts may be " + "privacy-suppressed or outside Chicago, and no record-level mechanism is claimed." + ), + }, + "rounding": { + "pickup_on_15_minute_grid_rate": ( + float(availability[4]) if availability[4] is not None else None + ), + "fare_on_declared_grid_rate": ( + float(availability[5]) if availability[5] is not None else None + ), + "declared_timestamp_rounding_minutes": timestamp_increments, + "declared_fare_rounding_increments": fare_increments, + "interpretation": ( + "Grid conformance verifies reported-value patterns; it does not recover " + "latent exact fares or timestamps." + ), + }, + "validity": { + "duplicate_trip_id_count": rows - distinct_trip_ids, + "missing_trip_id_count": null_counts["trip_id"], + "nonpositive_trip_seconds_count": nonpositive_seconds, + "negative_trip_miles_count": negative_miles, + "negative_fare_count": negative_fare, + "utc_conversion_null_count": null_counts["pickup_datetime_utc"], + }, + "source_caveats": { + source: SOURCE_METADATA[source]["known_measurement"] for source in sources + }, + } + return _json_safe(diagnostics) + + +def _aggregate_nyc_full_from_clean( + clean_files: Sequence[Path], + config: DataConfig, + zone_output_dir: Path, + od_output_dir: Path, + temporary_dir: Path, +) -> tuple[tuple[Path, ...], tuple[Path, ...], dict[str, Any], dict[str, int]]: + connection = _open_streaming_duckdb(clean_files, temporary_dir) + try: + observed_panel = connection.sql( + _streaming_zone_query(config.panel_frequency) + ).pl() + observed_panel_rows = observed_panel.height + panel = ( + _complete_zone_time_grid(observed_panel, config.panel_frequency) + if config.complete_panel_grid + else observed_panel + ) + panel_files = write_partitioned_parquet( + panel, + zone_output_dir, + partition_by=("source", "year", "month"), + ) + od_files = _copy_partitioned_query( + connection, + _streaming_od_query(config.panel_frequency), + od_output_dir, + ) + eligible_rows = int( + connection.execute( + "SELECT count(*) FROM clean_trips WHERE pickup_datetime IS NOT NULL" + ).fetchone()[0] + ) + od_stats = connection.execute( + f"SELECT count(*)::BIGINT, coalesce(sum(trip_count), 0)::BIGINT " + f"FROM {_parquet_scan_sql(od_files)}" + ).fetchone() + if od_stats is None: + raise RuntimeError("OD aggregation returned no validation summary") + panel_trip_sum = int(panel.get_column("trip_count").sum() or 0) + od_rows = int(od_stats[0]) + od_trip_sum = int(od_stats[1]) + if panel_trip_sum != eligible_rows or od_trip_sum != eligible_rows: + raise RuntimeError( + "NYC full aggregation failed row conservation: " + f"eligible={eligible_rows}, zone={panel_trip_sum}, od={od_trip_sum}" + ) + diagnostics = _streaming_diagnostics(connection) + counts = { + "eligible_trip_rows": eligible_rows, + "zone_time_rows": panel.height, + "observed_zone_time_rows": observed_panel_rows, + "synthesized_zone_time_rows": panel.height - observed_panel_rows, + "zone_time_trip_sum": panel_trip_sum, + "od_flow_rows": od_rows, + "od_flow_trip_sum": od_trip_sum, + } + return panel_files, od_files, diagnostics, counts + finally: + connection.close() + + +def _run_nyc_full_pipeline( + config: DataConfig, + raw_files: Sequence[Path], +) -> PipelineArtifacts: + clean_target = config.clean_dir / "trips" + zone_target = config.panel_dir / "zone_time" + od_target = config.panel_dir / "od_flow" + clean_staging = _new_staging_directory(clean_target) + zone_staging = _new_staging_directory(zone_target) + od_staging = _new_staging_directory(od_target) + duckdb_temporary = _new_staging_directory(config.clean_dir / "duckdb_spill") + staging_paths = (clean_staging, zone_staging, od_staging, duckdb_temporary) + try: + staged_clean_files, streaming = _stream_normalize_nyc_full( + raw_files, + config, + clean_staging, + ) + _, _, diagnostics, counts = _aggregate_nyc_full_from_clean( + staged_clean_files, + config, + zone_staging, + od_staging, + duckdb_temporary, + ) + if int(streaming["clean_rows"]) != int(diagnostics["row_count"]): + raise RuntimeError("NYC full clean rows disagree with diagnostics") + if int(streaming["clean_rows"]) < counts["eligible_trip_rows"]: + raise RuntimeError("NYC full eligible trip count exceeds clean row count") + + _replace_directory(clean_staging, clean_target) + _replace_directory(zone_staging, zone_target) + _replace_directory(od_staging, od_target) + clean_files = tuple(sorted(clean_target.rglob("*.parquet"))) + panel_files = tuple(sorted(zone_target.rglob("*.parquet"))) + od_flow_files = tuple(sorted(od_target.rglob("*.parquet"))) + _atomic_json(diagnostics, config.diagnostics_path) + + streaming["row_conservation"] = { + "raw_rows": int(streaming["raw_rows"]), + "clean_rows": int(streaming["clean_rows"]), + "pickup_datetime_null_rows": ( + int(streaming["clean_rows"]) - counts["eligible_trip_rows"] + ), + "panel_eligible_rows": counts["eligible_trip_rows"], + "zone_time_trip_sum": counts["zone_time_trip_sum"], + "od_flow_trip_sum": counts["od_flow_trip_sum"], + "passes": True, + } + streaming["duckdb_memory_limit"] = "1GB" + streaming["duckdb_threads"] = 1 + streaming["observed_zone_time_rows"] = counts["observed_zone_time_rows"] + streaming["synthesized_zone_time_rows"] = counts[ + "synthesized_zone_time_rows" + ] + all_files = ( + *raw_files, + *clean_files, + *panel_files, + *od_flow_files, + config.diagnostics_path, + ) + write_manifest( + all_files, + config.manifest_path, + config=config, + root=config.project_root, + metadata={ + "trip_rows": int(streaming["clean_rows"]), + "zone_time_rows": counts["zone_time_rows"], + "od_flow_rows": counts["od_flow_rows"], + "evidence_label": "descriptive_real_data", + "causal_claim": False, + "full_month_processing": streaming, + }, + ) + _nyc_full_incomplete_path(config).unlink(missing_ok=True) + return PipelineArtifacts( + raw_files=tuple(raw_files), + clean_files=clean_files, + panel_files=panel_files, + od_flow_files=od_flow_files, + manifest_path=config.manifest_path, + diagnostics_path=config.diagnostics_path, + trip_rows=int(streaming["clean_rows"]), + panel_rows=counts["zone_time_rows"], + ) + finally: + for staging in staging_paths: + if staging.exists(): + shutil.rmtree(staging) + + +def _nyc_full_incomplete_path(config: DataConfig) -> Path: + return config.manifest_path.with_name("NYC_FULL_INCOMPLETE.json") + + +def _begin_nyc_full_run(config: DataConfig) -> Path: + """Publish a fail-closed run marker before raw download or cache reuse.""" + + marker = _nyc_full_incomplete_path(config) + _atomic_json( + { + "schema_version": SCHEMA_VERSION, + "status": "incomplete", + "started_at_utc": datetime.now(UTC).isoformat(), + "config": config.as_serializable_dict(), + "interpretation": ( + "The NYC full-month manifest and outputs must not be treated as a " + "successful run while this marker exists." + ), + }, + marker, + ) + config.manifest_path.unlink(missing_ok=True) + return marker + + +def run_data_pipeline( + config: DataConfig | PathLike, + *, + refresh: bool = False, +) -> PipelineArtifacts: + """Run ingestion → normalization → diagnostics → zone/OD panels → manifest.""" + + cfg = load_data_config(config) if not isinstance(config, DataConfig) else config + if cfg.source == "nyc_hvfhv" and cfg.mode == "full": + _begin_nyc_full_run(cfg) + raw_files = download_data(cfg, refresh=refresh) + return _run_nyc_full_pipeline(cfg, raw_files) + raw_files = download_data(cfg, refresh=refresh) + trips = normalize_trips(raw_files, config=cfg) + validate_clean_schema(trips) + clean_files = write_partitioned_parquet( + trips, + cfg.clean_dir / "trips", + partition_by=cfg.partition_by, + ) + panel = build_zone_time_panel( + trips, + frequency=cfg.panel_frequency, + complete_grid=cfg.complete_panel_grid, + ) + panel_partition = tuple( + column for column in ("source", "year", "month") if column in panel.columns + ) + panel_files = write_partitioned_parquet( + panel, + cfg.panel_dir / "zone_time", + partition_by=panel_partition, + ) + od_flow = build_od_flow_panel(trips, frequency=cfg.panel_frequency) + od_partition = tuple( + column for column in ("source", "year", "month") if column in od_flow.columns + ) + od_flow_files = write_partitioned_parquet( + od_flow, + cfg.panel_dir / "od_flow", + partition_by=od_partition, + ) + write_diagnostics(trips, cfg.diagnostics_path) + all_files = (*raw_files, *clean_files, *panel_files, *od_flow_files, cfg.diagnostics_path) + write_manifest( + all_files, + cfg.manifest_path, + config=cfg, + root=cfg.project_root, + metadata={ + "trip_rows": trips.height, + "zone_time_rows": panel.height, + "od_flow_rows": od_flow.height, + "evidence_label": "descriptive_real_data", + "causal_claim": False, + **( + { + "sample_selection": { + "strategy": "equal_quota_per_configured_day_hour_stable_hash_v1", + "days": list(sorted(cfg.nyc_sample_days)), + "hours": list(sorted(cfg.nyc_sample_hours)), + "requested_rows": cfg.sample_rows, + "probability_sample": False, + "population_weighted": False, + } + } + if cfg.source == "nyc_hvfhv" and cfg.mode == "sample" + else {} + ), + }, + ) + return PipelineArtifacts( + raw_files=tuple(raw_files), + clean_files=clean_files, + panel_files=panel_files, + od_flow_files=od_flow_files, + manifest_path=cfg.manifest_path, + diagnostics_path=cfg.diagnostics_path, + trip_rows=trips.height, + panel_rows=panel.height, + ) + + +__all__ = [ + "CHICAGO_DATASET_ID", + "CHICAGO_RAW_SCHEMA", + "CLEAN_TRIP_SCHEMA", + "DataConfig", + "MISSING_ZONE_ID", + "NYC_HVFHV_RAW_SCHEMA", + "PipelineArtifacts", + "build_od_flow_panel", + "build_zone_time_panel", + "chicago_query_url", + "chicago_sample_urls", + "data_quality_diagnostics", + "download_data", + "download_sample", + "load_data_config", + "materialize_nyc_hvfhv_sample", + "normalize_trips", + "nyc_hvfhv_urls", + "read_partitioned_parquet", + "run_data_pipeline", + "sha256_file", + "validate_clean_schema", + "write_diagnostics", + "write_manifest", + "write_partitioned_parquet", +] diff --git a/CasualLab/src/casuallab/designs.py b/CasualLab/src/casuallab/designs.py new file mode 100644 index 0000000000000000000000000000000000000000..4de42da19355cb8bedf55fbea453986de16285b9 --- /dev/null +++ b/CasualLab/src/casuallab/designs.py @@ -0,0 +1,485 @@ +"""Randomization mechanisms for marketplace experiments. + +Every generator returns the same explicit assignment schema. In particular, +``assigned_treatment`` records the randomized arm (the ITT instrument), while +``treatment`` records realized exposure after partial saturation. The simulator may +subsequently attenuate ``treatment`` to respect a budget, but never rewrites the arm. +""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import replace + +import numpy as np +import pandas as pd + +from .config import DesignConfig, DesignName + +ASSIGNMENT_COLUMNS = ( + "zone_id", + "period_id", + "design", + "cluster_id", + "time_block", + "randomization_cluster", + "assigned_treatment", + "treatment", + "treatment_probability", + "analysis_eligible", + "washout", + "assignment_seed", +) + + +def _coerce_config(config: DesignConfig | str | None) -> DesignConfig: + if config is None: + return DesignConfig() + if isinstance(config, DesignConfig): + return config + return DesignConfig(name=DesignName.parse(config)) + + +def _prepare_units( + units: pd.DataFrame | int, + n_periods: int | None = None, +) -> pd.DataFrame: + if isinstance(units, (int, np.integer)): + n_zones = int(units) + if n_zones < 1 or n_periods is None or n_periods < 1: + raise ValueError("positive n_zones and n_periods are required") + grid = pd.MultiIndex.from_product( + [range(n_periods), range(n_zones)], + names=["period_id", "zone_id"], + ).to_frame(index=False) + grid["unit_id"] = np.arange(len(grid), dtype=int) + return grid + + frame = units.copy().reset_index(drop=True) + rename: dict[str, str] = {} + if "zone_id" not in frame and "zone" in frame: + rename["zone"] = "zone_id" + if "period_id" not in frame and "period" in frame: + rename["period"] = "period_id" + frame = frame.rename(columns=rename) + missing = {"zone_id", "period_id"}.difference(frame.columns) + if missing: + raise ValueError(f"assignment units missing columns: {sorted(missing)}") + if frame.empty: + raise ValueError("assignment units must not be empty") + if frame[["zone_id", "period_id"]].isna().any().any(): + raise ValueError("zone_id and period_id cannot contain missing values") + if "unit_id" not in frame: + frame["unit_id"] = np.arange(len(frame), dtype=int) + return frame + + +def _complete_randomization( + n_groups: int, + probability: float, + rng: np.random.Generator, +) -> np.ndarray: + """Balanced complete randomization with a Bernoulli fallback for one group.""" + + if n_groups < 1: + raise ValueError("at least one randomization group is required") + if n_groups == 1: + return np.asarray([float(rng.random() < probability)]) + n_treated = int(np.rint(probability * n_groups)) + n_treated = min(max(n_treated, 1), n_groups - 1) + result = np.zeros(n_groups, dtype=float) + result[rng.permutation(n_groups)[:n_treated]] = 1.0 + return result + + +def _marginal_probability(arms: np.ndarray, configured_probability: float) -> float: + """Return fixed-count inclusion probability or Bernoulli p for one group.""" + + return ( + float(configured_probability) + if len(arms) == 1 + else float(np.asarray(arms, dtype=float).mean()) + ) + + +def _zone_clusters(frame: pd.DataFrame, config: DesignConfig) -> pd.Series: + zones = np.asarray(sorted(frame["zone_id"].unique())) + n_zones = len(zones) + if config.n_clusters is not None: + if config.n_clusters > n_zones: + raise ValueError("n_clusters cannot exceed the number of observed zones") + cluster_for_rank = np.floor(np.arange(n_zones) * config.n_clusters / n_zones).astype(int) + else: + cluster_for_rank = np.arange(n_zones) // config.cluster_size + mapping = dict(zip(zones.tolist(), cluster_for_rank.tolist(), strict=True)) + return frame["zone_id"].map(mapping).astype(int) + + +def _mark_washout(frame: pd.DataFrame, periods: int, *, by_cluster: bool) -> pd.DataFrame: + result = frame.copy() + result["washout"] = 0 + if periods == 0: + result["analysis_eligible"] = 1 + return result + + group_columns = ["cluster_id"] if by_cluster else [] + schedules = ( + result[[*group_columns, "period_id", "assigned_treatment"]] + .drop_duplicates() + .sort_values([*group_columns, "period_id"]) + ) + if group_columns: + grouped = schedules.groupby(group_columns, sort=False, dropna=False) + else: + grouped = [(None, schedules)] + washout_keys: set[tuple[int, int] | int] = set() + for group, schedule in grouped: + prior: float | None = None + ordered = schedule.sort_values("period_id") + for row in ordered.itertuples(index=False): + current = float(row.assigned_treatment) + period = int(row.period_id) + if prior is not None and current != prior: + for offset in range(periods): + if by_cluster: + cluster = int(group[0] if isinstance(group, tuple) else group) + washout_keys.add((cluster, period + offset)) + else: + washout_keys.add(period + offset) + prior = current + + if by_cluster: + keys = list( + zip( + result["cluster_id"].astype(int), + result["period_id"].astype(int), + strict=True, + ) + ) + result["washout"] = [int(key in washout_keys) for key in keys] + else: + result["washout"] = result["period_id"].astype(int).isin(washout_keys).astype(int) + result["analysis_eligible"] = 1 - result["washout"] + return result + + +def _finalize( + frame: pd.DataFrame, + config: DesignConfig, + seed: int, + *, + washout_by_cluster: bool = False, +) -> pd.DataFrame: + result = frame.copy() + result["assigned_treatment"] = result["assigned_treatment"].astype(float) + result["treatment"] = ( + result["assigned_treatment"].to_numpy(dtype=float) * config.treatment_saturation + ) + result["treatment_intensity"] = result["treatment"] + result["assignment"] = result["assigned_treatment"] + if "treatment_probability" not in result: + result["treatment_probability"] = float(config.treatment_probability) + result["design"] = config.name.value + result["assignment_seed"] = int(seed) + if "cluster_id" not in result: + result["cluster_id"] = result["unit_id"] + if "time_block" not in result: + result["time_block"] = result["period_id"] + if "randomization_cluster" not in result: + result["randomization_cluster"] = result["cluster_id"].astype(str) + temporal_designs = {DesignName.TIME_BLOCK, DesignName.SWITCHBACK, DesignName.GEO_TIME} + if config.name in temporal_designs: + result = _mark_washout( + result, + config.washout_periods, + by_cluster=washout_by_cluster, + ) + else: + # Washout is a temporal carryover exclusion. Contemporaneous differences + # between geographic arms are not switches and must never trigger it. + result["washout"] = 0 + result["analysis_eligible"] = 1 + return result + + +def individual_randomization( + units: pd.DataFrame | int, + config: DesignConfig | None = None, + *, + n_periods: int | None = None, + seed: int | None = None, +) -> pd.DataFrame: + """Randomize individual rows, or binomial shares for aggregated cells. + + If ``unit_count`` is present, each row is interpreted as an aggregated cell and + the returned assignment is its randomized individual share. Otherwise rows are + individual experimental units and receive binary arms. + """ + + cfg = _coerce_config(config or DesignConfig(name=DesignName.INDIVIDUAL)) + cfg = replace(cfg, name=DesignName.INDIVIDUAL) + actual_seed = cfg.seed if seed is None and cfg.seed is not None else (0 if seed is None else seed) + rng = np.random.default_rng(actual_seed) + frame = _prepare_units(units, n_periods) + if "unit_count" in frame: + counts = frame["unit_count"].to_numpy(dtype=int) + if (counts < 1).any(): + raise ValueError("unit_count must contain positive integers") + treated = rng.binomial(counts, cfg.treatment_probability) + frame["treated_units"] = treated + frame["assigned_treatment"] = treated / counts + frame["treatment_probability"] = cfg.treatment_probability + frame["cluster_id"] = frame["unit_id"] + frame["randomization_cluster"] = "individuals_in_" + frame["unit_id"].astype(str) + else: + frame["assigned_treatment"] = _complete_randomization( + len(frame), cfg.treatment_probability, rng + ) + frame["treatment_probability"] = _marginal_probability( + frame["assigned_treatment"].to_numpy(dtype=float), + cfg.treatment_probability, + ) + frame["cluster_id"] = frame["unit_id"] + frame["randomization_cluster"] = frame["unit_id"].astype(str) + return _finalize(frame, cfg, int(actual_seed)) + + +def geo_cluster_randomization( + units: pd.DataFrame | int, + config: DesignConfig | None = None, + *, + n_periods: int | None = None, + seed: int | None = None, +) -> pd.DataFrame: + """Assign geographic clusters once and hold their arm over all periods.""" + + cfg = _coerce_config(config or DesignConfig(name=DesignName.GEO_CLUSTER)) + cfg = replace(cfg, name=DesignName.GEO_CLUSTER) + actual_seed = cfg.seed if seed is None and cfg.seed is not None else (0 if seed is None else seed) + rng = np.random.default_rng(actual_seed) + frame = _prepare_units(units, n_periods) + frame["cluster_id"] = _zone_clusters(frame, cfg) + clusters = np.asarray(sorted(frame["cluster_id"].unique())) + arms = _complete_randomization(len(clusters), cfg.treatment_probability, rng) + mapping = dict(zip(clusters.tolist(), arms.tolist(), strict=True)) + frame["assigned_treatment"] = frame["cluster_id"].map(mapping) + frame["treatment_probability"] = _marginal_probability( + arms, cfg.treatment_probability + ) + frame["randomization_cluster"] = "geo_" + frame["cluster_id"].astype(str) + return _finalize(frame, cfg, int(actual_seed)) + + +def time_block_randomization( + units: pd.DataFrame | int, + config: DesignConfig | None = None, + *, + n_periods: int | None = None, + seed: int | None = None, +) -> pd.DataFrame: + """Randomize common marketplace-wide time blocks.""" + + cfg = _coerce_config(config or DesignConfig(name=DesignName.TIME_BLOCK)) + cfg = replace(cfg, name=DesignName.TIME_BLOCK) + actual_seed = cfg.seed if seed is None and cfg.seed is not None else (0 if seed is None else seed) + rng = np.random.default_rng(actual_seed) + frame = _prepare_units(units, n_periods) + period_rank = {period: rank for rank, period in enumerate(sorted(frame["period_id"].unique()))} + frame["time_block"] = frame["period_id"].map(period_rank).astype(int) // cfg.treatment_duration + blocks = np.asarray(sorted(frame["time_block"].unique())) + arms = _complete_randomization(len(blocks), cfg.treatment_probability, rng) + mapping = dict(zip(blocks.tolist(), arms.tolist(), strict=True)) + frame["assigned_treatment"] = frame["time_block"].map(mapping) + frame["treatment_probability"] = _marginal_probability( + arms, cfg.treatment_probability + ) + frame["cluster_id"] = frame["time_block"] + frame["randomization_cluster"] = "time_" + frame["time_block"].astype(str) + return _finalize(frame, cfg, int(actual_seed)) + + +def switchback_randomization( + units: pd.DataFrame | int, + config: DesignConfig | None = None, + *, + n_periods: int | None = None, + seed: int | None = None, +) -> pd.DataFrame: + """Alternate the entire marketplace between treatment and control blocks.""" + + cfg = _coerce_config(config or DesignConfig(name=DesignName.SWITCHBACK)) + cfg = replace(cfg, name=DesignName.SWITCHBACK) + actual_seed = cfg.seed if seed is None and cfg.seed is not None else (0 if seed is None else seed) + rng = np.random.default_rng(actual_seed) + frame = _prepare_units(units, n_periods) + period_rank = {period: rank for rank, period in enumerate(sorted(frame["period_id"].unique()))} + frame["time_block"] = frame["period_id"].map(period_rank).astype(int) // cfg.treatment_duration + frame["switchback_pair"] = frame["time_block"].astype(int) // 2 + pairs = np.asarray(sorted(frame["switchback_pair"].unique())) + first_arms = rng.binomial(1, cfg.treatment_probability, size=len(pairs)) + first_mapping = dict(zip(pairs.tolist(), first_arms.tolist(), strict=True)) + pair_first = frame["switchback_pair"].map(first_mapping).astype(int) + within_pair = frame["time_block"].astype(int) % 2 + frame["assigned_treatment"] = (pair_first + within_pair) % 2 + frame["treatment_probability"] = np.where( + within_pair == 0, + cfg.treatment_probability, + 1.0 - cfg.treatment_probability, + ) + frame["cluster_id"] = frame["switchback_pair"] + frame["randomization_cluster"] = "switch_pair_" + frame["switchback_pair"].astype(str) + return _finalize(frame, cfg, int(actual_seed)) + + +def geo_time_randomization( + units: pd.DataFrame | int, + config: DesignConfig | None = None, + *, + n_periods: int | None = None, + seed: int | None = None, +) -> pd.DataFrame: + """Randomize geographic-cluster by time-block cells.""" + + cfg = _coerce_config(config or DesignConfig(name=DesignName.GEO_TIME)) + cfg = replace(cfg, name=DesignName.GEO_TIME) + actual_seed = cfg.seed if seed is None and cfg.seed is not None else (0 if seed is None else seed) + rng = np.random.default_rng(actual_seed) + frame = _prepare_units(units, n_periods) + frame["cluster_id"] = _zone_clusters(frame, cfg) + period_rank = {period: rank for rank, period in enumerate(sorted(frame["period_id"].unique()))} + frame["time_block"] = frame["period_id"].map(period_rank).astype(int) // cfg.treatment_duration + cells = frame[["cluster_id", "time_block"]].drop_duplicates().sort_values( + ["time_block", "cluster_id"] + ) + arms = _complete_randomization(len(cells), cfg.treatment_probability, rng) + mapping = { + (int(row.cluster_id), int(row.time_block)): float(arm) + for row, arm in zip(cells.itertuples(index=False), arms, strict=True) + } + keys = zip(frame["cluster_id"].astype(int), frame["time_block"].astype(int), strict=True) + frame["assigned_treatment"] = [mapping[key] for key in keys] + frame["treatment_probability"] = _marginal_probability( + arms, cfg.treatment_probability + ) + frame["randomization_cluster"] = ( + "geo_" + frame["cluster_id"].astype(str) + "_time_" + frame["time_block"].astype(str) + ) + return _finalize(frame, cfg, int(actual_seed), washout_by_cluster=True) + + +_GENERATORS: dict[DesignName, Callable[..., pd.DataFrame]] = { + DesignName.INDIVIDUAL: individual_randomization, + DesignName.GEO_CLUSTER: geo_cluster_randomization, + DesignName.TIME_BLOCK: time_block_randomization, + DesignName.SWITCHBACK: switchback_randomization, + DesignName.GEO_TIME: geo_time_randomization, +} + + +def assign_treatment( + units: pd.DataFrame, + config: DesignConfig | str, + *, + seed: int | None = None, +) -> pd.DataFrame: + """Assign treatment to an existing unit frame using a named design.""" + + cfg = _coerce_config(config) + return _GENERATORS[cfg.name](units, cfg, seed=seed) + + +def generate_assignment( + n_zones: int, + n_periods: int, + config: DesignConfig | str | None = None, + *, + seed: int | None = None, + individuals_per_cell: int | None = None, +) -> pd.DataFrame: + """Generate a canonical zone-period assignment frame. + + ``individuals_per_cell`` activates a binomial partial-saturation assignment for + the individual design; other designs ignore it because their assignment unit is + a market cluster or time block. + """ + + cfg = _coerce_config(config) + frame = _prepare_units(n_zones, n_periods) + if cfg.name is DesignName.INDIVIDUAL and individuals_per_cell is not None: + if individuals_per_cell < 1: + raise ValueError("individuals_per_cell must be positive") + frame["unit_count"] = int(individuals_per_cell) + return _GENERATORS[cfg.name](frame, cfg, seed=seed) + + +def assignment_for_design( + design: DesignName | str, + n_zones: int, + n_periods: int, + **kwargs: object, +) -> pd.DataFrame: + """Convenience keyed dispatcher for interactive callers.""" + + config_fields = { + key: value + for key, value in kwargs.items() + if key + in { + "treatment_probability", + "treatment_saturation", + "n_clusters", + "cluster_size", + "treatment_duration", + "washout_periods", + "budget", + "seed", + } + } + cfg = DesignConfig(name=DesignName.parse(design), **config_fields) + seed = kwargs.get("seed") + individuals = kwargs.get("individuals_per_cell") + return generate_assignment( + n_zones, + n_periods, + cfg, + seed=None if seed is None else int(seed), + individuals_per_cell=None if individuals is None else int(individuals), + ) + + +def enforce_budget( + assignments: pd.DataFrame, + cost_per_full_treatment: np.ndarray | pd.Series | float, + budget: float | None, +) -> pd.DataFrame: + """Uniformly attenuate exposure to satisfy an expected-spend constraint. + + Uniform attenuation preserves the randomized ordering and avoids post-outcome + selection. The simulator refines this scale using structural realized spend. + """ + + result = assignments.copy() + if "treatment" not in result: + raise ValueError("assignments must contain treatment") + costs = np.broadcast_to(np.asarray(cost_per_full_treatment, dtype=float), len(result)) + if not np.isfinite(costs).all() or (costs < 0).any(): + raise ValueError("cost_per_full_treatment must be finite and non-negative") + if budget is not None and budget < 0: + raise ValueError("budget cannot be negative") + planned = result["treatment"].to_numpy(dtype=float) + gross_cost = float(np.dot(planned, costs)) + scale = 1.0 if budget is None or gross_cost <= budget else float(budget / gross_cost) + result["planned_treatment"] = planned + result["treatment"] = planned * scale + result["treatment_intensity"] = result["treatment"] + result["budget_scale"] = scale + result["expected_treatment_cost"] = result["treatment"] * costs + return result + + +# Short aliases are useful in notebooks while the explicit names remain discoverable. +individual = individual_randomization +geo_cluster = geo_cluster_randomization +time_block = time_block_randomization +switchback = switchback_randomization +geo_time = geo_time_randomization diff --git a/CasualLab/src/casuallab/enrichments.py b/CasualLab/src/casuallab/enrichments.py new file mode 100644 index 0000000000000000000000000000000000000000..8cb664085a92b42bded7c3dab3a769e6f891c6a2 --- /dev/null +++ b/CasualLab/src/casuallab/enrichments.py @@ -0,0 +1,163 @@ +"""Optional weather, calendar, event, transit, and neighborhood panel adapters. + +Adapters are intentionally file- and schema-driven. Missing optional inputs remain +missing and visible; they are never converted to "normal weather" or "no event". +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +import pandas as pd + + +@dataclass(frozen=True) +class EnrichmentAdapter: + """Declarative join contract for one optional external source.""" + + name: str + path: Path | None + panel_keys: tuple[str, ...] + source_keys: tuple[str, ...] | None = None + value_columns: tuple[str, ...] = () + required: bool = False + evidence_type: str = "observed_external_covariate" + source_metadata: dict[str, Any] = field(default_factory=dict) + + def __post_init__(self) -> None: + if not self.name.strip(): + raise ValueError("enrichment name must not be empty") + if not self.panel_keys: + raise ValueError("panel_keys must not be empty") + source_keys = self.source_keys or self.panel_keys + if len(source_keys) != len(self.panel_keys): + raise ValueError("panel_keys and source_keys must have the same length") + + +@dataclass(frozen=True) +class EnrichmentResult: + panel: pd.DataFrame + diagnostics: pd.DataFrame + + +def optional_adapter_registry() -> dict[str, dict[str, object]]: + """Return documented feature contracts without requiring any external files.""" + + return { + "weather": { + "typical_keys": ["time_bin"], + "candidate_values": ["temperature", "precipitation", "snowfall", "wind_speed"], + "caution": "Weather controls improve description/precision but do not instrument price.", + }, + "holidays": { + "typical_keys": ["service_date"], + "candidate_values": ["holiday_name", "is_holiday"], + "caution": "Unmatched dates are unknown until source coverage is verified.", + }, + "events": { + "typical_keys": ["zone_id", "time_bin"], + "candidate_values": ["event_intensity", "venue_capacity", "event_category"], + "caution": "Event occurrence may be endogenous to location and season.", + }, + "transit_disruptions": { + "typical_keys": ["zone_id", "time_bin"], + "candidate_values": ["disruption_intensity", "affected_routes"], + "caution": "Reported and unreported disruptions have different missingness mechanisms.", + }, + "neighborhood": { + "typical_keys": ["zone_id"], + "candidate_values": ["income_index", "population", "vehicle_access", "demographics"], + "caution": "Area characteristics are ecological and are not rider-level attributes.", + }, + } + + +def _read_source(path: Path) -> pd.DataFrame: + suffix = path.suffix.lower() + if suffix == ".csv": + return pd.read_csv(path) + if suffix in {".parquet", ".pq"}: + return pd.read_parquet(path) + raise ValueError(f"unsupported enrichment format for {path}; use CSV or Parquet") + + +def apply_optional_enrichments( + panel: pd.DataFrame, + adapters: list[EnrichmentAdapter] | tuple[EnrichmentAdapter, ...], +) -> EnrichmentResult: + """Left-join available enrichments and return row-coverage diagnostics.""" + + result = panel.copy() + if result.empty: + raise ValueError("panel must not be empty") + diagnostics: list[dict[str, object]] = [] + for adapter in adapters: + source_keys = adapter.source_keys or adapter.panel_keys + missing_panel = set(adapter.panel_keys).difference(result.columns) + if missing_panel: + raise ValueError( + f"panel missing keys for {adapter.name}: {sorted(missing_panel)}" + ) + if adapter.path is None or not Path(adapter.path).exists(): + if adapter.required: + raise FileNotFoundError(f"required {adapter.name} enrichment is unavailable") + diagnostics.append( + { + "name": adapter.name, + "status": "unavailable_optional", + "matched_rows": 0, + "total_rows": len(result), + "coverage_rate": None, + "evidence_type": adapter.evidence_type, + } + ) + continue + + source = _read_source(Path(adapter.path)) + missing_source = set(source_keys).difference(source.columns) + if missing_source: + raise ValueError( + f"{adapter.name} source missing keys: {sorted(missing_source)}" + ) + values = adapter.value_columns or tuple( + column for column in source.columns if column not in source_keys + ) + missing_values = set(values).difference(source.columns) + if missing_values: + raise ValueError( + f"{adapter.name} source missing values: {sorted(missing_values)}" + ) + selected = source[[*source_keys, *values]].copy() + if selected.duplicated(list(source_keys)).any(): + raise ValueError( + f"{adapter.name} source has duplicate join keys; aggregate explicitly first" + ) + + rename = dict(zip(source_keys, adapter.panel_keys, strict=True)) + value_rename = {column: f"{adapter.name}__{column}" for column in values} + selected = selected.rename(columns={**rename, **value_rename}) + marker = f"_{adapter.name}_matched" + selected[marker] = True + result = result.merge( + selected, + on=list(adapter.panel_keys), + how="left", + validate="many_to_one", + ) + matched = int(result[marker].fillna(False).sum()) + result = result.drop(columns=marker) + diagnostics.append( + { + "name": adapter.name, + "status": "joined", + "matched_rows": matched, + "total_rows": len(result), + "coverage_rate": matched / len(result), + "evidence_type": adapter.evidence_type, + "source_metadata": adapter.source_metadata, + } + ) + return EnrichmentResult(result, pd.DataFrame(diagnostics)) + diff --git a/CasualLab/src/casuallab/equilibrium.py b/CasualLab/src/casuallab/equilibrium.py new file mode 100644 index 0000000000000000000000000000000000000000..f9a3a64b1c223efc4b5e5694d0fa0353a39d9309 --- /dev/null +++ b/CasualLab/src/casuallab/equilibrium.py @@ -0,0 +1,1249 @@ +"""Transparent fixed-point equilibrium benchmark for a two-sided ride-hailing market. + +This module is deliberately a small theoretical benchmark, not an empirical or +NYC structural estimate. Conditional on one seeded exogenous market state, it +solves control and policy counterfactuals with common random numbers. + +For zone ``z``, let ``x_z = log(wait_z / base_wait)``. At a candidate state, + +``D_z(x) = A_z exp(beta_p * discount_z - eta_d * x_z)`` + +``S_z(x) = B_z exp(beta_i * incentive_z / reference_incentive + eta_s * x_z)`` + +``F_z(x) = gamma * [(1-kappa) log(D_z / (capacity*S_z)) + + kappa sum_j W_zj log(D_j / (capacity*S_j))]``. + +An equilibrium satisfies ``x = F(x)``. ``W`` is a row-normalized ring network +and ``kappa`` can disable or activate the cross-zone congestion channel. Because +the network mixture is non-expansive in the sup norm, a transparent sufficient +condition for a unique equilibrium and convergence is +``gamma * (eta_d + eta_s) < 1``. The solver fails closed when this condition is +not met or when the reported residual does not reach the configured tolerance. +""" + +from __future__ import annotations + +import hashlib +import json +import tempfile +from collections.abc import Mapping, Sequence +from dataclasses import asdict, dataclass, fields +from math import isfinite +from numbers import Integral, Real +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd + +from .config import TreatmentVersion + +EVIDENCE_TYPE = "theoretical_simulation_known_ground_truth" +CAUSAL_SCOPE = "within_declared_equilibrium_model_only" +EMPIRICAL_STATUS = "not_an_empirical_or_nyc_structural_estimate" + + +@dataclass(frozen=True, slots=True) +class EquilibriumConfig: + """Assumptions and numerical tolerances for the equilibrium benchmark.""" + + n_zones: int = 2 + seed: int = 202_503 + base_demand: float = 100.0 + base_drivers: float = 72.0 + demand_shock_sd: float = 0.08 + supply_shock_sd: float = 0.06 + base_fare: float = 20.0 + base_wait_minutes: float = 5.0 + capacity_per_driver: float = 1.30 + demand_price_semielasticity: float = 1.20 + demand_wait_elasticity: float = 0.28 + supply_incentive_semielasticity: float = 0.30 + supply_wait_elasticity: float = 0.14 + congestion_elasticity: float = 0.70 + cross_zone_enabled: bool = True + cross_zone_share: float = 0.20 + treatment_version: TreatmentVersion = TreatmentVersion.BUNDLED + discount_rate: float = 0.10 + incentive_per_driver: float = 2.00 + reference_incentive_per_driver: float = 2.00 + rider_value_per_trip: float = 32.0 + wait_disutility_per_minute: float = 0.25 + platform_take_rate: float = 0.25 + driver_operating_cost_per_trip: float = 9.0 + driver_opportunity_cost_per_active_driver: float = 0.50 + budget: float | None = None + tolerance: float = 1e-10 + max_iterations: int = 500 + relaxation: float = 0.75 + budget_tolerance: float = 1e-8 + budget_max_iterations: int = 80 + + def __post_init__(self) -> None: + object.__setattr__( + self, + "treatment_version", + TreatmentVersion.parse(self.treatment_version), + ) + for name in ("n_zones", "seed", "max_iterations", "budget_max_iterations"): + value = getattr(self, name) + if isinstance(value, bool) or not isinstance(value, Integral): + raise ValueError(f"{name} must be an integer") + if self.n_zones < 1: + raise ValueError("n_zones must be positive") + if self.max_iterations < 1 or self.budget_max_iterations < 1: + raise ValueError("iteration limits must be positive") + if not isinstance(self.cross_zone_enabled, bool): + raise ValueError("cross_zone_enabled must be boolean") + + numeric_names = ( + "base_demand", + "base_drivers", + "demand_shock_sd", + "supply_shock_sd", + "base_fare", + "base_wait_minutes", + "capacity_per_driver", + "demand_price_semielasticity", + "demand_wait_elasticity", + "supply_incentive_semielasticity", + "supply_wait_elasticity", + "congestion_elasticity", + "cross_zone_share", + "discount_rate", + "incentive_per_driver", + "reference_incentive_per_driver", + "rider_value_per_trip", + "wait_disutility_per_minute", + "platform_take_rate", + "driver_operating_cost_per_trip", + "driver_opportunity_cost_per_active_driver", + "tolerance", + "relaxation", + "budget_tolerance", + ) + for name in numeric_names: + value = getattr(self, name) + if not isinstance(value, Real) or not isfinite(float(value)): + raise ValueError(f"{name} must be a finite number") + if self.budget is not None and ( + not isinstance(self.budget, Real) or not isfinite(float(self.budget)) + ): + raise ValueError("budget must be finite when supplied") + + for name in ( + "base_demand", + "base_drivers", + "base_fare", + "base_wait_minutes", + "capacity_per_driver", + "reference_incentive_per_driver", + "rider_value_per_trip", + "tolerance", + "budget_tolerance", + ): + if getattr(self, name) <= 0: + raise ValueError(f"{name} must be positive") + for name in ( + "demand_shock_sd", + "supply_shock_sd", + "demand_price_semielasticity", + "demand_wait_elasticity", + "supply_incentive_semielasticity", + "supply_wait_elasticity", + "congestion_elasticity", + "incentive_per_driver", + "wait_disutility_per_minute", + "driver_operating_cost_per_trip", + "driver_opportunity_cost_per_active_driver", + ): + if getattr(self, name) < 0: + raise ValueError(f"{name} cannot be negative") + if not 0 <= self.discount_rate <= 1: + raise ValueError("discount_rate must lie in [0, 1]") + if not 0 <= self.cross_zone_share <= 1: + raise ValueError("cross_zone_share must lie in [0, 1]") + if not 0 <= self.platform_take_rate <= 1: + raise ValueError("platform_take_rate must lie in [0, 1]") + if not 0 < self.relaxation <= 1: + raise ValueError("relaxation must lie in (0, 1]") + if self.budget is not None and self.budget < 0: + raise ValueError("budget cannot be negative") + + @property + def contraction_bound(self) -> float: + """Sup-norm Lipschitz bound for the raw fixed-point map ``F``.""" + + return float( + self.congestion_elasticity + * (self.demand_wait_elasticity + self.supply_wait_elasticity) + ) + + @property + def effective_iteration_bound(self) -> float: + """Conservative bound after applying the configured relaxation.""" + + return float( + 1.0 + - self.relaxation + + self.relaxation * self.contraction_bound + ) + + @classmethod + def from_mapping(cls, values: Mapping[str, object]) -> EquilibriumConfig: + """Create a config while rejecting misspelled or unsupported fields.""" + + if not isinstance(values, Mapping): + raise TypeError("equilibrium configuration must be a mapping") + allowed = {item.name for item in fields(cls)} + unknown = set(values).difference(allowed) + if unknown: + raise ValueError(f"unknown equilibrium configuration keys: {sorted(unknown)}") + return cls(**dict(values)) + + +@dataclass(frozen=True, slots=True) +class EquilibriumState: + """One immutable exogenous state shared by all counterfactual policy paths.""" + + baseline_rider_arrivals: tuple[float, ...] + baseline_driver_pool: tuple[float, ...] + seed: int + state_id: str + + def __post_init__(self) -> None: + demand = tuple(float(value) for value in self.baseline_rider_arrivals) + supply = tuple(float(value) for value in self.baseline_driver_pool) + object.__setattr__(self, "baseline_rider_arrivals", demand) + object.__setattr__(self, "baseline_driver_pool", supply) + if len(demand) == 0 or len(demand) != len(supply): + raise ValueError("exogenous demand and driver state must have equal positive length") + values = np.asarray([*demand, *supply], dtype=float) + if not np.isfinite(values).all() or (values <= 0).any(): + raise ValueError("exogenous demand and driver state must be finite and positive") + if isinstance(self.seed, bool) or not isinstance(self.seed, Integral): + raise ValueError("state seed must be an integer") + if not self.state_id: + raise ValueError("state_id cannot be empty") + + +@dataclass(frozen=True, slots=True) +class EquilibriumDiagnostics: + """Auditable numerical and identification diagnostics for one solution.""" + + converged: bool + iterations: int + initial_residual_sup_norm: float | None + residual_sup_norm: float | None + step_sup_norm: float | None + tolerance: float + contraction_bound: float + effective_iteration_bound: float + uniqueness_condition_satisfied: bool + termination_reason: str + + def to_dict(self) -> dict[str, Any]: + return asdict(self) + + +class EquilibriumConvergenceError(RuntimeError): + """Raised instead of returning an unverified or non-unique equilibrium.""" + + def __init__(self, message: str, diagnostics: EquilibriumDiagnostics) -> None: + super().__init__(message) + self.diagnostics = diagnostics + + +class EquilibriumBudgetError(RuntimeError): + """Raised when a monotone, budget-feasible treatment scale cannot be certified.""" + + +@dataclass(frozen=True) +class EquilibriumOutcome: + """One solved market path and its convergence evidence.""" + + panel: pd.DataFrame + diagnostics: EquilibriumDiagnostics + metadata: Mapping[str, Any] + + +@dataclass(frozen=True) +class EquilibriumBenchmarkResult: + """Paired equilibrium counterfactuals, exact model truth, and accounting ledger.""" + + control: EquilibriumOutcome + treatment: EquilibriumOutcome + zone_effects: pd.DataFrame + ledger: pd.DataFrame + ground_truth: Mapping[str, float | None] + metadata: Mapping[str, Any] + + @property + def truth(self) -> Mapping[str, float | None]: + """Compact alias for callers that treat this as a simulation benchmark.""" + + return self.ground_truth + + +@dataclass(frozen=True, slots=True) +class EquilibriumArtifacts: + """Portable files published by :func:`write_equilibrium_artifacts`.""" + + summary_path: Path + zone_effects_path: Path + ledger_path: Path + manifest_path: Path + + def paths(self) -> tuple[Path, ...]: + """Return every published path, with the manifest last.""" + + return ( + self.summary_path, + self.zone_effects_path, + self.ledger_path, + self.manifest_path, + ) + + +def _coerce_config( + config: EquilibriumConfig | Mapping[str, object] | None, +) -> EquilibriumConfig: + if config is None: + return EquilibriumConfig() + if isinstance(config, EquilibriumConfig): + return config + if isinstance(config, Mapping): + return EquilibriumConfig.from_mapping(config) + raise TypeError("config must be EquilibriumConfig, a mapping, or None") + + +def _state_id(seed: int, demand: np.ndarray, supply: np.ndarray) -> str: + digest = hashlib.sha256() + digest.update(str(seed).encode("ascii")) + digest.update(np.asarray(demand, dtype=" EquilibriumState: + """Draw the one seeded exogenous state used for paired counterfactuals.""" + + cfg = _coerce_config(config) + rng = np.random.default_rng(cfg.seed) + demand_multiplier = np.exp( + rng.normal(-0.5 * cfg.demand_shock_sd**2, cfg.demand_shock_sd, cfg.n_zones) + ) + supply_multiplier = np.exp( + rng.normal(-0.5 * cfg.supply_shock_sd**2, cfg.supply_shock_sd, cfg.n_zones) + ) + demand = cfg.base_demand * demand_multiplier + supply = cfg.base_drivers * supply_multiplier + return EquilibriumState( + baseline_rider_arrivals=tuple(float(value) for value in demand), + baseline_driver_pool=tuple(float(value) for value in supply), + seed=cfg.seed, + state_id=_state_id(cfg.seed, demand, supply), + ) + + +def _ring_adjacency(n_zones: int) -> np.ndarray: + weights = np.zeros((n_zones, n_zones), dtype=float) + if n_zones == 1: + return weights + if n_zones == 2: + weights[0, 1] = 1.0 + weights[1, 0] = 1.0 + return weights + for zone in range(n_zones): + weights[zone, (zone - 1) % n_zones] = 0.5 + weights[zone, (zone + 1) % n_zones] = 0.5 + return weights + + +def _coerce_intensity( + treatment_intensity: float | Sequence[float] | np.ndarray, + n_zones: int, +) -> np.ndarray: + if isinstance(treatment_intensity, Real) and not isinstance(treatment_intensity, bool): + intensity = np.full(n_zones, float(treatment_intensity), dtype=float) + else: + intensity = np.asarray(treatment_intensity, dtype=float) + if intensity.ndim != 1 or len(intensity) != n_zones: + raise ValueError("treatment_intensity must be scalar or have one value per zone") + if not np.isfinite(intensity).all() or ((intensity < 0) | (intensity > 1)).any(): + raise ValueError("treatment_intensity must be finite and lie in [0, 1]") + return intensity + + +def _active_doses( + intensity: np.ndarray, + config: EquilibriumConfig, +) -> tuple[np.ndarray, np.ndarray]: + rider_active = config.treatment_version in { + TreatmentVersion.RIDER_DISCOUNT, + TreatmentVersion.BUNDLED, + } + driver_active = config.treatment_version in { + TreatmentVersion.DRIVER_INCENTIVE, + TreatmentVersion.BUNDLED, + } + rider = intensity if rider_active else np.zeros_like(intensity) + driver = intensity if driver_active else np.zeros_like(intensity) + return rider, driver + + +def _market_map( + log_wait_ratio: np.ndarray, + state: EquilibriumState, + intensity: np.ndarray, + config: EquilibriumConfig, +) -> tuple[np.ndarray, dict[str, np.ndarray]]: + rider_dose, driver_dose = _active_doses(intensity, config) + discount = config.discount_rate * rider_dose + incentive = config.incentive_per_driver * driver_dose + baseline_demand = np.asarray(state.baseline_rider_arrivals, dtype=float) + baseline_supply = np.asarray(state.baseline_driver_pool, dtype=float) + log_demand = ( + np.log(baseline_demand) + + config.demand_price_semielasticity * discount + - config.demand_wait_elasticity * log_wait_ratio + ) + log_supply = ( + np.log(baseline_supply) + + config.supply_incentive_semielasticity + * incentive + / config.reference_incentive_per_driver + + config.supply_wait_elasticity * log_wait_ratio + ) + log_tightness = log_demand - np.log(config.capacity_per_driver) - log_supply + cross_share = ( + config.cross_zone_share + if config.cross_zone_enabled and config.n_zones > 1 + else 0.0 + ) + neighbor_tightness = _ring_adjacency(config.n_zones) @ log_tightness + mapped_tightness = ( + (1.0 - cross_share) * log_tightness + cross_share * neighbor_tightness + ) + target = config.congestion_elasticity * mapped_tightness + components = { + "rider_dose": rider_dose, + "driver_dose": driver_dose, + "discount": discount, + "incentive": incentive, + "log_demand": log_demand, + "log_supply": log_supply, + "log_tightness": log_tightness, + "neighbor_log_tightness": neighbor_tightness, + "mapped_log_tightness": mapped_tightness, + } + return target, components + + +def _equations_metadata() -> dict[str, str]: + return { + "equilibrium_variable": "x_z = log(wait_z / base_wait_minutes)", + "rider_demand": ( + "D_z = A_z * exp(demand_price_semielasticity * discount_z " + "- demand_wait_elasticity * x_z)" + ), + "driver_supply": ( + "S_z = B_z * exp(supply_incentive_semielasticity * " + "incentive_z/reference_incentive + supply_wait_elasticity * x_z)" + ), + "wait_fixed_point": ( + "x_z = congestion_elasticity * ((1-cross_zone_share)*log(D_z/(capacity*S_z)) " + "+ cross_zone_share*sum_j W_zj*log(D_j/(capacity*S_j)))" + ), + "service_probability": "p_z = 1 - exp(-capacity_per_driver*S_z/D_z)", + "served_trips": "Q_z = D_z * p_z", + "uniqueness_and_convergence": ( + "Banach sufficient condition: congestion_elasticity * " + "(demand_wait_elasticity + supply_wait_elasticity) < 1" + ), + "welfare": ( + "rider_surplus + driver_surplus + platform_net_revenue; monetary transfers " + "cancel, while waiting, driver opportunity, and trip operating costs remain" + ), + } + + +def _failed_diagnostics( + config: EquilibriumConfig, + *, + reason: str, + iterations: int, + initial_residual: float | None, + residual: float | None, + step: float | None, +) -> EquilibriumDiagnostics: + return EquilibriumDiagnostics( + converged=False, + iterations=iterations, + initial_residual_sup_norm=initial_residual, + residual_sup_norm=residual, + step_sup_norm=step, + tolerance=config.tolerance, + contraction_bound=config.contraction_bound, + effective_iteration_bound=config.effective_iteration_bound, + uniqueness_condition_satisfied=config.contraction_bound < 1.0, + termination_reason=reason, + ) + + +def solve_market_equilibrium( + config: EquilibriumConfig | Mapping[str, object] | None = None, + treatment_intensity: float | Sequence[float] | np.ndarray = 0.0, + *, + state: EquilibriumState | None = None, +) -> EquilibriumOutcome: + """Solve one intervention path, refusing uncertified or imprecise results.""" + + cfg = _coerce_config(config) + market_state = draw_equilibrium_state(cfg) if state is None else state + if len(market_state.baseline_rider_arrivals) != cfg.n_zones: + raise ValueError("state length must equal config.n_zones") + intensity = _coerce_intensity(treatment_intensity, cfg.n_zones) + if not cfg.contraction_bound < 1.0: + diagnostics = _failed_diagnostics( + cfg, + reason="sufficient_contraction_condition_failed", + iterations=0, + initial_residual=None, + residual=None, + step=None, + ) + raise EquilibriumConvergenceError( + "equilibrium not solved: the declared sufficient uniqueness and convergence " + "condition is not satisfied", + diagnostics, + ) + + log_wait = np.zeros(cfg.n_zones, dtype=float) + target, _ = _market_map(log_wait, market_state, intensity, cfg) + initial_residual = float(np.max(np.abs(target - log_wait))) + residual = initial_residual + step = 0.0 + iterations = 0 + converged = residual <= cfg.tolerance + while not converged and iterations < cfg.max_iterations: + candidate = (1.0 - cfg.relaxation) * log_wait + cfg.relaxation * target + if not np.isfinite(candidate).all(): + diagnostics = _failed_diagnostics( + cfg, + reason="nonfinite_fixed_point_iterate", + iterations=iterations + 1, + initial_residual=initial_residual, + residual=None, + step=None, + ) + raise EquilibriumConvergenceError( + "equilibrium iteration produced a non-finite state", diagnostics + ) + step = float(np.max(np.abs(candidate - log_wait))) + log_wait = candidate + iterations += 1 + target, _ = _market_map(log_wait, market_state, intensity, cfg) + residual = float(np.max(np.abs(target - log_wait))) + converged = residual <= cfg.tolerance + + if not converged: + diagnostics = _failed_diagnostics( + cfg, + reason="maximum_iterations_reached_before_residual_tolerance", + iterations=iterations, + initial_residual=initial_residual, + residual=residual, + step=step, + ) + raise EquilibriumConvergenceError( + "equilibrium not returned because the residual tolerance was not reached", + diagnostics, + ) + + target, components = _market_map(log_wait, market_state, intensity, cfg) + residual = float(np.max(np.abs(target - log_wait))) + diagnostics = EquilibriumDiagnostics( + converged=True, + iterations=iterations, + initial_residual_sup_norm=initial_residual, + residual_sup_norm=residual, + step_sup_norm=step, + tolerance=cfg.tolerance, + contraction_bound=cfg.contraction_bound, + effective_iteration_bound=cfg.effective_iteration_bound, + uniqueness_condition_satisfied=True, + termination_reason="residual_tolerance_satisfied", + ) + + log_demand = components["log_demand"] + log_supply = components["log_supply"] + if ( + np.max(np.abs(log_demand)) > 300 + or np.max(np.abs(log_supply)) > 300 + or np.max(np.abs(log_wait)) > 300 + ): + failed = _failed_diagnostics( + cfg, + reason="equilibrium_quantities_outside_numerically_safe_range", + iterations=iterations, + initial_residual=initial_residual, + residual=residual, + step=step, + ) + raise EquilibriumConvergenceError( + "equilibrium quantities exceed the declared numerical safety range", failed + ) + + latent_demand = np.exp(log_demand) + available_drivers = np.exp(log_supply) + wait_minutes = cfg.base_wait_minutes * np.exp(log_wait) + log_capacity_ratio = ( + np.log(cfg.capacity_per_driver) + log_supply - log_demand + ) + capacity_ratio = np.exp(np.clip(log_capacity_ratio, -745.0, 50.0)) + service_probability = -np.expm1(-capacity_ratio) + trips = latent_demand * service_probability + rider_price = cfg.base_fare * (1.0 - components["discount"]) + rider_discount_spend = trips * (cfg.base_fare - rider_price) + driver_incentive_spend = available_drivers * components["incentive"] + treatment_spend = rider_discount_spend + driver_incentive_spend + + driver_base_payout = trips * (1.0 - cfg.platform_take_rate) * cfg.base_fare + trip_operating_cost = trips * cfg.driver_operating_cost_per_trip + driver_opportunity_cost = ( + available_drivers * cfg.driver_opportunity_cost_per_active_driver + ) + wait_disutility = ( + latent_demand * wait_minutes * cfg.wait_disutility_per_minute + ) + rider_surplus = trips * (cfg.rider_value_per_trip - rider_price) - wait_disutility + driver_surplus = ( + driver_base_payout + + driver_incentive_spend + - trip_operating_cost + - driver_opportunity_cost + ) + platform_net_revenue = ( + trips * rider_price - driver_base_payout - driver_incentive_spend + ) + total_welfare = ( + trips * cfg.rider_value_per_trip + - trip_operating_cost + - wait_disutility + - driver_opportunity_cost + ) + welfare_accounting_residual = ( + rider_surplus + driver_surplus + platform_net_revenue - total_welfare + ) + + panel = pd.DataFrame( + { + "zone_id": np.arange(cfg.n_zones, dtype=int), + "treatment_version": cfg.treatment_version.value, + "treatment_intensity": intensity, + "rider_treatment_dose": components["rider_dose"], + "driver_treatment_dose": components["driver_dose"], + "baseline_rider_arrivals": market_state.baseline_rider_arrivals, + "baseline_driver_pool": market_state.baseline_driver_pool, + "rider_price": rider_price, + "driver_incentive_per_driver": components["incentive"], + "log_wait_ratio": log_wait, + "wait_minutes": wait_minutes, + "latent_demand": latent_demand, + "available_drivers": available_drivers, + "log_tightness": components["log_tightness"], + "mapped_log_tightness": components["mapped_log_tightness"], + "service_probability": service_probability, + "trips": trips, + "rider_discount_spend": rider_discount_spend, + "driver_incentive_spend": driver_incentive_spend, + "treatment_spend": treatment_spend, + "rider_surplus": rider_surplus, + "driver_surplus": driver_surplus, + "platform_net_revenue": platform_net_revenue, + "total_welfare": total_welfare, + "welfare_accounting_residual": welfare_accounting_residual, + "evidence_type": EVIDENCE_TYPE, + "causal_scope": CAUSAL_SCOPE, + "empirical_calibration_status": EMPIRICAL_STATUS, + "is_nyc_structural_estimate": False, + "simulation_seed": cfg.seed, + "state_id": market_state.state_id, + } + ) + numeric = panel.select_dtypes(include=[np.number]).to_numpy(dtype=float) + if not np.isfinite(numeric).all(): + failed = _failed_diagnostics( + cfg, + reason="nonfinite_equilibrium_output", + iterations=iterations, + initial_residual=initial_residual, + residual=residual, + step=step, + ) + raise EquilibriumConvergenceError( + "equilibrium output contains non-finite quantities", failed + ) + + metadata: dict[str, Any] = { + "schema_version": 1, + "evidence_type": EVIDENCE_TYPE, + "causal_scope": CAUSAL_SCOPE, + "empirical_calibration_status": EMPIRICAL_STATUS, + "is_nyc_structural_estimate": False, + "simulation_seed": cfg.seed, + "state_id": market_state.state_id, + "treatment_version": cfg.treatment_version.value, + "cross_zone_channel": bool(cfg.cross_zone_enabled and cfg.n_zones > 1), + "cross_zone_share": ( + cfg.cross_zone_share + if cfg.cross_zone_enabled and cfg.n_zones > 1 + else 0.0 + ), + "equations": _equations_metadata(), + "diagnostics": diagnostics.to_dict(), + "configuration": asdict(cfg), + } + metadata["configuration"]["treatment_version"] = cfg.treatment_version.value + return EquilibriumOutcome(panel=panel, diagnostics=diagnostics, metadata=metadata) + + +_LEDGER_COLUMNS = ( + "trips", + "latent_demand", + "available_drivers", + "rider_discount_spend", + "driver_incentive_spend", + "treatment_spend", + "rider_surplus", + "driver_surplus", + "platform_net_revenue", + "total_welfare", + "welfare_accounting_residual", +) + + +def _ledger_row(scenario: str, outcome: EquilibriumOutcome) -> dict[str, Any]: + panel = outcome.panel + row: dict[str, Any] = { + "scenario": scenario, + "treatment_version": str(panel["treatment_version"].iloc[0]), + "mean_wait_minutes": float(panel["wait_minutes"].mean()), + "mean_service_probability": float(panel["service_probability"].mean()), + "equilibrium_converged": outcome.diagnostics.converged, + "equilibrium_iterations": outcome.diagnostics.iterations, + "equilibrium_residual_sup_norm": outcome.diagnostics.residual_sup_norm, + } + row.update({column: float(panel[column].sum()) for column in _LEDGER_COLUMNS}) + return row + + +def _budget_feasible_treatment( + config: EquilibriumConfig, + state: EquilibriumState, + planned: np.ndarray, + control: EquilibriumOutcome, +) -> tuple[EquilibriumOutcome, float, dict[str, Any]]: + unconstrained = solve_market_equilibrium(config, planned, state=state) + unconstrained_spend = float(unconstrained.panel["treatment_spend"].sum()) + budget = config.budget + if budget is None or unconstrained_spend <= budget + config.budget_tolerance: + return unconstrained, 1.0, { + "budget": budget, + "binding": False, + "planned_treatment_spend": unconstrained_spend, + "realized_treatment_spend": unconstrained_spend, + "budget_scale": 1.0, + "budget_search_iterations": 0, + "budget_residual": None if budget is None else budget - unconstrained_spend, + "budget_feasible": True, + } + if budget <= config.budget_tolerance: + return control, 0.0, { + "budget": budget, + "binding": True, + "planned_treatment_spend": unconstrained_spend, + "realized_treatment_spend": 0.0, + "budget_scale": 0.0, + "budget_search_iterations": 0, + "budget_residual": budget, + "budget_feasible": True, + } + + low = 0.0 + high = 1.0 + low_spend = 0.0 + high_spend = unconstrained_spend + feasible = control + iterations = 0 + for iteration in range(1, config.budget_max_iterations + 1): + iterations = iteration + midpoint = 0.5 * (low + high) + candidate = solve_market_equilibrium(config, planned * midpoint, state=state) + spend = float(candidate.panel["treatment_spend"].sum()) + if ( + spend < low_spend - config.budget_tolerance + or spend > high_spend + config.budget_tolerance + ): + raise EquilibriumBudgetError( + "treatment spend was not monotone in the common intensity scale; " + "a budget-feasible policy was not asserted" + ) + if spend <= budget: + low = midpoint + low_spend = spend + feasible = candidate + else: + high = midpoint + high_spend = spend + if abs(spend - budget) <= config.budget_tolerance or high - low <= 1e-12: + break + + realized_spend = float(feasible.panel["treatment_spend"].sum()) + if realized_spend > budget + config.budget_tolerance: + raise EquilibriumBudgetError( + "budget search ended without a certified feasible treatment path" + ) + return feasible, low, { + "budget": budget, + "binding": True, + "planned_treatment_spend": unconstrained_spend, + "realized_treatment_spend": realized_spend, + "budget_scale": low, + "budget_search_iterations": iterations, + "budget_residual": budget - realized_spend, + "budget_feasible": True, + } + + +def run_equilibrium_benchmark( + config: EquilibriumConfig | Mapping[str, object] | None = None, + planned_treatment_intensity: float | Sequence[float] | np.ndarray = 1.0, + *, + state: EquilibriumState | None = None, +) -> EquilibriumBenchmarkResult: + """Solve paired control/policy equilibria and expose exact within-model truth. + + The same exogenous state is passed to both paths. When a budget is supplied, + the planned policy is uniformly scaled via a deterministic bisection and the + realized equilibrium is re-solved at every candidate scale. + """ + + cfg = _coerce_config(config) + market_state = draw_equilibrium_state(cfg) if state is None else state + planned = _coerce_intensity(planned_treatment_intensity, cfg.n_zones) + control = solve_market_equilibrium(cfg, 0.0, state=market_state) + treatment, budget_scale, budget_diagnostics = _budget_feasible_treatment( + cfg, market_state, planned, control + ) + if control.metadata["state_id"] != treatment.metadata["state_id"]: + raise AssertionError("counterfactual paths did not use common random numbers") + + control_panel = control.panel.sort_values("zone_id").reset_index(drop=True) + treatment_panel = treatment.panel.sort_values("zone_id").reset_index(drop=True) + zone_effects = pd.DataFrame( + { + "zone_id": control_panel["zone_id"], + "control_trips": control_panel["trips"], + "treatment_trips": treatment_panel["trips"], + "trip_effect": treatment_panel["trips"] - control_panel["trips"], + "control_wait_minutes": control_panel["wait_minutes"], + "treatment_wait_minutes": treatment_panel["wait_minutes"], + "wait_effect_minutes": ( + treatment_panel["wait_minutes"] - control_panel["wait_minutes"] + ), + "control_service_probability": control_panel["service_probability"], + "treatment_service_probability": treatment_panel["service_probability"], + "service_probability_effect": ( + treatment_panel["service_probability"] + - control_panel["service_probability"] + ), + "control_welfare": control_panel["total_welfare"], + "treatment_welfare": treatment_panel["total_welfare"], + "welfare_effect": ( + treatment_panel["total_welfare"] - control_panel["total_welfare"] + ), + "realized_treatment_intensity": treatment_panel["treatment_intensity"], + "state_id": market_state.state_id, + "evidence_type": EVIDENCE_TYPE, + } + ) + + ledger = pd.DataFrame( + [_ledger_row("control", control), _ledger_row("treatment", treatment)] + ) + ledger["budget"] = cfg.budget + ledger["budget_binding"] = bool(budget_diagnostics["binding"]) + ledger["budget_scale"] = [0.0, budget_scale] + treatment_spend = float(treatment_panel["treatment_spend"].sum()) + trip_effect = float(zone_effects["trip_effect"].sum()) + welfare_effect = float(zone_effects["welfare_effect"].sum()) + ground_truth: dict[str, float | None] = { + "market_total_effect": trip_effect, + "market_total_trip_effect": trip_effect, + "mean_zone_trip_effect": float(zone_effects["trip_effect"].mean()), + "market_total_welfare_effect": welfare_effect, + "mean_zone_wait_effect_minutes": float(zone_effects["wait_effect_minutes"].mean()), + "mean_zone_service_probability_effect": float( + zone_effects["service_probability_effect"].mean() + ), + "treatment_spend": treatment_spend, + "incremental_trips_per_dollar": ( + trip_effect / treatment_spend if treatment_spend > 1e-12 else None + ), + "incremental_welfare_per_dollar": ( + welfare_effect / treatment_spend if treatment_spend > 1e-12 else None + ), + } + + metadata: dict[str, Any] = { + "schema_version": 1, + "evidence_type": EVIDENCE_TYPE, + "causal_scope": CAUSAL_SCOPE, + "ground_truth_status": "known_exactly_for_the_paired_model_counterfactuals", + "empirical_calibration_status": EMPIRICAL_STATUS, + "is_nyc_structural_estimate": False, + "common_random_numbers": True, + "simulation_seed": cfg.seed, + "state_id": market_state.state_id, + "control_state_id": control.metadata["state_id"], + "treatment_state_id": treatment.metadata["state_id"], + "treatment_version": cfg.treatment_version.value, + "planned_treatment_intensity": planned.tolist(), + "realized_budget_scale": budget_scale, + "cross_zone_channel": bool(cfg.cross_zone_enabled and cfg.n_zones > 1), + "equations": _equations_metadata(), + "uniqueness_diagnostics": { + "sufficient_condition_satisfied": cfg.contraction_bound < 1.0, + "contraction_bound": cfg.contraction_bound, + "effective_iteration_bound": cfg.effective_iteration_bound, + "condition": ( + "congestion_elasticity * (demand_wait_elasticity + " + "supply_wait_elasticity) < 1" + ), + }, + "control_diagnostics": control.diagnostics.to_dict(), + "treatment_diagnostics": treatment.diagnostics.to_dict(), + "budget_diagnostics": budget_diagnostics, + "ground_truth_definition": ( + "feasible policy equilibrium minus all-zero equilibrium for the identical " + "seeded exogenous market state" + ), + "limitations": [ + "This is a theoretical simulation benchmark, not an empirical causal estimate.", + "Parameters are declared assumptions and are not estimated from NYC data.", + "The model is a static fixed point and omits forward-looking entry and relocation.", + "The contraction condition is sufficient; paths failing it are withheld.", + "Welfare inherits the declared value, waiting-cost, and driver-cost assumptions.", + ], + } + return EquilibriumBenchmarkResult( + control=control, + treatment=treatment, + zone_effects=zone_effects, + ledger=ledger, + ground_truth=ground_truth, + metadata=metadata, + ) + + +def _strict_json_value(value: Any) -> Any: + """Convert numpy scalars while refusing non-finite values and filesystem paths.""" + + if isinstance(value, Path): + raise ValueError("artifact JSON must not embed filesystem Path objects") + if isinstance(value, Mapping): + return {str(key): _strict_json_value(item) for key, item in value.items()} + if isinstance(value, (list, tuple, set, frozenset)): + return [_strict_json_value(item) for item in value] + if isinstance(value, np.generic): + value = value.item() + if isinstance(value, float) and not isfinite(value): + raise ValueError("artifact JSON must not contain non-finite numbers") + return value + + +def _assert_no_absolute_path_strings(value: Any) -> None: + if isinstance(value, Mapping): + for item in value.values(): + _assert_no_absolute_path_strings(item) + elif isinstance(value, (list, tuple, set, frozenset)): + for item in value: + _assert_no_absolute_path_strings(item) + elif isinstance(value, str) and Path(value).is_absolute(): + raise ValueError(f"artifact payload contains an absolute path: {value}") + + +def _atomic_text(text: str, destination: Path) -> Path: + destination.parent.mkdir(parents=True, exist_ok=True) + temporary: Path | None = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="", + prefix=f".{destination.stem}-", + suffix=destination.suffix, + dir=destination.parent, + delete=False, + ) as handle: + temporary = Path(handle.name) + handle.write(text) + temporary.replace(destination) + finally: + if temporary is not None: + temporary.unlink(missing_ok=True) + return destination + + +def _atomic_artifact_json(payload: Mapping[str, Any], destination: Path) -> Path: + safe = _strict_json_value(payload) + _assert_no_absolute_path_strings(safe) + rendered = json.dumps(safe, indent=2, sort_keys=True, allow_nan=False) + "\n" + return _atomic_text(rendered, destination) + + +def _atomic_artifact_csv(frame: pd.DataFrame, destination: Path) -> Path: + if frame.select_dtypes(include=[np.number]).isna().any().any(): + raise ValueError(f"numeric artifact columns contain missing values: {destination.name}") + numeric = frame.select_dtypes(include=[np.number]).to_numpy(dtype=float) + if numeric.size and not np.isfinite(numeric).all(): + raise ValueError(f"numeric artifact columns are non-finite: {destination.name}") + return _atomic_text(frame.to_csv(index=False, lineterminator="\n"), destination) + + +def _artifact_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + while block := stream.read(1024 * 1024): + digest.update(block) + return digest.hexdigest() + + +def _portable_artifact_path(path: Path, project_root: Path) -> str: + try: + return path.resolve().relative_to(project_root).as_posix() + except ValueError as exc: + raise ValueError(f"equilibrium artifact is outside project_root: {path}") from exc + + +def _validate_equilibrium_artifact_result(result: EquilibriumBenchmarkResult) -> None: + if not isinstance(result, EquilibriumBenchmarkResult): + raise TypeError("result must be an EquilibriumBenchmarkResult") + metadata = result.metadata + expected_labels = { + "evidence_type": EVIDENCE_TYPE, + "causal_scope": CAUSAL_SCOPE, + "empirical_calibration_status": EMPIRICAL_STATUS, + "is_nyc_structural_estimate": False, + "common_random_numbers": True, + } + for key, expected in expected_labels.items(): + if metadata.get(key) != expected: + raise ValueError(f"equilibrium result has invalid {key}") + state_id = metadata.get("state_id") + if ( + not isinstance(state_id, str) + or not state_id + or metadata.get("control_state_id") != state_id + or metadata.get("treatment_state_id") != state_id + ): + raise ValueError("equilibrium counterfactuals do not share one declared state") + + expected_zones: np.ndarray | None = None + for scenario, outcome in (("control", result.control), ("treatment", result.treatment)): + diagnostics = outcome.diagnostics + if ( + not diagnostics.converged + or not diagnostics.uniqueness_condition_satisfied + or diagnostics.residual_sup_norm is None + or diagnostics.residual_sup_norm > diagnostics.tolerance + ): + raise ValueError(f"{scenario} equilibrium is not convergence-certified") + if outcome.metadata.get("state_id") != state_id: + raise ValueError(f"{scenario} equilibrium state does not match benchmark state") + panel = outcome.panel.sort_values("zone_id") + zones = panel["zone_id"].to_numpy(dtype=int) + if len(zones) == 0 or len(np.unique(zones)) != len(zones): + raise ValueError(f"{scenario} equilibrium zones must be unique and nonempty") + if expected_zones is None: + expected_zones = zones + elif not np.array_equal(zones, expected_zones): + raise ValueError("control and treatment zone sets do not match") + if set(panel["evidence_type"].astype(str)) != {EVIDENCE_TYPE}: + raise ValueError(f"{scenario} panel has an invalid evidence label") + if panel["state_id"].astype(str).nunique() != 1 or str( + panel["state_id"].iloc[0] + ) != state_id: + raise ValueError(f"{scenario} panel does not preserve the shared state id") + + zone_effects = result.zone_effects.sort_values("zone_id") + if expected_zones is None or not np.array_equal( + zone_effects["zone_id"].to_numpy(dtype=int), expected_zones + ): + raise ValueError("zone effect rows do not match the solved counterfactual zones") + if set(zone_effects["evidence_type"].astype(str)) != {EVIDENCE_TYPE}: + raise ValueError("zone effects have an invalid evidence label") + if set(zone_effects["state_id"].astype(str)) != {state_id}: + raise ValueError("zone effects do not preserve the shared state id") + + scenarios = result.ledger["scenario"].astype(str) + if len(scenarios) != 2 or set(scenarios) != {"control", "treatment"}: + raise ValueError("equilibrium ledger must contain one control and one treatment row") + if float(result.ledger["welfare_accounting_residual"].abs().max()) > 1e-8: + raise ValueError("equilibrium welfare ledger does not balance") + budget_diagnostics = metadata.get("budget_diagnostics") + if not isinstance(budget_diagnostics, Mapping) or not budget_diagnostics.get( + "budget_feasible" + ): + raise ValueError("equilibrium budget feasibility is not certified") + + trip_effect = float(zone_effects["trip_effect"].sum()) + welfare_effect = float(zone_effects["welfare_effect"].sum()) + treatment_spend = float(result.treatment.panel["treatment_spend"].sum()) + truth_checks = { + "market_total_trip_effect": trip_effect, + "market_total_welfare_effect": welfare_effect, + "treatment_spend": treatment_spend, + } + for key, recomputed in truth_checks.items(): + declared = result.ground_truth.get(key) + if declared is None or not np.isclose(float(declared), recomputed, atol=1e-10): + raise ValueError(f"equilibrium ground truth failed recomputation: {key}") + + +def write_equilibrium_artifacts( + result: EquilibriumBenchmarkResult, + output_dir: str | Path, + project_root: str | Path, +) -> EquilibriumArtifacts: + """Atomically publish a portable, hash-manifested equilibrium evidence bundle. + + The conventional destination is ``artifacts/benchmarks/equilibrium`` beneath + ``project_root``. The function enforces containment rather than embedding an + absolute machine-specific path. A manifest is published last and an incomplete + marker remains if any content write or validation fails. + """ + + _validate_equilibrium_artifact_result(result) + root = Path(project_root).resolve() + if not root.is_dir(): + raise ValueError("project_root must be an existing directory") + output = Path(output_dir).resolve() + _portable_artifact_path(output, root) + output.mkdir(parents=True, exist_ok=True) + + summary_path = output / "summary.json" + zone_effects_path = output / "zone_effects.csv" + ledger_path = output / "ledger.csv" + manifest_path = output / "manifest.json" + marker_path = output / "EQUILIBRIUM_INCOMPLETE.json" + manifest_path.unlink(missing_ok=True) + _atomic_artifact_json( + {"schema_version": 1, "status": "incomplete", "manifest_published": False}, + marker_path, + ) + + summary: dict[str, Any] = { + "schema_version": 1, + "evidence_type": EVIDENCE_TYPE, + "causal_scope": CAUSAL_SCOPE, + "ground_truth_status": result.metadata["ground_truth_status"], + "empirical_calibration_status": EMPIRICAL_STATUS, + "is_nyc_structural_estimate": False, + "common_random_numbers": True, + "simulation_seed": result.metadata["simulation_seed"], + "state_id": result.metadata["state_id"], + "treatment_version": result.metadata["treatment_version"], + "planned_treatment_intensity": result.metadata["planned_treatment_intensity"], + "realized_budget_scale": result.metadata["realized_budget_scale"], + "cross_zone_channel": result.metadata["cross_zone_channel"], + "ground_truth": dict(result.ground_truth), + "equations": result.metadata["equations"], + "uniqueness_diagnostics": result.metadata["uniqueness_diagnostics"], + "control_diagnostics": result.control.diagnostics.to_dict(), + "treatment_diagnostics": result.treatment.diagnostics.to_dict(), + "budget_diagnostics": result.metadata["budget_diagnostics"], + "configuration": result.control.metadata["configuration"], + "limitations": result.metadata["limitations"], + } + _atomic_artifact_json(summary, summary_path) + _atomic_artifact_csv( + result.zone_effects.sort_values("zone_id").reset_index(drop=True), + zone_effects_path, + ) + _atomic_artifact_csv( + result.ledger.sort_values("scenario").reset_index(drop=True), ledger_path + ) + + content_paths = (summary_path, zone_effects_path, ledger_path) + entries = [ + { + "path": _portable_artifact_path(path, root), + "bytes": path.stat().st_size, + "sha256": _artifact_sha256(path), + } + for path in sorted(content_paths) + ] + declared_file_set_sha256 = hashlib.sha256( + json.dumps(entries, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + manifest: dict[str, Any] = { + "schema_version": 1, + "bundle_type": "two_sided_fixed_point_equilibrium_benchmark", + "evidence_type": EVIDENCE_TYPE, + "causal_scope": CAUSAL_SCOPE, + "empirical_calibration_status": EMPIRICAL_STATUS, + "is_nyc_structural_estimate": False, + "portable_paths": True, + "files": entries, + "declared_file_set_sha256": declared_file_set_sha256, + "metadata": { + "simulation_seed": result.metadata["simulation_seed"], + "state_id": result.metadata["state_id"], + "treatment_version": result.metadata["treatment_version"], + "common_random_numbers": True, + "ground_truth_status": result.metadata["ground_truth_status"], + }, + "checks": { + "control_equilibrium_converged": True, + "treatment_equilibrium_converged": True, + "residuals_within_tolerance": True, + "sufficient_uniqueness_condition_satisfied": True, + "common_random_numbers_verified": True, + "budget_feasible": True, + "welfare_accounting_balanced": True, + "ground_truth_recomputed": True, + "hashes_recomputed": True, + }, + } + _atomic_artifact_json(manifest, manifest_path) + marker_path.unlink(missing_ok=True) + return EquilibriumArtifacts( + summary_path=summary_path, + zone_effects_path=zone_effects_path, + ledger_path=ledger_path, + manifest_path=manifest_path, + ) + + +__all__ = [ + "CAUSAL_SCOPE", + "EMPIRICAL_STATUS", + "EVIDENCE_TYPE", + "EquilibriumBenchmarkResult", + "EquilibriumArtifacts", + "EquilibriumBudgetError", + "EquilibriumConfig", + "EquilibriumConvergenceError", + "EquilibriumDiagnostics", + "EquilibriumOutcome", + "EquilibriumState", + "draw_equilibrium_state", + "run_equilibrium_benchmark", + "solve_market_equilibrium", + "write_equilibrium_artifacts", +] diff --git a/CasualLab/src/casuallab/estimands.py b/CasualLab/src/casuallab/estimands.py new file mode 100644 index 0000000000000000000000000000000000000000..ca75b959e34675ffc04d86f5627102921f113199 --- /dev/null +++ b/CasualLab/src/casuallab/estimands.py @@ -0,0 +1,543 @@ +"""Pre-specified estimands and simulator ground-truth calculations. + +An estimand is a causal contrast; an estimator is only a procedure used to learn it. +Keeping this registry separate prevents a convenient regression coefficient from +quietly becoming the scientific target. +""" + +from __future__ import annotations + +from collections.abc import Iterator, Mapping +from dataclasses import dataclass +from enum import StrEnum +from typing import Any + +import numpy as np +import pandas as pd + +from .config import DesignName + + +class EstimandName(StrEnum): + DIRECT = "direct_effect" + CONTROLLED_ZONE_DIRECT = "controlled_zone_direct_effect" + MARKET_TOTAL = "market_total_effect" + SPILLOVER = "spillover_effect" + SHORT_RUN = "short_run_effect" + PERSISTENT = "persistent_effect" + CUMULATIVE = "cumulative_effect" + ITT = "intent_to_treat" + TOT = "treatment_on_treated" + TRIPS_PER_DOLLAR = "incremental_trips_per_dollar" + WELFARE_PER_DOLLAR = "incremental_welfare_per_dollar" + + @classmethod + def parse(cls, value: str | EstimandName) -> EstimandName: + if isinstance(value, cls): + return value + normalized = str(value).strip().lower().replace("-", "_").replace(" ", "_") + aliases = { + "direct": cls.DIRECT.value, + "controlled_zone_direct": cls.CONTROLLED_ZONE_DIRECT.value, + "ate": cls.MARKET_TOTAL.value, + "total": cls.MARKET_TOTAL.value, + "market_total": cls.MARKET_TOTAL.value, + "market_level_total": cls.MARKET_TOTAL.value, + "market_level_total_effect": cls.MARKET_TOTAL.value, + "spillover": cls.SPILLOVER.value, + "short_run": cls.SHORT_RUN.value, + "persistent": cls.PERSISTENT.value, + "cumulative": cls.CUMULATIVE.value, + "itt": cls.ITT.value, + "tot": cls.TOT.value, + "late": cls.TOT.value, + "trips_per_dollar": cls.TRIPS_PER_DOLLAR.value, + "welfare_per_dollar": cls.WELFARE_PER_DOLLAR.value, + } + try: + return cls(aliases.get(normalized, normalized)) + except ValueError as exc: + choices = ", ".join(item.value for item in cls) + raise ValueError(f"unknown estimand {value!r}; choose one of: {choices}") from exc + + +@dataclass(frozen=True, slots=True) +class EstimandDefinition: + """Human- and machine-readable causal target definition.""" + + name: EstimandName + label: str + unit: str + contrast: str + identified_when: tuple[str, ...] + not_identified_when: tuple[str, ...] + compatible_designs: tuple[str, ...] + + def to_dict(self) -> dict[str, Any]: + return { + "name": self.name.value, + "label": self.label, + "unit": self.unit, + "contrast": self.contrast, + "identified_when": list(self.identified_when), + "not_identified_when": list(self.not_identified_when), + "compatible_designs": list(self.compatible_designs), + } + + +ESTIMANDS: dict[EstimandName, EstimandDefinition] = { + EstimandName.DIRECT: EstimandDefinition( + EstimandName.DIRECT, + "Individual direct effect", + "eligible rider opportunity", + "Individual outcome with own treatment versus own control at a fixed mapped exposure", + ( + "own assignment is randomized", + "the relevant neighbor and lag exposure is measured or absent", + "consistency holds for the specified treatment intensity", + ), + ( + "unmapped interference changes outcomes", + "assignment affects who enters the observed sample", + ), + ("individual",), + ), + EstimandName.MARKET_TOTAL: EstimandDefinition( + EstimandName.MARKET_TOTAL, + "Market-level total effect", + "configured zone-time marketplace horizon", + ( + "Mean zone-period outcome under the feasible all-zone policy versus all-zero " + "over the fixed configured horizon, including modeled direct, " + "cross-zone, and congestion pathways" + ), + ( + "policy schedules or sufficiently isolated market clusters are randomized", + "cross-cluster interference is absent, bounded, or included in the target", + ), + ("only individuals within a connected market are randomized",), + ("geo_cluster", "time_block", "switchback", "geo_time"), + ), + EstimandName.CONTROLLED_ZONE_DIRECT: EstimandDefinition( + EstimandName.CONTROLLED_ZONE_DIRECT, + "Controlled own-zone saturation effect", + "zone-time marketplace cell", + ( + "Outcome with the focal zone treated at the configured saturation versus " + "focal-zone control while mapped neighbors are held at zero" + ), + ( + "zone assignment or saturation is randomized", + "mapped neighbor exposure and policy horizon are fixed", + ), + ("only aggregate outcomes are observed but the claim is interpreted as individual",), + ("geo_cluster", "geo_time"), + ), + EstimandName.SPILLOVER: EstimandDefinition( + EstimandName.SPILLOVER, + "Spillover effect", + "untreated or fixed-own-treatment market cell", + "Neighbor exposure versus no neighbor exposure at fixed own treatment", + ( + "assignment induces independent variation in mapped neighbor exposure", + "the exposure mapping is pre-specified", + ), + ("neighbor exposure is perfectly collinear with own treatment",), + ("individual", "geo_time"), + ), + EstimandName.SHORT_RUN: EstimandDefinition( + EstimandName.SHORT_RUN, + "Short-run effect", + "zone-time marketplace", + ( + "Mean all-zone policy versus all-zero over the fixed configured horizon with " + "the persistence state disabled" + ), + ("current assignment varies independently of prior exposure",), + ("all treated observations follow treated histories",), + ("time_block", "switchback", "geo_time"), + ), + EstimandName.PERSISTENT: EstimandDefinition( + EstimandName.PERSISTENT, + "Persistent effect", + "zone-time marketplace", + "Full-policy total effect minus the same policy effect with persistence disabled", + ( + "treatment histories vary", + "carryover horizon or state transition is specified", + ), + ("the experiment is shorter than the relevant carryover horizon",), + ("switchback", "geo_time", "time_block"), + ), + EstimandName.CUMULATIVE: EstimandDefinition( + EstimandName.CUMULATIVE, + "Cumulative market effect", + "experiment horizon", + "Sum of full-policy-versus-zero outcome differences over the full decision horizon", + ("the evaluation horizon is fixed before analysis",), + ("post-experiment displacement outside the horizon is ignored",), + ("geo_cluster", "time_block", "switchback", "geo_time"), + ), + EstimandName.ITT: EstimandDefinition( + EstimandName.ITT, + "Intent-to-treat effect", + "assigned market cell", + "Assignment to an encouragement schedule versus assignment to control", + ("assignment is randomized and analyzed as assigned",), + ("post-randomization exposure replaces assignment without adjustment",), + ("individual", "geo_cluster", "time_block", "switchback", "geo_time"), + ), + EstimandName.TOT: EstimandDefinition( + EstimandName.TOT, + "Treatment-on-the-treated effect", + "exposed complier-equivalent unit", + "ITT divided by the assignment-induced exposure first stage", + ( + "assignment is a valid instrument", + "exclusion, monotonicity, and a nonzero first stage hold", + ), + ("assignment affects outcomes through channels other than received treatment",), + ("individual", "geo_cluster", "time_block", "switchback", "geo_time"), + ), + EstimandName.TRIPS_PER_DOLLAR: EstimandDefinition( + EstimandName.TRIPS_PER_DOLLAR, + "Incremental trips per dollar", + "experiment or policy horizon", + "Full-horizon incremental served trips divided by feasible full-policy spend", + ("incremental trips and all treatment costs are measured on the same horizon",), + ("zero spend or omitted operational costs",), + ("individual", "geo_cluster", "time_block", "switchback", "geo_time"), + ), + EstimandName.WELFARE_PER_DOLLAR: EstimandDefinition( + EstimandName.WELFARE_PER_DOLLAR, + "Incremental welfare per dollar", + "experiment or policy horizon", + "Full-horizon modeled welfare gain divided by feasible full-policy spend", + ("the welfare function and transfer treatment are pre-specified",), + ("unmeasured externalities or distributional weights are decision relevant",), + ("individual", "geo_cluster", "time_block", "switchback", "geo_time"), + ), +} + + +def get_estimand(name: str | EstimandName) -> EstimandDefinition: + """Return a pre-specified estimand definition.""" + + return ESTIMANDS[EstimandName.parse(name)] + + +def list_estimands() -> list[dict[str, Any]]: + """Return serializable definitions for a dashboard or report.""" + + return [definition.to_dict() for definition in ESTIMANDS.values()] + + +def identification_assessment( + name: str | EstimandName, + *, + design: str, + interference_present: bool, + exposure_mapped: bool = False, + histories_observed: bool = True, + first_stage: float | None = None, +) -> tuple[bool, tuple[str, ...]]: + """Apply a conservative, explicit identification screen. + + This is a guardrail rather than a proof. A ``True`` result says the supplied + design metadata does not immediately contradict the estimand's core conditions. + """ + + target = EstimandName.parse(name) + normalized_design = DesignName.parse(design).value + reasons: list[str] = [] + definition = get_estimand(target) + if normalized_design not in set(definition.compatible_designs): + reasons.append( + f"{normalized_design} assignment is not compatible with {target.value}" + ) + if ( + target in {EstimandName.DIRECT, EstimandName.CONTROLLED_ZONE_DIRECT} + and interference_present + and not exposure_mapped + ): + reasons.append("direct effects require a mapped neighbor exposure under interference") + if ( + target is EstimandName.MARKET_TOTAL + and normalized_design in {"individual", "geo_cluster"} + and interference_present + and not exposure_mapped + ): + reasons.append( + f"{normalized_design} assignment within one connected market does not isolate " + "the all-zone total effect under unmapped cross-arm interference" + ) + if target is EstimandName.SPILLOVER and not exposure_mapped: + reasons.append("spillover effects require a pre-specified exposure mapping") + if target in {EstimandName.SHORT_RUN, EstimandName.PERSISTENT} and not histories_observed: + reasons.append("temporal effects require observed assignment histories") + if target is EstimandName.TOT and (first_stage is None or abs(first_stage) < 1e-8): + reasons.append("treatment-on-treated requires a nonzero exposure first stage") + return not reasons, tuple(reasons) + + +Estimand = EstimandDefinition + + +@dataclass(frozen=True) +class GroundTruth(Mapping[str, float]): + """Scalar targets plus row-level structural counterfactual contrasts.""" + + effects: Mapping[str, float] + unit_effects: pd.DataFrame + evidence_type: str = "semi_synthetic_known_ground_truth" + + def __getitem__(self, key: str | EstimandName) -> float: + normalized = key.value if isinstance(key, EstimandName) else str(key) + return float(self.effects[normalized]) + + def __iter__(self) -> Iterator[str]: + return iter(self.effects) + + def __len__(self) -> int: + return len(self.effects) + + def get(self, key: str | EstimandName, default: float | None = None) -> float | None: + normalized = key.value if isinstance(key, EstimandName) else str(key) + value = self.effects.get(normalized, default) + return None if value is None else float(value) + + def to_dict(self) -> dict[str, float]: + return {key: float(value) for key, value in self.effects.items()} + + def to_json_dict(self) -> dict[str, float | None]: + """Return strict-JSON-safe truth metadata (unavailable targets become null).""" + + return { + key: (float(value) if np.isfinite(value) else None) + for key, value in self.effects.items() + } + + @property + def market_total_effect(self) -> float: + return self[EstimandName.MARKET_TOTAL] + + +def _array(frame: pd.DataFrame, column: str) -> np.ndarray: + if column not in frame: + raise ValueError(f"counterfactual frame missing {column!r}") + values = frame[column].to_numpy(dtype=float) + if not np.isfinite(values).all(): + raise ValueError(f"counterfactual column {column!r} must be finite") + return values + + +def compute_ground_truth( + observed: pd.DataFrame, + control: pd.DataFrame, + *, + direct_only: pd.DataFrame | None = None, + short_run: pd.DataFrame | None = None, + all_treated: pd.DataFrame | None = None, + all_treated_short_run: pd.DataFrame | None = None, + controlled_direct_effects: np.ndarray | pd.Series | None = None, + controlled_spillover_effects: np.ndarray | pd.Series | None = None, + all_treated_received: np.ndarray | pd.Series | None = None, + analysis_eligible: np.ndarray | pd.Series | None = None, + assignment_itt_effects: np.ndarray | pd.Series | None = None, + assignment_first_stage: float | None = None, + individual_direct_effects: np.ndarray | pd.Series | None = None, + assigned_treatment: np.ndarray | pd.Series | None = None, + received_treatment: np.ndarray | pd.Series | None = None, + outcome: str = "trips", + cost: str = "treatment_cost", + welfare: str = "welfare", +) -> GroundTruth: + """Calculate named truths from structural paths sharing exogenous shocks.""" + + if len(observed) != len(control): + raise ValueError("observed and control paths must have the same length") + y = _array(observed, outcome) + y0 = _array(control, outcome) + realized_total = y - y0 + realized_mechanism_direct = ( + _array(direct_only, outcome) - y0 + if direct_only is not None + else realized_total.copy() + ) + realized_mechanism_spillover = realized_total - realized_mechanism_direct + realized_short = ( + _array(short_run, outcome) - y0 if short_run is not None else realized_total.copy() + ) + realized_persistent = realized_total - realized_short + + full_policy_effect = ( + _array(all_treated, outcome) - y0 if all_treated is not None else realized_total.copy() + ) + full_policy_short = ( + _array(all_treated_short_run, outcome) - y0 + if all_treated_short_run is not None + else full_policy_effect.copy() + ) + full_policy_persistent = full_policy_effect - full_policy_short + controlled_direct = ( + np.asarray(controlled_direct_effects, dtype=float) + if controlled_direct_effects is not None + else realized_mechanism_direct.copy() + ) + controlled_spillover = ( + np.asarray(controlled_spillover_effects, dtype=float) + if controlled_spillover_effects is not None + else realized_mechanism_spillover.copy() + ) + for name, values_array in { + "controlled_direct_effects": controlled_direct, + "controlled_spillover_effects": controlled_spillover, + }.items(): + if values_array.shape != y.shape or not np.isfinite(values_array).all(): + raise ValueError(f"{name} must be finite and align with counterfactual rows") + if individual_direct_effects is None: + individual_direct = np.full(len(observed), np.nan) + else: + individual_direct = np.asarray(individual_direct_effects, dtype=float) + if individual_direct.shape != y.shape or not np.isfinite(individual_direct).all(): + raise ValueError("individual_direct_effects must be finite and align with rows") + + if analysis_eligible is None: + analysis_mask = np.ones(len(observed), dtype=bool) + else: + analysis_mask = np.asarray(analysis_eligible, dtype=bool) + if analysis_mask.shape != y.shape: + raise ValueError("analysis_eligible must align with counterfactual rows") + if not analysis_mask.any(): + raise ValueError("analysis_eligible must retain at least one row") + + assignment = ( + np.asarray(assigned_treatment, dtype=float) + if assigned_treatment is not None + else np.ones(len(observed), dtype=float) + ) + received = ( + np.asarray(received_treatment, dtype=float) + if received_treatment is not None + else assignment.copy() + ) + if assignment.shape != y.shape or received.shape != y.shape: + raise ValueError("assignment and received treatment must align with counterfactual rows") + assigned_mask = (assignment > 0) & analysis_mask + realized_assigned_effect = ( + float(np.mean(realized_total[assigned_mask])) if assigned_mask.any() else 0.0 + ) + if all_treated_received is not None: + full_policy_received = np.asarray(all_treated_received, dtype=float) + if full_policy_received.shape != y.shape: + raise ValueError("all_treated_received must align with counterfactual rows") + full_policy_mean_exposure = float(np.mean(full_policy_received)) + else: + full_policy_mean_exposure = ( + 1.0 if all_treated is not None else float(np.mean(received)) + ) + if assignment_itt_effects is None: + # A within-market assignment coefficient is generally not the all-policy + # contrast under interference, carryover, or a shared budget. Leave ITT + # unavailable rather than relabeling a different structural contrast. + itt = float("nan") + first_stage = float("nan") + else: + itt_effects = np.asarray(assignment_itt_effects, dtype=float) + if itt_effects.shape != y.shape or not np.isfinite(itt_effects).all(): + raise ValueError("assignment_itt_effects must be finite and align with rows") + if assignment_first_stage is None or not np.isfinite(assignment_first_stage): + raise ValueError("assignment_first_stage is required with assignment_itt_effects") + itt = float(np.mean(itt_effects)) + first_stage = float(assignment_first_stage) + tot = itt / first_stage if first_stage > 1e-12 else float("nan") + + policy_frame = all_treated if all_treated is not None else observed + spend = float(_array(policy_frame, cost).sum()) if cost in policy_frame else 0.0 + incremental_trips = float(full_policy_effect.sum()) + if welfare in policy_frame and welfare in control: + incremental_welfare = float( + (_array(policy_frame, welfare) - _array(control, welfare)).sum() + ) + else: + incremental_welfare = float("nan") + + values: dict[str, float] = { + EstimandName.DIRECT.value: ( + float(np.mean(individual_direct[analysis_mask])) + if np.isfinite(individual_direct[analysis_mask]).all() + else float("nan") + ), + EstimandName.CONTROLLED_ZONE_DIRECT.value: float(np.mean(controlled_direct)), + # The canonical total effect is the market-wide policy contrast, which is + # the quantity a between-market experiment estimates in the no-interference + # case. The realized mixed schedule is reported separately below. + EstimandName.MARKET_TOTAL.value: float(np.mean(full_policy_effect)), + EstimandName.SPILLOVER.value: float(np.mean(controlled_spillover)), + EstimandName.SHORT_RUN.value: float(np.mean(full_policy_short)), + EstimandName.PERSISTENT.value: float(np.mean(full_policy_persistent)), + EstimandName.CUMULATIVE.value: incremental_trips, + EstimandName.ITT.value: itt, + EstimandName.TOT.value: float(tot), + EstimandName.TRIPS_PER_DOLLAR.value: ( + incremental_trips / spend if spend > 1e-12 else float("nan") + ), + EstimandName.WELFARE_PER_DOLLAR.value: ( + incremental_welfare / spend if spend > 1e-12 else float("nan") + ), + "first_stage": first_stage, + "assignment_first_stage": first_stage, + "itt_available": float(np.isfinite(itt)), + "full_policy_mean_exposure": full_policy_mean_exposure, + "full_policy_spend": spend, + "incremental_trips": incremental_trips, + "incremental_welfare": incremental_welfare, + "full_horizon_incremental_trips": incremental_trips, + "full_horizon_incremental_welfare": incremental_welfare, + "analysis_rows": float(analysis_mask.sum()), + "analysis_share": float(analysis_mask.mean()), + "analysis_population_market_total_effect": float( + np.mean(full_policy_effect[analysis_mask]) + ), + "analysis_population_controlled_zone_direct_effect": float( + np.mean(controlled_direct[analysis_mask]) + ), + "analysis_population_spillover_effect": float( + np.mean(controlled_spillover[analysis_mask]) + ), + "analysis_population_short_run_effect": float( + np.mean(full_policy_short[analysis_mask]) + ), + "analysis_population_persistent_effect": float( + np.mean(full_policy_persistent[analysis_mask]) + ), + "full_horizon_market_total_effect": float(np.mean(full_policy_effect)), + "analysis_horizon_cumulative_effect": float(full_policy_effect[analysis_mask].sum()), + "realized_schedule_mean_effect": float(np.mean(realized_total)), + "realized_schedule_cumulative_effect": float(realized_total.sum()), + "realized_schedule_assigned_mean_effect": realized_assigned_effect, + "realized_schedule_mechanism_direct_component": float( + np.mean(realized_mechanism_direct) + ), + "realized_schedule_mechanism_spillover_component": float( + np.mean(realized_mechanism_spillover) + ), + "realized_schedule_short_run_component": float(np.mean(realized_short)), + "realized_schedule_persistent_component": float(np.mean(realized_persistent)), + } + if all_treated is not None: + values["all_treated_market_total_effect"] = float(np.mean(full_policy_effect)) + values["average_treatment_effect"] = float(np.mean(full_policy_effect)) + + identifiers = [column for column in ("unit_id", "zone_id", "period_id") if column in observed] + unit_effects = observed[identifiers].copy() + unit_effects["y0"] = y0 + unit_effects["y_observed"] = y + unit_effects["realized_schedule_effect"] = realized_total + unit_effects["full_policy_total_effect"] = full_policy_effect + unit_effects["individual_direct_effect"] = individual_direct + unit_effects["controlled_direct_effect"] = controlled_direct + unit_effects["controlled_spillover_effect"] = controlled_spillover + unit_effects["full_policy_short_run_effect"] = full_policy_short + unit_effects["full_policy_persistent_effect"] = full_policy_persistent + return GroundTruth(effects=values, unit_effects=unit_effects) diff --git a/CasualLab/src/casuallab/estimators.py b/CasualLab/src/casuallab/estimators.py new file mode 100644 index 0000000000000000000000000000000000000000..dab67e1886f3f10b26908846f2e1da75ade9a49c --- /dev/null +++ b/CasualLab/src/casuallab/estimators.py @@ -0,0 +1,947 @@ +"""Transparent causal estimator ladder with a common result contract. + +These implementations favor inspectable design matrices and influence functions over +opaque causal-ML packages. Each result names its target estimand; callers remain +responsible for choosing a design that identifies that target. +""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from dataclasses import asdict, dataclass, field, fields, replace +from typing import Any + +import numpy as np +import pandas as pd +import statsmodels.api as sm +from scipy.optimize import minimize +from scipy.stats import norm +from scipy.stats import t as student_t +from sklearn.linear_model import LinearRegression, LogisticRegression +from sklearn.model_selection import StratifiedGroupKFold, StratifiedKFold +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler +from statsmodels.stats.sandwich_covariance import cov_cluster_2groups + +from .config import EstimatorConfig + + +@dataclass(frozen=True) +class EstimatorResult: + """Method-agnostic scalar estimate and uncertainty contract.""" + + method: str + target_estimand: str + estimate: float + standard_error: float + ci_low: float + ci_high: float + p_value: float + n_obs: int + outcome: str + treatment: str + alpha: float = 0.05 + diagnostics: Mapping[str, Any] = field(default_factory=dict) + + @property + def se(self) -> float: + return self.standard_error + + @property + def std_error(self) -> float: + return self.standard_error + + @property + def ci(self) -> tuple[float, float]: + return (self.ci_low, self.ci_high) + + def to_dict(self, *, flatten_diagnostics: bool = False) -> dict[str, Any]: + result = asdict(self) + result["se"] = result["standard_error"] + result["std_error"] = result["standard_error"] + if flatten_diagnostics: + diagnostics = result.pop("diagnostics") + result.update({f"diagnostic_{key}": value for key, value in diagnostics.items()}) + return result + + def __getitem__(self, key: str) -> Any: + if key == "se": + return self.standard_error + return getattr(self, key) + + +def _normal_result( + *, + method: str, + config: EstimatorConfig, + estimate: float, + standard_error: float, + n_obs: int, + p_value: float | None = None, + critical_value: float | None = None, + diagnostics: Mapping[str, Any] | None = None, + treatment: str | None = None, +) -> EstimatorResult: + critical = ( + float(norm.ppf(1.0 - config.alpha / 2.0)) + if critical_value is None + else float(critical_value) + ) + if p_value is None: + if standard_error > 0 and np.isfinite(standard_error): + p_value = float(2.0 * norm.sf(abs(estimate / standard_error))) + elif standard_error == 0: + p_value = float(0.0 if estimate != 0 else 1.0) + else: + p_value = float("nan") + return EstimatorResult( + method=method, + target_estimand=config.target_estimand, + estimate=float(estimate), + standard_error=float(standard_error), + ci_low=float(estimate - critical * standard_error), + ci_high=float(estimate + critical * standard_error), + p_value=float(p_value), + n_obs=int(n_obs), + outcome=config.outcome, + treatment=treatment or config.treatment, + alpha=config.alpha, + diagnostics=dict(diagnostics or {}), + ) + + +def _normalize_method(method: str) -> str: + normalized = method.strip().lower().replace("-", "_").replace(" ", "_") + aliases = { + "dim": "difference_in_means", + "difference": "difference_in_means", + "ols": "regression_adjustment", + "regression": "regression_adjustment", + "adjusted": "regression_adjustment", + "regression_adjusted": "regression_adjustment", + "clustered": "cluster_robust", + "cluster_robust_ols": "cluster_robust", + "cluster_adjusted": "cluster_robust", + "two_way_cluster": "two_way_cluster_robust", + "two_way_clustered": "two_way_cluster_robust", + "two_way_cluster_robust_ols": "two_way_cluster_robust", + "did": "difference_in_differences", + "diff_in_diff": "difference_in_differences", + "aipw": "doubly_robust", + "dr": "doubly_robust", + "synthetic": "synthetic_control", + "synthetic_control_style": "synthetic_control", + } + return aliases.get(normalized, normalized) + + +def _coerce_config( + method: str | EstimatorConfig | None, + config: EstimatorConfig | Mapping[str, Any] | None, + overrides: Mapping[str, Any], +) -> EstimatorConfig: + if isinstance(method, EstimatorConfig): + if config is not None: + raise ValueError("provide EstimatorConfig as method or config, not both") + cfg = method + elif isinstance(config, EstimatorConfig): + cfg = config + elif isinstance(config, Mapping): + cfg = EstimatorConfig.from_dict(config) + else: + cfg = EstimatorConfig() + updates = dict(overrides) + if method is not None and not isinstance(method, EstimatorConfig): + updates["method"] = method + if updates: + allowed = {item.name for item in fields(EstimatorConfig) if item.init} + unknown = set(updates).difference(allowed) + if unknown: + raise TypeError(f"unknown estimator options: {sorted(unknown)}") + cfg = replace(cfg, **updates) + return replace(cfg, method=_normalize_method(cfg.method)) + + +def _eligible(data: pd.DataFrame, config: EstimatorConfig) -> pd.DataFrame: + if not isinstance(data, pd.DataFrame): + raise TypeError("data must be a pandas DataFrame") + frame = data.copy() + if config.filter_eligible and "analysis_eligible" in frame: + frame = frame.loc[frame["analysis_eligible"].astype(bool)].copy() + if frame.empty: + raise ValueError("no eligible observations remain") + return frame + + +def _complete_cases(frame: pd.DataFrame, columns: Sequence[str]) -> pd.DataFrame: + missing = set(columns).difference(frame.columns) + if missing: + raise ValueError(f"estimator data missing columns: {sorted(missing)}") + result = frame.dropna(subset=list(dict.fromkeys(columns))).copy() + if result.empty: + raise ValueError("no complete observations remain") + return result + + +def _numeric_vector(frame: pd.DataFrame, column: str) -> np.ndarray: + try: + values = frame[column].to_numpy(dtype=float) + except (TypeError, ValueError) as exc: + raise ValueError(f"{column!r} must be numeric") from exc + if not np.isfinite(values).all(): + raise ValueError(f"{column!r} must be finite after complete-case filtering") + return values + + +def _covariate_matrix(frame: pd.DataFrame, covariates: Sequence[str]) -> pd.DataFrame: + if not covariates: + return pd.DataFrame(index=frame.index) + missing = set(covariates).difference(frame.columns) + if missing: + raise ValueError(f"estimator data missing covariates: {sorted(missing)}") + matrix = pd.get_dummies(frame[list(covariates)], drop_first=True, dtype=float) + if not np.isfinite(matrix.to_numpy(dtype=float)).all(): + raise ValueError("covariates must be finite") + return matrix + + +def difference_in_means( + data: pd.DataFrame, + config: EstimatorConfig | Mapping[str, Any] | None = None, +) -> EstimatorResult: + """Welch difference in means for a two-level randomized assignment.""" + + cfg = _coerce_config("difference_in_means", config, {}) + frame = _complete_cases(_eligible(data, cfg), [cfg.outcome, cfg.treatment]) + outcome = _numeric_vector(frame, cfg.outcome) + treatment = _numeric_vector(frame, cfg.treatment) + levels = np.unique(treatment) + if len(levels) != 2: + raise ValueError("difference_in_means requires exactly two treatment levels") + control_level, treated_level = float(levels[0]), float(levels[1]) + treated = outcome[treatment == treated_level] + control = outcome[treatment == control_level] + if len(treated) < 2 or len(control) < 2: + raise ValueError("each treatment arm needs at least two observations") + estimate = float(treated.mean() - control.mean()) + treated_component = float(treated.var(ddof=1) / len(treated)) + control_component = float(control.var(ddof=1) / len(control)) + variance = treated_component + control_component + standard_error = float(np.sqrt(variance)) + denominator = ( + treated_component**2 / (len(treated) - 1) + + control_component**2 / (len(control) - 1) + ) + degrees_freedom = variance**2 / denominator if denominator > 0 else len(frame) - 2 + if standard_error > 0: + statistic = estimate / standard_error + else: + statistic = 0.0 if estimate == 0 else np.inf + p_value = float(2.0 * student_t.sf(abs(statistic), degrees_freedom)) + critical = float(student_t.ppf(1.0 - cfg.alpha / 2.0, degrees_freedom)) + return _normal_result( + method="difference_in_means", + config=cfg, + estimate=estimate, + standard_error=standard_error, + n_obs=len(frame), + p_value=p_value, + critical_value=critical, + diagnostics={ + "control_level": control_level, + "treated_level": treated_level, + "n_control": int(len(control)), + "n_treated": int(len(treated)), + "degrees_freedom": float(degrees_freedom), + "variance_estimator": "Welch", + }, + ) + + +def _regression_design( + frame: pd.DataFrame, + config: EstimatorConfig, + *, + treatment_column: str | None = None, +) -> tuple[pd.Series, pd.DataFrame, str]: + treatment_name = treatment_column or config.treatment + columns = [config.outcome, treatment_name, *config.covariates] + clean = _complete_cases(frame, columns) + y = pd.Series(_numeric_vector(clean, config.outcome), index=clean.index, name=config.outcome) + treatment = pd.Series( + _numeric_vector(clean, treatment_name), index=clean.index, name=treatment_name + ) + if np.isclose(treatment.var(), 0): + raise ValueError("treatment must vary") + covariates = _covariate_matrix(clean, config.covariates) + design = pd.concat([treatment, covariates], axis=1).astype(float) + design = sm.add_constant(design, has_constant="add") + full_rank = np.linalg.matrix_rank(design.to_numpy()) + without_treatment_rank = np.linalg.matrix_rank( + design.drop(columns=treatment_name).to_numpy() + ) + if full_rank == without_treatment_rank: + raise ValueError("treatment coefficient is not identified by the design matrix") + return y, design, treatment_name + + +def regression_adjustment( + data: pd.DataFrame, + config: EstimatorConfig | Mapping[str, Any] | None = None, +) -> EstimatorResult: + """OLS adjustment with HC1 heteroskedasticity-robust uncertainty.""" + + cfg = _coerce_config("regression_adjustment", config, {}) + frame = _eligible(data, cfg) + y, design, treatment_name = _regression_design(frame, cfg) + fit = sm.OLS(y, design).fit(cov_type="HC1") + estimate = float(fit.params[treatment_name]) + standard_error = float(fit.bse[treatment_name]) + interval = fit.conf_int(alpha=cfg.alpha).loc[treatment_name] + return EstimatorResult( + method="regression_adjustment", + target_estimand=cfg.target_estimand, + estimate=estimate, + standard_error=standard_error, + ci_low=float(interval.iloc[0]), + ci_high=float(interval.iloc[1]), + p_value=float(fit.pvalues[treatment_name]), + n_obs=int(fit.nobs), + outcome=cfg.outcome, + treatment=treatment_name, + alpha=cfg.alpha, + diagnostics={ + "covariates": list(cfg.covariates), + "variance_estimator": "HC1", + "r_squared": float(fit.rsquared), + "design_rank": int(np.linalg.matrix_rank(design.to_numpy())), + }, + ) + + +def cluster_robust( + data: pd.DataFrame, + config: EstimatorConfig | Mapping[str, Any] | None = None, +) -> EstimatorResult: + """OLS coefficient with small-sample corrected cluster-robust uncertainty.""" + + cfg = _coerce_config("cluster_robust", config, {}) + if cfg.cluster is None: + raise ValueError("cluster_robust requires config.cluster") + frame = _eligible(data, cfg) + required = [cfg.outcome, cfg.treatment, cfg.cluster, *cfg.covariates] + frame = _complete_cases(frame, required) + y, design, treatment_name = _regression_design(frame, cfg) + groups = frame.loc[y.index, cfg.cluster] + n_clusters = int(groups.nunique()) + if n_clusters < 2: + raise ValueError("cluster-robust inference requires at least two clusters") + fit = sm.OLS(y, design).fit( + cov_type="cluster", + cov_kwds={"groups": groups, "use_correction": True}, + use_t=True, + ) + estimate = float(fit.params[treatment_name]) + standard_error = float(fit.bse[treatment_name]) + critical = float(student_t.ppf(1.0 - cfg.alpha / 2.0, n_clusters - 1)) + statistic = ( + estimate / standard_error + if standard_error > 0 + else (0.0 if estimate == 0 else np.inf) + ) + p_value = float(2.0 * student_t.sf(abs(statistic), n_clusters - 1)) + return _normal_result( + method="cluster_robust", + config=cfg, + estimate=estimate, + standard_error=standard_error, + n_obs=int(fit.nobs), + p_value=p_value, + critical_value=critical, + diagnostics={ + "cluster_column": cfg.cluster, + "n_clusters": n_clusters, + "covariates": list(cfg.covariates), + "variance_estimator": "CR1", + "degrees_freedom": n_clusters - 1, + }, + ) + + +def two_way_cluster_robust( + data: pd.DataFrame, + config: EstimatorConfig | Mapping[str, Any] | None = None, +) -> EstimatorResult: + """OLS coefficient with geographic × temporal two-way clustered uncertainty. + + ``config.cluster`` names the geographic/randomization grouping and ``config.time`` + names the temporal grouping. The covariance uses the Cameron-Gelbach-Miller + inclusion-exclusion form implemented by statsmodels. A t reference distribution + with ``min(G_geo, G_time) - 1`` degrees of freedom is deliberately conservative. + """ + + cfg = _coerce_config("two_way_cluster_robust", config, {}) + if cfg.cluster is None or cfg.time is None: + raise ValueError( + "two_way_cluster_robust requires config.cluster and config.time" + ) + frame = _eligible(data, cfg) + required = [cfg.outcome, cfg.treatment, cfg.cluster, cfg.time, *cfg.covariates] + frame = _complete_cases(frame, required) + y, design, treatment_name = _regression_design(frame, cfg) + geo_groups = frame.loc[y.index, cfg.cluster] + time_groups = frame.loc[y.index, cfg.time] + n_geo_clusters = int(geo_groups.nunique()) + n_time_clusters = int(time_groups.nunique()) + if min(n_geo_clusters, n_time_clusters) < 2: + raise ValueError("two-way clustered inference requires at least two groups per dimension") + fit = sm.OLS(y, design).fit() + covariance, _, _ = cov_cluster_2groups( + fit, + geo_groups, + time_groups, + use_correction=True, + ) + coefficient_index = int(design.columns.get_loc(treatment_name)) + variance = float(covariance[coefficient_index, coefficient_index]) + if not np.isfinite(variance) or variance < 0: + raise ValueError("two-way clustered treatment variance is negative or non-finite") + estimate = float(fit.params[treatment_name]) + standard_error = float(np.sqrt(variance)) + degrees_freedom = min(n_geo_clusters, n_time_clusters) - 1 + statistic = ( + estimate / standard_error + if standard_error > 0 + else (0.0 if estimate == 0 else np.inf) + ) + p_value = float(2.0 * student_t.sf(abs(statistic), degrees_freedom)) + critical = float(student_t.ppf(1.0 - cfg.alpha / 2.0, degrees_freedom)) + return _normal_result( + method="two_way_cluster_robust", + config=cfg, + estimate=estimate, + standard_error=standard_error, + n_obs=int(fit.nobs), + p_value=p_value, + critical_value=critical, + diagnostics={ + "geographic_cluster_column": cfg.cluster, + "time_cluster_column": cfg.time, + "n_geographic_clusters": n_geo_clusters, + "n_time_clusters": n_time_clusters, + "covariates": list(cfg.covariates), + "variance_estimator": "two-way cluster CR1 inclusion-exclusion", + "degrees_freedom": degrees_freedom, + "inference_warning": ( + "few groups require randomization or small-sample sensitivity analysis" + if min(n_geo_clusters, n_time_clusters) < 8 + else None + ), + }, + ) + + +def _infer_column( + frame: pd.DataFrame, + explicit: str | None, + candidates: Sequence[str], + role: str, +) -> str: + if explicit is not None: + if explicit not in frame: + raise ValueError(f"{role} column {explicit!r} not found") + return explicit + for candidate in candidates: + if candidate in frame: + return candidate + raise ValueError(f"could not infer {role} column; set it in EstimatorConfig") + + +def difference_in_differences( + data: pd.DataFrame, + config: EstimatorConfig | Mapping[str, Any] | None = None, +) -> EstimatorResult: + """Two-way fixed-effects DiD for a supplied or inferred active treatment. + + If ``config.post`` is supplied, ``config.treatment`` is interpreted as treated + group membership and their interaction is the coefficient of interest. Without + ``post``, the treatment column must itself be the active treatment indicator. + """ + + cfg = _coerce_config("difference_in_differences", config, {}) + frame = _eligible(data, cfg) + unit = _infer_column(frame, cfg.unit, ("zone_id", "unit_id", "cluster_id"), "unit") + time = _infer_column(frame, cfg.time, ("period_id", "time", "date"), "time") + required = [cfg.outcome, cfg.treatment, unit, time, *cfg.covariates] + if cfg.post is not None: + required.append(cfg.post) + frame = _complete_cases(frame, required) + treatment_name = "_did_treatment" + if cfg.post is not None: + frame[treatment_name] = ( + _numeric_vector(frame, cfg.treatment) * _numeric_vector(frame, cfg.post) + ) + else: + frame[treatment_name] = _numeric_vector(frame, cfg.treatment) + within_variation = frame.groupby(unit, observed=True)[treatment_name].nunique() + if int((within_variation > 1).sum()) == 0: + raise ValueError("DiD treatment must vary within unit or config.post must be supplied") + + y = pd.Series(_numeric_vector(frame, cfg.outcome), index=frame.index) + active = pd.Series( + frame[treatment_name].to_numpy(dtype=float), index=frame.index, name=treatment_name + ) + covariates = _covariate_matrix(frame, cfg.covariates) + unit_dummies = pd.get_dummies( + frame[unit].astype("category"), prefix="unit", drop_first=True, dtype=float + ) + time_dummies = pd.get_dummies( + frame[time].astype("category"), prefix="time", drop_first=True, dtype=float + ) + design = pd.concat([active, covariates, unit_dummies, time_dummies], axis=1) + design = sm.add_constant(design.astype(float), has_constant="add") + if np.linalg.matrix_rank(design.to_numpy()) == np.linalg.matrix_rank( + design.drop(columns=treatment_name).to_numpy() + ): + raise ValueError("DiD treatment contrast is collinear with fixed effects") + groups = frame[unit] + n_clusters = int(groups.nunique()) + if n_clusters < 2: + raise ValueError("DiD requires at least two panel units") + fit = sm.OLS(y, design).fit( + cov_type="cluster", + cov_kwds={"groups": groups, "use_correction": True}, + use_t=True, + ) + estimate = float(fit.params[treatment_name]) + standard_error = float(fit.bse[treatment_name]) + critical = float(student_t.ppf(1.0 - cfg.alpha / 2.0, n_clusters - 1)) + statistic = estimate / standard_error if standard_error > 0 else (0.0 if estimate == 0 else np.inf) + p_value = float(2.0 * student_t.sf(abs(statistic), n_clusters - 1)) + return _normal_result( + method="difference_in_differences", + config=cfg, + estimate=estimate, + standard_error=standard_error, + n_obs=int(fit.nobs), + p_value=p_value, + critical_value=critical, + treatment=treatment_name, + diagnostics={ + "unit_column": unit, + "time_column": time, + "post_column": cfg.post, + "n_units": n_clusters, + "variance_estimator": "unit-clustered CR1", + "parallel_trends_required": True, + }, + ) + + +def _binary_treatment(values: np.ndarray) -> tuple[np.ndarray, tuple[float, float]]: + levels = np.unique(values) + if len(levels) != 2: + raise ValueError("this estimator requires exactly two treatment levels") + low, high = float(levels[0]), float(levels[1]) + return (values == high).astype(int), (low, high) + + +def _influence_standard_error( + scores: np.ndarray, + clusters: pd.Series | np.ndarray | None, +) -> tuple[float, dict[str, Any]]: + centered = scores - scores.mean() + n_obs = len(scores) + if clusters is None: + return float(scores.std(ddof=1) / np.sqrt(n_obs)), { + "variance_estimator": "influence_iid" + } + labels = pd.Series(np.asarray(clusters)).reset_index(drop=True) + unique = labels.unique() + if len(unique) < 2: + raise ValueError("clustered influence-function inference needs at least two clusters") + label_values = labels.to_numpy() + sums = np.asarray([centered[label_values == label].sum() for label in unique]) + variance = len(unique) / (len(unique) - 1) * float(np.sum(sums**2)) / n_obs**2 + return float(np.sqrt(variance)), { + "variance_estimator": "clustered_influence_function", + "n_clusters": int(len(unique)), + } + + +def _nuisance_splits( + frame: pd.DataFrame, + treatment: np.ndarray, + config: EstimatorConfig, +) -> tuple[list[tuple[np.ndarray, np.ndarray]], dict[str, Any]]: + """Construct honest row- or group-level nuisance folds.""" + + if config.cluster is None: + group_counts = np.bincount(treatment, minlength=2) + n_splits = min(config.crossfit_folds, int(group_counts.min())) + if n_splits < 2: + raise ValueError("doubly robust estimation needs at least two observations per arm") + splitter = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=config.seed) + splits = list(splitter.split(np.zeros((len(frame), 1)), treatment)) + return splits, { + "crossfit_folds": n_splits, + "crossfit_unit": "row", + "group_leakage_prevented": False, + } + + groups = frame[config.cluster].to_numpy() + n_groups = int(pd.Series(groups).nunique()) + for n_splits in range(min(config.crossfit_folds, n_groups), 1, -1): + splitter = StratifiedGroupKFold( + n_splits=n_splits, + shuffle=True, + random_state=config.seed, + ) + candidate = list( + splitter.split(np.zeros((len(frame), 1)), treatment, groups=groups) + ) + if all(np.unique(treatment[train]).size == 2 for train, _ in candidate): + for train, test in candidate: + if np.intersect1d(groups[train], groups[test]).size: + raise AssertionError("group-aware cross-fitting leaked a cluster") + return candidate, { + "crossfit_folds": n_splits, + "crossfit_unit": config.cluster, + "crossfit_groups": n_groups, + "group_leakage_prevented": True, + } + raise ValueError( + "cluster-aware doubly robust estimation needs enough clusters in both arms" + ) + + +def doubly_robust( + data: pd.DataFrame, + config: EstimatorConfig | Mapping[str, Any] | None = None, +) -> EstimatorResult: + """Cross-fitted augmented inverse-probability weighted ATE.""" + + cfg = _coerce_config("doubly_robust", config, {}) + frame = _eligible(data, cfg) + required = [cfg.outcome, cfg.treatment, *cfg.covariates] + if cfg.propensity is not None: + required.append(cfg.propensity) + if cfg.cluster is not None: + required.append(cfg.cluster) + frame = _complete_cases(frame, required).reset_index(drop=True) + y = _numeric_vector(frame, cfg.outcome) + raw_treatment = _numeric_vector(frame, cfg.treatment) + treatment, levels = _binary_treatment(raw_treatment) + matrix = _covariate_matrix(frame, cfg.covariates) + x = matrix.to_numpy(dtype=float) if len(matrix.columns) else np.zeros((len(frame), 1)) + mu0 = np.empty(len(frame), dtype=float) + mu1 = np.empty(len(frame), dtype=float) + propensity = np.empty(len(frame), dtype=float) + splits, split_diagnostics = _nuisance_splits(frame, treatment, cfg) + supplied_propensity = ( + _numeric_vector(frame, cfg.propensity) if cfg.propensity is not None else None + ) + if supplied_propensity is not None and ( + (supplied_propensity <= 0).any() or (supplied_propensity >= 1).any() + ): + raise ValueError("supplied propensity scores must lie strictly inside (0, 1)") + for train, test in splits: + train_control = train[treatment[train] == 0] + train_treated = train[treatment[train] == 1] + outcome0 = LinearRegression().fit(x[train_control], y[train_control]) + outcome1 = LinearRegression().fit(x[train_treated], y[train_treated]) + mu0[test] = outcome0.predict(x[test]) + mu1[test] = outcome1.predict(x[test]) + if supplied_propensity is None: + propensity_model = make_pipeline( + StandardScaler(), + LogisticRegression(max_iter=2_000, random_state=cfg.seed, C=1.0), + ) + propensity_model.fit(x[train], treatment[train]) + propensity[test] = propensity_model.predict_proba(x[test])[:, 1] + else: + propensity[test] = supplied_propensity[test] + unclipped_propensity = propensity.copy() + propensity = np.clip(propensity, 0.02, 0.98) + scores = ( + mu1 + - mu0 + + treatment * (y - mu1) / propensity + - (1 - treatment) * (y - mu0) / (1.0 - propensity) + ) + estimate = float(scores.mean()) + clusters = frame[cfg.cluster] if cfg.cluster is not None else None + standard_error, variance_diagnostics = _influence_standard_error(scores, clusters) + diagnostics: dict[str, Any] = { + "covariates": list(cfg.covariates), + **split_diagnostics, + "control_level": levels[0], + "treated_level": levels[1], + "propensity_min_unclipped": float(unclipped_propensity.min()), + "propensity_max_unclipped": float(unclipped_propensity.max()), + "propensity_clip": [0.02, 0.98], + "estimating_equation": "AIPW", + **variance_diagnostics, + } + p_value: float | None = None + critical_value: float | None = None + if cfg.cluster is not None: + n_clusters = int(variance_diagnostics["n_clusters"]) + degrees_freedom = n_clusters - 1 + critical_value = float(student_t.ppf(1.0 - cfg.alpha / 2.0, degrees_freedom)) + statistic = ( + estimate / standard_error + if standard_error > 0 + else (0.0 if estimate == 0 else np.inf) + ) + p_value = float(2.0 * student_t.sf(abs(statistic), degrees_freedom)) + diagnostics["degrees_freedom"] = degrees_freedom + diagnostics["reference_distribution"] = "cluster_t" + else: + diagnostics["reference_distribution"] = "normal" + return _normal_result( + method="doubly_robust", + config=cfg, + estimate=estimate, + standard_error=standard_error, + n_obs=len(frame), + p_value=p_value, + critical_value=critical_value, + diagnostics=diagnostics, + ) + + +def synthetic_control( + data: pd.DataFrame, + config: EstimatorConfig | Mapping[str, Any] | None = None, +) -> EstimatorResult: + """Nonnegative donor-weight synthetic-control-style post-period contrast. + + The interval uses pre-treatment fit residuals as a diagnostic approximation; it + is not presented as randomization inference. The result records this limitation. + """ + + cfg = _coerce_config("synthetic_control", config, {}) + frame = _eligible(data, cfg) + unit = _infer_column(frame, cfg.unit, ("zone_id", "unit_id", "cluster_id"), "unit") + time = _infer_column(frame, cfg.time, ("period_id", "time", "date"), "time") + required = [cfg.outcome, cfg.treatment, unit, time] + if cfg.post is not None: + required.append(cfg.post) + frame = _complete_cases(frame, required) + treatment_by_unit = frame.groupby(unit, observed=True)[cfg.treatment].max() + treated_units = treatment_by_unit[treatment_by_unit > 0].index.tolist() + donor_units = treatment_by_unit[treatment_by_unit <= 0].index.tolist() + if not treated_units or not donor_units: + raise ValueError("synthetic control requires treated units and never-treated donors") + + treated_rows = frame[frame[unit].isin(treated_units)] + if cfg.post is not None: + post_mask = _numeric_vector(frame, cfg.post) > 0 + post_times = set(frame.loc[post_mask, time].tolist()) + pre_times = set(frame[time].tolist()).difference(post_times) + else: + active = treated_rows.loc[treated_rows[cfg.treatment] > 0, time] + if active.empty: + raise ValueError("could not infer a treatment onset") + onset = active.min() + pre_times = {value for value in frame[time].unique() if value < onset} + post_times = {value for value in frame[time].unique() if value >= onset} + if len(pre_times) < 2 or not post_times: + raise ValueError("synthetic control requires at least two pre periods and one post period") + + outcome_panel = frame.pivot_table( + index=time, columns=unit, values=cfg.outcome, aggfunc="mean" + ) + treated_series = outcome_panel[treated_units].mean(axis=1) + donor_panel = outcome_panel[donor_units] + valid_times = outcome_panel.index[treated_series.notna() & donor_panel.notna().all(axis=1)] + ordered_pre = [value for value in valid_times if value in pre_times] + ordered_post = [value for value in valid_times if value in post_times] + if len(ordered_pre) < 2 or not ordered_post: + raise ValueError("insufficient complete pre/post donor outcomes") + x_pre = donor_panel.loc[ordered_pre].to_numpy(dtype=float) + y_pre = treated_series.loc[ordered_pre].to_numpy(dtype=float) + initial_weights = np.full(len(donor_units), 1.0 / len(donor_units)) + optimization = minimize( + lambda weights: float(np.mean(np.square(y_pre - x_pre @ weights))), + initial_weights, + method="SLSQP", + bounds=[(0.0, 1.0)] * len(donor_units), + constraints={"type": "eq", "fun": lambda weights: float(weights.sum() - 1.0)}, + ) + if optimization.success and np.isfinite(optimization.x).all(): + weights = np.clip(optimization.x, 0.0, 1.0) + weights = weights / weights.sum() + else: + # A deterministic single best donor is a transparent fallback when the + # constrained optimizer cannot converge. + donor_mse = np.mean(np.square(x_pre - y_pre[:, None]), axis=0) + weights = np.zeros(len(donor_units), dtype=float) + weights[int(np.argmin(donor_mse))] = 1.0 + synthetic_values = donor_panel.to_numpy(dtype=float) @ weights + synthetic_series = pd.Series(synthetic_values, index=donor_panel.index) + pre_gap = treated_series.loc[ordered_pre] - synthetic_series.loc[ordered_pre] + post_gap = treated_series.loc[ordered_post] - synthetic_series.loc[ordered_post] + estimate = float(post_gap.mean()) + pre_rmspe = float(np.sqrt(np.mean(np.square(pre_gap)))) + standard_error = float(pre_gap.std(ddof=1) / np.sqrt(len(ordered_post))) + return _normal_result( + method="synthetic_control", + config=cfg, + estimate=estimate, + standard_error=standard_error, + n_obs=len(frame), + diagnostics={ + "unit_column": unit, + "time_column": time, + "treated_units": [str(value) for value in treated_units], + "donor_weights": { + str(donor): float(weight) + for donor, weight in zip(donor_units, weights, strict=True) + }, + "n_pre_periods": len(ordered_pre), + "n_post_periods": len(ordered_post), + "pre_rmspe": pre_rmspe, + "weight_optimizer_converged": bool(optimization.success), + "uncertainty_warning": ( + "pre-fit residual approximation; use placebo or randomization inference " + "for decisions" + ), + }, + ) + + +_ESTIMATORS: dict[str, Callable[[pd.DataFrame, EstimatorConfig], EstimatorResult]] = { + "difference_in_means": difference_in_means, + "regression_adjustment": regression_adjustment, + "cluster_robust": cluster_robust, + "two_way_cluster_robust": two_way_cluster_robust, + "difference_in_differences": difference_in_differences, + "doubly_robust": doubly_robust, + "synthetic_control": synthetic_control, +} + + +def estimate_effect( + data: pd.DataFrame, + method: str | EstimatorConfig | None = None, + config: EstimatorConfig | Mapping[str, Any] | None = None, + **overrides: Any, +) -> EstimatorResult: + """Dispatch to a named estimator and return the shared scalar result type.""" + + cfg = _coerce_config(method, config, overrides) + try: + estimator = _ESTIMATORS[cfg.method] + except KeyError as exc: + choices = ", ".join(sorted(_ESTIMATORS)) + raise ValueError(f"unknown estimator {cfg.method!r}; choose one of: {choices}") from exc + return estimator(data, cfg) + + +def estimate_ladder( + data: pd.DataFrame, + methods: Sequence[str] | None = None, + config: EstimatorConfig | Mapping[str, Any] | None = None, + *, + on_error: str = "record", + **overrides: Any, +) -> pd.DataFrame: + """Run comparable estimators, recording inapplicable-method diagnostics. + + ``on_error='raise'`` is useful in tests; ``'record'`` keeps a benchmark table + rectangular when, for example, a design has no pre-period for synthetic control. + """ + + if on_error not in {"record", "raise"}: + raise ValueError("on_error must be 'record' or 'raise'") + selected = list(methods or _ESTIMATORS) + rows: list[dict[str, Any]] = [] + for method_name in selected: + try: + result = estimate_effect(data, method_name, config, **overrides) + row = result.to_dict() + row["status"] = "ok" + rows.append(row) + except (ValueError, np.linalg.LinAlgError) as exc: + if on_error == "raise": + raise + cfg = _coerce_config(method_name, config, overrides) + rows.append( + { + "method": cfg.method, + "target_estimand": cfg.target_estimand, + "estimate": np.nan, + "standard_error": np.nan, + "se": np.nan, + "ci_low": np.nan, + "ci_high": np.nan, + "p_value": np.nan, + "n_obs": 0, + "outcome": cfg.outcome, + "treatment": cfg.treatment, + "alpha": cfg.alpha, + "diagnostics": {"error": str(exc)}, + "status": "not_applicable", + } + ) + return pd.DataFrame(rows) + + +def estimate_heterogeneous_effects( + data: pd.DataFrame, + covariates: Sequence[str], + *, + outcome: str = "outcome", + treatment: str = "assigned_treatment", + folds: int = 3, + seed: int = 202503, +) -> pd.DataFrame: + """Cross-fitted linear T-learner benchmark for unit-level heterogeneity. + + The learner is intentionally simple. Its predictions are exploratory unless + treatment is randomized or unconfounded conditional on the supplied covariates. + """ + + if folds < 2: + raise ValueError("folds must be at least 2") + columns = [outcome, treatment, *covariates] + frame = _complete_cases(data, columns).copy() + frame["_original_index"] = frame.index + frame = frame.reset_index(drop=True) + y = _numeric_vector(frame, outcome) + raw_treatment = _numeric_vector(frame, treatment) + assigned, levels = _binary_treatment(raw_treatment) + matrix = _covariate_matrix(frame, covariates) + x = matrix.to_numpy(dtype=float) if len(matrix.columns) else np.zeros((len(frame), 1)) + counts = np.bincount(assigned, minlength=2) + n_splits = min(folds, int(counts.min())) + if n_splits < 2: + raise ValueError("T-learner needs at least two observations per arm") + mu0 = np.empty(len(frame), dtype=float) + mu1 = np.empty(len(frame), dtype=float) + splitter = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=seed) + for train, test in splitter.split(x, assigned): + train_control = train[assigned[train] == 0] + train_treated = train[assigned[train] == 1] + model0 = LinearRegression().fit(x[train_control], y[train_control]) + model1 = LinearRegression().fit(x[train_treated], y[train_treated]) + mu0[test] = model0.predict(x[test]) + mu1[test] = model1.predict(x[test]) + return pd.DataFrame( + { + "row_index": frame["_original_index"].to_numpy(), + "predicted_y0": mu0, + "predicted_y1": mu1, + "estimated_treatment_effect": mu1 - mu0, + "control_level": levels[0], + "treated_level": levels[1], + "method": "cross_fitted_linear_t_learner", + "evidence_type": "model_based_heterogeneity_conditional_on_identification", + } + ) + + +estimate = estimate_effect +estimate_hte = estimate_heterogeneous_effects diff --git a/CasualLab/src/casuallab/generated_reports.py b/CasualLab/src/casuallab/generated_reports.py new file mode 100644 index 0000000000000000000000000000000000000000..234a262c8485f9d77aaeb460891d9abc779e432d --- /dev/null +++ b/CasualLab/src/casuallab/generated_reports.py @@ -0,0 +1,4557 @@ +"""Code-generated technical and executive reports from machine-readable artifacts.""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd + +from casuallab.config import load_simulation_config +from casuallab.equilibrium import ( + CAUSAL_SCOPE as EQUILIBRIUM_CAUSAL_SCOPE, +) +from casuallab.equilibrium import ( + EMPIRICAL_STATUS as EQUILIBRIUM_EMPIRICAL_STATUS, +) +from casuallab.equilibrium import ( + EVIDENCE_TYPE as EQUILIBRIUM_EVIDENCE_TYPE, +) +from casuallab.nyc_benchmark import ( + NYC_BENCHMARK_EVIDENCE_TYPE, + NYC_BENCHMARK_SCHEMA_VERSION, +) +from casuallab.nyc_events import EVENT_EVIDENCE_LABEL, EVENT_SCHEMA_VERSION +from casuallab.nyc_graph_benchmark import ( + BENCHMARK_EVIDENCE as NYC_GRAPH_EVIDENCE_TYPE, +) +from casuallab.nyc_graph_benchmark import ( + validate_nyc_graph_bundle, +) +from casuallab.nyc_income import INCOME_EVIDENCE_LABEL, INCOME_SCHEMA_VERSION +from casuallab.nyc_simulation import ( + CAUSAL_ASSUMPTION_FIELDS, + validate_nyc_simulation_anchor_integrity, +) +from casuallab.nyc_weather import WEATHER_EVIDENCE_LABEL +from casuallab.reporting import ( + _strict_boolean, + _validate_policy_provenance, + choose_recommendation, + markdown_table, + sha256_file, +) + + +def _validate_benchmark(frame: pd.DataFrame) -> None: + required = { + "design", + "estimator", + "target_estimand", + "scenario", + "declared_scenario_set", + "declared_scenario_count", + "rmse", + "coverage", + "power", + "identified", + "inference_valid", + "fit_complete", + "applicable", + "attempted_fits", + "successful_fits", + "bias", + "evidence_type", + } + missing = required.difference(frame.columns) + if missing: + raise ValueError(f"benchmark results missing columns: {sorted(missing)}") + if frame.empty: + raise ValueError("benchmark results are empty") + if not frame["evidence_type"].astype(str).str.startswith("semi_synthetic").all(): + raise ValueError("benchmark rows must be labeled semi-synthetic") + + +def _optional_hash(path: str | Path | None, label: str) -> str: + if path is None: + return f"- {label}: not supplied" + source = Path(path) + if not source.is_file(): + return f"- {label}: not supplied" + return f"- {label} SHA-256: `{sha256_file(source)}`" + + +def _counted(count: int, singular: str, plural: str | None = None) -> str: + """Render a count without producing strings such as ``1 trips``.""" + + return f"{count:,} {singular if count == 1 else plural or singular + 's'}" + + +def _load_json_object(path: Path, label: str) -> dict[str, Any]: + if not path.is_file(): + raise FileNotFoundError(f"{label} is required: {path}") + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (json.JSONDecodeError, OSError) as exc: + raise ValueError(f"{label} is not readable valid JSON: {path}") from exc + if not isinstance(payload, dict): + raise ValueError(f"{label} must be a JSON object") + return payload + + +def _portable_manifest_path(raw_path: object, label: str) -> Path: + if not isinstance(raw_path, str) or not raw_path: + raise ValueError(f"{label} must be a nonempty path string") + path = Path(raw_path) + if path.is_absolute() or ".." in path.parts: + raise ValueError(f"{label} must be project-relative and portable") + return path + + +def _manifest_root_for_artifact( + manifest: dict[str, Any], artifact_path: Path, label: str +) -> Path: + files = manifest.get("files") + if not isinstance(files, list) or not files: + raise ValueError(f"{label} manifest has no file entries") + target = artifact_path.resolve() + for entry in files: + if not isinstance(entry, dict): + raise ValueError(f"{label} manifest contains a non-object entry") + rendered = _portable_manifest_path( + entry.get("path"), f"{label} manifest entry path" + ) + for candidate_root in target.parents: + if (candidate_root / rendered).resolve() == target: + return candidate_root.resolve() + raise ValueError( + f"{label} manifest does not contain the supplied artifact" + ) + + +def _validate_manifest_files( + manifest: dict[str, Any], manifest_root: Path, label: str +) -> dict[Path, dict[str, Any]]: + validated: dict[Path, dict[str, Any]] = {} + for raw_entry in manifest["files"]: + if not isinstance(raw_entry, dict): + raise ValueError(f"{label} manifest contains a non-object entry") + rendered = _portable_manifest_path( + raw_entry.get("path"), f"{label} manifest entry path" + ) + expected_bytes = raw_entry.get("bytes") + expected_sha256 = raw_entry.get("sha256") + if ( + isinstance(expected_bytes, bool) + or not isinstance(expected_bytes, int) + or expected_bytes < 0 + or not isinstance(expected_sha256, str) + or len(expected_sha256) != 64 + ): + raise ValueError(f"{label} manifest has an invalid hash entry") + resolved = (manifest_root / rendered).resolve() + try: + resolved.relative_to(manifest_root) + except ValueError as exc: + raise ValueError( + f"{label} manifest entry escapes its project root" + ) from exc + if resolved in validated: + raise ValueError(f"{label} manifest contains duplicate paths") + if not resolved.is_file(): + raise FileNotFoundError(f"{label} manifest file is missing: {resolved}") + if resolved.stat().st_size != expected_bytes: + raise ValueError(f"{label} manifest byte mismatch: {rendered}") + if sha256_file(resolved) != expected_sha256: + raise ValueError(f"{label} manifest SHA-256 mismatch: {rendered}") + validated[resolved] = raw_entry + return validated + + +@dataclass(frozen=True, slots=True) +class _ManifestBundle: + """One manifest whose portable file set has been independently verified.""" + + path: Path + root: Path + payload: dict[str, Any] + files: dict[Path, dict[str, Any]] + inputs: dict[Path, dict[str, Any]] + + +def _manifest_bundle( + manifest_path: str | Path | None, + label: str, +) -> _ManifestBundle | None: + """Resolve a manifest-only optional input without assuming a repository location.""" + + if manifest_path is None: + return None + manifest_file = Path(manifest_path).resolve() + payload = _load_json_object(manifest_file, f"{label} manifest") + raw_files = payload.get("files") + if not isinstance(raw_files, list) or not raw_files: + raise ValueError(f"{label} manifest has no file entries") + rendered: list[Path] = [] + for entry in raw_files: + if not isinstance(entry, dict): + raise ValueError(f"{label} manifest contains a non-object entry") + rendered.append( + _portable_manifest_path(entry.get("path"), f"{label} manifest entry path") + ) + roots = [ + root.resolve() + for root in manifest_file.parents + if all((root / relative).resolve().is_file() for relative in rendered) + ] + if len(roots) != 1: + raise ValueError( + f"{label} manifest portable root is " + f"{'ambiguous' if roots else 'unresolvable'}" + ) + incomplete = sorted(manifest_file.parent.glob("*INCOMPLETE*.json")) + if incomplete: + raise ValueError(f"{label} evidence is marked incomplete") + root = roots[0] + files = _validate_manifest_files(payload, root, label) + raw_inputs = payload.get("inputs", []) + if not isinstance(raw_inputs, list): + raise ValueError(f"{label} manifest inputs must be a list") + inputs: dict[Path, dict[str, Any]] = {} + if raw_inputs: + rendered_inputs: list[Path] = [] + for entry in raw_inputs: + if not isinstance(entry, dict): + raise ValueError(f"{label} manifest contains a non-object input") + rendered_inputs.append( + _portable_manifest_path( + entry.get("path"), f"{label} manifest input path" + ) + ) + input_roots = [ + candidate.resolve() + for candidate in manifest_file.parents + if all( + (candidate / relative).resolve().is_file() + for relative in rendered_inputs + ) + ] + if len(input_roots) != 1: + raise ValueError( + f"{label} manifest input root is " + f"{'ambiguous' if input_roots else 'unresolvable'}" + ) + inputs = _validate_manifest_files( + {"files": raw_inputs}, input_roots[0], f"{label} input" + ) + declared_digest = payload.get("declared_file_set_sha256") + if declared_digest is not None: + actual_digest = hashlib.sha256( + json.dumps(raw_files, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + if declared_digest != actual_digest: + raise ValueError(f"{label} declared file-set digest is inconsistent") + declared_input_digest = payload.get("declared_input_set_sha256") + if declared_input_digest is not None: + actual_input_digest = hashlib.sha256( + json.dumps(raw_inputs, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + if declared_input_digest != actual_input_digest: + raise ValueError(f"{label} declared input-set digest is inconsistent") + return _ManifestBundle(manifest_file, root, payload, files, inputs) + + +def _require_manifest_evidence( + bundle: _ManifestBundle, + expected: str, + label: str, +) -> None: + metadata = bundle.payload.get("metadata") + values = { + bundle.payload.get("evidence_type"), + bundle.payload.get("evidence_label"), + } + if isinstance(metadata, dict): + values.update({metadata.get("evidence_type"), metadata.get("evidence_label")}) + values.discard(None) + if expected not in values: + raise ValueError(f"{label} manifest has an incompatible evidence label") + + +def _json_objects(bundle: _ManifestBundle, label: str) -> dict[Path, dict[str, Any]]: + objects: dict[Path, dict[str, Any]] = {} + for path in bundle.files: + if path.suffix.lower() == ".json": + objects[path] = _load_json_object(path, f"{label} JSON artifact") + return objects + + +def _unique_json_object( + bundle: _ManifestBundle, + predicate: Callable[[dict[str, Any]], bool], + artifact_label: str, +) -> tuple[Path, dict[str, Any]]: + candidates = [ + (path, payload) + for path, payload in _json_objects(bundle, artifact_label).items() + if predicate(payload) + ] + if len(candidates) != 1: + raise ValueError( + f"{artifact_label} manifest must identify exactly one matching JSON artifact" + ) + return candidates[0] + + +def _csv_header(path: Path, label: str) -> set[str]: + try: + return set(pd.read_csv(path, nrows=0).columns) + except (OSError, pd.errors.ParserError, pd.errors.EmptyDataError) as exc: + raise ValueError(f"{label} is not a readable CSV artifact") from exc + + +def _unique_csv( + bundle: _ManifestBundle, + required_columns: set[str], + artifact_label: str, + *, + excluded_columns: set[str] | None = None, +) -> tuple[Path, pd.DataFrame]: + excluded = excluded_columns or set() + candidates = [ + path + for path in bundle.files + if path.suffix.lower() == ".csv" + and required_columns.issubset(_csv_header(path, artifact_label)) + and not excluded.intersection(_csv_header(path, artifact_label)) + ] + if len(candidates) != 1: + raise ValueError( + f"{artifact_label} manifest must identify exactly one matching CSV artifact" + ) + return candidates[0], pd.read_csv(candidates[0]) + + +def _valid_sha256(value: object) -> bool: + return ( + isinstance(value, str) + and len(value) == 64 + and all(character in "0123456789abcdef" for character in value) + ) + + +def _file_with_declared_hash( + bundle: _ManifestBundle, + digest: object, + label: str, +) -> Path: + if not _valid_sha256(digest): + raise ValueError(f"{label} is not a valid SHA-256 digest") + declared = {**bundle.files, **bundle.inputs} + matches = [path for path, entry in declared.items() if entry.get("sha256") == digest] + if len(matches) != 1: + raise ValueError(f"{label} is not uniquely covered by the evidence manifest") + return matches[0] + + +def _bundle_file_by_role( + bundle: _ManifestBundle, + role: str, + label: str, +) -> Path: + matches = [path for path, entry in bundle.files.items() if entry.get("role") == role] + if len(matches) != 1: + raise ValueError(f"{label} manifest must identify exactly one {role!r} file") + return matches[0] + + +def _bundle_input_by_role( + bundle: _ManifestBundle, + role: str, + label: str, +) -> Path: + matches = [path for path, entry in bundle.inputs.items() if entry.get("role") == role] + if len(matches) != 1: + raise ValueError(f"{label} manifest must identify exactly one {role!r} input") + return matches[0] + + +def _required_string_list(value: object, label: str) -> list[str]: + if ( + not isinstance(value, list) + or not value + or not all(isinstance(item, str) and item.strip() for item in value) + ): + raise ValueError(f"{label} must be a nonempty string list") + return value + + +def _required_int(mapping: dict[str, Any], key: str, label: str) -> int: + value = mapping.get(key) + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + raise ValueError(f"NYC full validation {label}.{key} must be a nonnegative integer") + return value + + +def _required_positive_number(mapping: dict[str, Any], key: str, label: str) -> float: + value = mapping.get(key) + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError(f"NYC full validation {label}.{key} must be numeric") + numeric = float(value) + if not np.isfinite(numeric) or numeric <= 0: + raise ValueError(f"NYC full validation {label}.{key} must be positive and finite") + return numeric + + +@dataclass(frozen=True, slots=True) +class _NYCFullEvidence: + summary: str + limitations: str + provenance: str + validation_path: Path + manifest_path: Path + data_manifest_path: Path + + +def _nyc_full_status( + validation_path: str | Path | None, + manifest_path: str | Path | None, +) -> _NYCFullEvidence | None: + """Validate and summarize an optional full-month NYC evidence bundle. + + Supplying either path activates a fail-closed contract: both artifacts, every + analysis-manifest file, and the source-data lineage must agree before report + text is generated. + """ + + if validation_path is None and manifest_path is None: + return None + if validation_path is None or manifest_path is None: + raise ValueError( + "NYC full evidence requires both validation.json and its analysis manifest" + ) + validation_file = Path(validation_path) + manifest_file = Path(manifest_path) + validation = _load_json_object(validation_file, "NYC full validation") + manifest = _load_json_object(manifest_file, "NYC full analysis manifest") + if validation.get("evidence_label") != "descriptive_real_data": + raise ValueError("NYC full validation must be labeled descriptive_real_data") + if validation.get("causal_claim") is not False: + raise ValueError("NYC full validation must declare causal_claim=false") + if validation.get("validation_passed") is not True: + raise ValueError("NYC full validation did not pass") + checks = validation.get("checks") + if not isinstance(checks, dict) or not checks: + raise ValueError("NYC full validation checks are missing") + required_checks = { + "raw_equals_clean", + "zone_conserves_clean", + "od_conserves_clean", + "calendar_complete", + "manifest_files_valid", + "manifest_scope_valid", + "resource_limit_passed", + } + missing_checks = sorted(required_checks.difference(checks)) + if missing_checks: + raise ValueError(f"NYC full validation checks are incomplete: {missing_checks}") + invalid_checks = sorted( + key for key, value in checks.items() if value is not True + ) + if invalid_checks: + raise ValueError( + f"NYC full validation checks did not all pass: {invalid_checks}" + ) + + metadata = manifest.get("metadata") + if not isinstance(metadata, dict): + raise ValueError("NYC full analysis manifest metadata is missing") + if metadata.get("evidence_label") != "descriptive_real_data": + raise ValueError("NYC full analysis manifest has an incompatible evidence label") + if metadata.get("causal_claim") is not False: + raise ValueError("NYC full analysis manifest must declare causal_claim=false") + if metadata.get("validation_passed") is not True: + raise ValueError("NYC full analysis manifest does not record a passing validation") + + manifest_root = _manifest_root_for_artifact( + manifest, validation_file, "NYC full analysis" + ) + if (validation_file.parent / "NYC_FULL_ANALYSIS_INCOMPLETE.json").exists(): + raise ValueError("NYC full analysis is marked incomplete") + validated_files = _validate_manifest_files( + manifest, manifest_root, "NYC full analysis" + ) + resolved_validation = validation_file.resolve() + if resolved_validation not in validated_files: + raise ValueError("NYC full validation is not covered by the analysis manifest") + + provenance = validation.get("provenance") + if not isinstance(provenance, dict): + raise ValueError("NYC full validation provenance is missing") + rendered_data_manifest = _portable_manifest_path( + provenance.get("data_manifest"), "NYC full validation data_manifest" + ) + data_manifest_file = (manifest_root / rendered_data_manifest).resolve() + if (data_manifest_file.parent / "NYC_FULL_INCOMPLETE.json").exists(): + raise ValueError("NYC full source-data pipeline is marked incomplete") + if data_manifest_file not in validated_files: + raise ValueError( + "NYC full source-data manifest is not covered by the analysis manifest" + ) + expected_data_sha = provenance.get("data_manifest_sha256") + actual_data_sha = sha256_file(data_manifest_file) + if ( + not isinstance(expected_data_sha, str) + or expected_data_sha != actual_data_sha + or metadata.get("source_data_manifest_sha256") != actual_data_sha + or validated_files[data_manifest_file].get("sha256") != actual_data_sha + ): + raise ValueError("NYC full source-data manifest lineage hashes do not agree") + + data_manifest = _load_json_object(data_manifest_file, "NYC full source-data manifest") + data_config = data_manifest.get("config") + data_metadata = data_manifest.get("metadata") + analysis_config = manifest.get("config") + scope = validation.get("scope") + if ( + not isinstance(data_config, dict) + or not isinstance(data_metadata, dict) + or not isinstance(analysis_config, dict) + ): + raise ValueError("NYC full source-data manifest scope metadata is missing") + if not isinstance(scope, dict): + raise ValueError("NYC full validation scope is missing") + if ( + data_config.get("source") != "nyc_hvfhv" + or data_config.get("mode") != "full" + or data_metadata.get("causal_claim") is not False + or data_metadata.get("evidence_label") != "descriptive_real_data" + or scope.get("source") != "nyc_hvfhv" + or scope.get("population_claim") is not False + or scope.get("unit") != "published_completed_trip_record" + ): + raise ValueError("NYC full validation and source-data manifest scopes are incompatible") + compatibility_keys = ( + "source", + "mode", + "nyc_year", + "nyc_months", + "nyc_expected_rows", + "nyc_expected_bytes", + "nyc_expected_sha256", + "manifest_path", + ) + if any( + analysis_config.get(key) != data_config.get(key) + for key in compatibility_keys + ): + raise ValueError("NYC full analysis and source-data manifests use different configs") + months = data_config.get("nyc_months") + year = data_config.get("nyc_year") + expected_scope_month = ( + f"{year}-{months[0]:02d}" + if isinstance(year, int) + and isinstance(months, list) + and len(months) == 1 + and isinstance(months[0], int) + else None + ) + if scope.get("pickup_month") != expected_scope_month: + raise ValueError("NYC full validation month does not match the source-data manifest") + configured_manifest = data_config.get("manifest_path") + if configured_manifest != str(rendered_data_manifest): + raise ValueError("NYC full validation points to a different configured data manifest") + + coverage = validation.get("coverage") + conservation = validation.get("conservation") + resources = validation.get("resources") + limitations = validation.get("limitations") + if not isinstance(coverage, dict) or not isinstance(conservation, dict): + raise ValueError("NYC full validation coverage or conservation facts are missing") + if not isinstance(resources, dict): + raise ValueError("NYC full validation resources are missing") + if ( + not isinstance(limitations, list) + or not limitations + or not all(isinstance(item, str) and item.strip() for item in limitations) + ): + raise ValueError("NYC full validation limitations are missing") + + raw_rows = _required_int(conservation, "raw_rows", "conservation") + clean_rows = _required_int(coverage, "clean_rows", "coverage") + zone_rows = _required_int(conservation, "zone_time_rows", "conservation") + od_rows = _required_int(conservation, "od_rows", "conservation") + zone_sum = _required_int(conservation, "zone_trip_sum", "conservation") + od_sum = _required_int(conservation, "od_trip_sum", "conservation") + service_dates = _required_int(coverage, "service_dates", "coverage") + hours = _required_int(coverage, "hours_of_day", "coverage") + date_hours = _required_int(coverage, "date_hours", "coverage") + if raw_rows == 0 or not (raw_rows == clean_rows == zone_sum == od_sum): + raise ValueError("NYC full validation row-conservation facts are inconsistent") + if service_dates == 0 or hours != 24 or date_hours != service_dates * hours: + raise ValueError("NYC full validation calendar facts are inconsistent") + expected_rows = data_config.get("nyc_expected_rows") + raw_hashes = provenance.get("sha256") + if expected_rows is not None and expected_rows != raw_rows: + raise ValueError("NYC full validation row count disagrees with the pinned source") + if ( + not isinstance(raw_hashes, list) + or not raw_hashes + or not all(isinstance(value, str) and len(value) == 64 for value in raw_hashes) + ): + raise ValueError("NYC full validation raw-object hashes are missing") + expected_raw_sha = data_config.get("nyc_expected_sha256") + if expected_raw_sha is not None and raw_hashes != [expected_raw_sha]: + raise ValueError("NYC full validation raw-object hash disagrees with the pin") + + elapsed = _required_positive_number(resources, "elapsed_seconds", "resources") + max_rss = int(_required_positive_number(resources, "max_rss_bytes", "resources")) + memory_limit = int( + _required_positive_number(resources, "memory_limit_bytes", "resources") + ) + if max_rss >= memory_limit: + raise ValueError("NYC full validation resource facts exceed the declared limit") + peak_footprint_value = resources.get("peak_memory_footprint_bytes") + footprint_text = "" + if peak_footprint_value is not None: + peak_footprint = int( + _required_positive_number( + resources, "peak_memory_footprint_bytes", "resources" + ) + ) + footprint_text = ( + f", and peak memory footprint {peak_footprint:,} bytes " + f"({peak_footprint / 1024**3:.2f} GiB)" + ) + + validation_sha = sha256_file(validation_file) + manifest_sha = sha256_file(manifest_file) + summary = ( + f"The verified NYC TLC HVFHV full-month bundle covers **{scope['pickup_month']}**: " + f"{_counted(raw_rows, 'published completed-trip record')}, " + f"{service_dates} service days × {hours} hours = {date_hours} date-hours, " + f"{zone_rows:,} complete zone-hour rows, and {od_rows:,} observed OD-hour rows. " + f"Raw, clean, zone-panel, and OD-panel trip totals all equal {raw_rows:,}. " + f"The cached-raw end-to-end validation completed in {elapsed:.2f} seconds with " + f"maximum RSS {max_rss:,} bytes ({max_rss / 1024**3:.2f} GiB)" + f"{footprint_text}, below the {memory_limit / 1024**3:.0f} GiB envelope. " + "These are descriptive facts about published completed trips, not a causal " + "effect, price elasticity, latent-demand estimate, or population claim." + ) + limitation_text = "\n".join(f"- {item}" for item in limitations) + provenance_text = "\n".join( + [ + f"- NYC full validation SHA-256: `{validation_sha}`", + f"- NYC full analysis manifest SHA-256: `{manifest_sha}`", + f"- NYC full source-data manifest SHA-256: `{actual_data_sha}`", + "- NYC pinned raw object SHA-256: " + + ", ".join(f"`{value}`" for value in raw_hashes), + ] + ) + return _NYCFullEvidence( + summary=summary, + limitations=limitation_text, + provenance=provenance_text, + validation_path=validation_file, + manifest_path=manifest_file, + data_manifest_path=data_manifest_file, + ) + + +@dataclass(frozen=True, slots=True) +class _NYCAnchorEvidence: + summary: str + limitations: str + provenance: str + + +def _nyc_anchor_status( + anchor_path: str | Path | None, + manifest_path: str | Path | None, +) -> _NYCAnchorEvidence | None: + """Validate the NYC descriptive simulation anchor and its full source hash chain.""" + + if anchor_path is None and manifest_path is None: + return None + if anchor_path is None or manifest_path is None: + raise ValueError("NYC simulation anchor requires both anchor and manifest") + anchor_file = Path(anchor_path) + manifest_file = Path(manifest_path) + anchor = _load_json_object(anchor_file, "NYC simulation anchor") + manifest = _load_json_object(manifest_file, "NYC simulation anchor manifest") + if ( + anchor.get("schema_version") != "1.0.0" + or anchor.get("evidence_label") != "semi_synthetic_descriptive_anchor" + or anchor.get("causal_claim") is not False + or anchor.get("status") + != "descriptive_control_path_anchor_validated_not_fitted_structural_model" + ): + raise ValueError("NYC simulation anchor has an incompatible evidence contract") + metadata = manifest.get("metadata") + if ( + not isinstance(metadata, dict) + or metadata.get("evidence_label") != "semi_synthetic_descriptive_anchor" + or metadata.get("causal_claim") is not False + or metadata.get("status") != anchor.get("status") + ): + raise ValueError("NYC simulation anchor manifest metadata is incompatible") + manifest_root = _manifest_root_for_artifact( + manifest, anchor_file, "NYC simulation anchor" + ) + validated = _validate_manifest_files( + manifest, manifest_root, "NYC simulation anchor" + ) + if anchor_file.resolve() not in validated: + raise ValueError("NYC simulation anchor is not covered by its manifest") + calibration_candidates = [ + path + for path, entry in validated.items() + if entry.get("sha256") == metadata.get("calibration_sha256") + ] + calibration_manifest_candidates = [ + path + for path, entry in validated.items() + if entry.get("sha256") == metadata.get("calibration_manifest_sha256") + ] + simulation_config_candidates = [ + path + for path, entry in validated.items() + if entry.get("sha256") == metadata.get("simulation_config_sha256") + ] + if ( + len(calibration_candidates) != 1 + or len(calibration_manifest_candidates) != 1 + or len(simulation_config_candidates) != 1 + ): + raise ValueError("NYC simulation anchor manifest has incomplete declared inputs") + calibration_file = calibration_candidates[0] + calibration_manifest_file = calibration_manifest_candidates[0] + simulation_config_file = simulation_config_candidates[0] + if ( + metadata.get("calibration_sha256") != sha256_file(calibration_file) + or metadata.get("calibration_manifest_sha256") + != sha256_file(calibration_manifest_file) + or metadata.get("simulation_config_sha256") + != sha256_file(simulation_config_file) + ): + raise ValueError("NYC simulation anchor declared input hashes disagree") + recomputed_integrity = validate_nyc_simulation_anchor_integrity( + calibration_file, + project_root=manifest_root, + manifest_path=calibration_manifest_file, + ) + integrity = anchor.get("integrity") + if ( + not isinstance(integrity, dict) + or integrity != recomputed_integrity + or integrity.get("all_valid") is not True + or integrity.get("hashes_recomputed") is not True + or metadata.get("source_data_manifest_sha256") + != integrity.get("source_data_manifest_sha256") + ): + raise ValueError("NYC simulation anchor integrity is stale or inconsistent") + + control = anchor.get("control_path_scale_validation") + field_provenance = anchor.get("field_provenance") + causal_assumptions = anchor.get("causal_parameter_assumptions") + source_scope = anchor.get("source_scope") + target_panel = anchor.get("target_panel") + simulation_config = anchor.get("simulation_config") + warnings = anchor.get("warnings") + if not all( + isinstance(value, dict) + for value in ( + control, + field_provenance, + causal_assumptions, + source_scope, + target_panel, + simulation_config, + ) + ): + raise ValueError("NYC simulation anchor is missing required sections") + assert isinstance(control, dict) + assert isinstance(field_provenance, dict) + assert isinstance(causal_assumptions, dict) + assert isinstance(source_scope, dict) + assert isinstance(target_panel, dict) + assert isinstance(simulation_config, dict) + if ( + control.get("evidence_label") != "semi_synthetic_descriptive_anchor" + or control.get("causal_claim") is not False + or control.get("broad_moment_match_passed") is not True + or field_provenance.get("partition_complete") is not True + or causal_assumptions.get("status") + != "explicit_assumptions_not_estimated_from_nyc_trip_records" + or causal_assumptions.get("calibration_embedded_template_assumptions_used") + is not False + or source_scope.get("evidence_label") != "descriptive_real_data" + or source_scope.get("causal_claim") is not False + or not isinstance(warnings, list) + or not warnings + ): + raise ValueError("NYC simulation anchor fails the noncausal provenance gate") + explicit_assumptions = field_provenance.get("explicit_assumptions") + if not isinstance(explicit_assumptions, dict): + raise ValueError("NYC simulation anchor explicit assumptions are missing") + template_config = load_simulation_config(simulation_config_file).to_dict() + for field in CAUSAL_ASSUMPTION_FIELDS: + record = explicit_assumptions.get(field) + if ( + not isinstance(record, dict) + or field not in simulation_config + or simulation_config[field] != template_config[field] + or record.get("value") != simulation_config[field] + or record.get("evidence_label") != "explicit_assumption" + ): + raise ValueError( + "NYC simulation anchor causal assumptions disagree with the declared template" + ) + numeric_keys = ( + "target_mean_published_completed_trips_per_zone_hour", + "achieved_simulated_control_completed_trips", + "target_mean_nonnegative_request_to_pickup_minutes", + "achieved_simulated_control_mean_wait_minutes", + "target_between_zone_variance_share", + "achieved_between_zone_variance_share", + "target_between_hour_of_day_variance_share", + "achieved_between_hour_of_day_variance_share", + "variance_share_absolute_tolerance", + ) + numeric = {key: float(control.get(key, np.nan)) for key in numeric_keys} + if not np.isfinite(list(numeric.values())).all(): + raise ValueError("NYC simulation anchor validation values must be finite") + tolerance = numeric["variance_share_absolute_tolerance"] + if ( + tolerance <= 0 + or not np.isclose( + numeric["target_mean_published_completed_trips_per_zone_hour"], + numeric["achieved_simulated_control_completed_trips"], + atol=1e-8, + ) + or not np.isclose( + numeric["target_mean_nonnegative_request_to_pickup_minutes"], + numeric["achieved_simulated_control_mean_wait_minutes"], + atol=1e-8, + ) + or abs( + numeric["target_between_zone_variance_share"] + - numeric["achieved_between_zone_variance_share"] + ) + > tolerance + or abs( + numeric["target_between_hour_of_day_variance_share"] + - numeric["achieved_between_hour_of_day_variance_share"] + ) + > tolerance + ): + raise ValueError("NYC simulation anchor broad-moment validation is inconsistent") + + observed = target_panel.get("observed") + simulation = target_panel.get("simulation") + scaling = target_panel.get("sample_scaling") + if not all(isinstance(value, dict) for value in (observed, simulation, scaling)): + raise ValueError("NYC simulation anchor panel geometry is malformed") + assert isinstance(observed, dict) + assert isinstance(simulation, dict) + assert isinstance(scaling, dict) + for label, geometry in (("observed", observed), ("simulation", simulation)): + if any( + isinstance(geometry.get(key), bool) + or not isinstance(geometry.get(key), int) + or int(geometry[key]) < 1 + for key in ("n_zones", "n_periods", "panel_cells") + ): + raise ValueError(f"NYC simulation anchor {label} geometry is invalid") + if geometry["panel_cells"] != geometry["n_zones"] * geometry["n_periods"]: + raise ValueError(f"NYC simulation anchor {label} geometry does not conserve") + if scaling.get("selection_performed") is not False: + raise ValueError("NYC simulation anchor cannot claim an empirical sample selection") + + summary = ( + f"The validated NYC anchor uses {source_scope['published_completed_trips']:,} " + "published January 2024 completed trips and a complete " + f"{observed['n_zones']}-zone × {observed['n_periods']}-hour panel to initialize a " + f"{simulation['n_zones']}-zone × {simulation['n_periods']}-period semi-synthetic " + "market. Its deterministic control path matches mean completed trips and mean " + "request-to-pickup time, and matches the descriptive between-zone and hour-of-day " + f"variance shares within {tolerance:.3f}. Treatment response, supply response, " + "spillovers, persistence, substitution, and welfare remain explicit assumptions, " + "not NYC estimates. This is a separate initialization proposal; the default design " + "benchmark retains its documented offline vertical-slice calibration, so its causal " + "magnitudes are not NYC effect estimates." + ) + limitations = "\n".join(f"- {item}" for item in warnings) + provenance = "\n".join( + [ + f"- NYC simulation anchor SHA-256: `{sha256_file(anchor_file)}`", + f"- NYC simulation anchor manifest SHA-256: `{sha256_file(manifest_file)}`", + f"- NYC calibration SHA-256: `{sha256_file(calibration_file)}`", + f"- NYC anchor assumption template SHA-256: `{sha256_file(simulation_config_file)}`", + "- NYC calibration source-data manifest SHA-256: " + f"`{integrity['source_data_manifest_sha256']}`", + ] + ) + return _NYCAnchorEvidence( + summary=summary, + limitations=limitations, + provenance=provenance, + ) + + +def _recommendation_status( + benchmark: pd.DataFrame, + target_estimand: str, +) -> tuple[pd.Series | None, str]: + try: + recommendation = choose_recommendation(benchmark, target_estimand) + except ValueError as exc: + return None, ( + "No robust design recommendation is issued. " + f"The generated selection gate reports: {exc}." + ) + return recommendation, ( + f"Conditional on all declared simulator scenarios, the selection rule chooses " + f"**{recommendation['design']}** with **{recommendation['estimator']}**. " + "This is a semi-synthetic design result, not a production-effect forecast." + ) + + +def _policy_table(policy_path: str | Path | None) -> tuple[str, str]: + if policy_path is None or not Path(policy_path).is_file(): + return ( + "Policy results were not supplied; no allocation recommendation is issued.", + "No policy artifact was available.", + ) + policy = pd.read_csv(policy_path) + required = { + "policy", + "expected_incremental_outcome", + "incremental_outcome_se", + "incremental_outcome_p10", + "budget_spent", + "budget_efficiency", + "budget_feasible", + "evaluation_complete", + "policy_eligible", + "decision_instability", + "training_market_seeds", + "holdout_market_seeds", + "training_signal", + "evaluation_engine", + "planning_cost_basis", + "target_estimand", + "evidence_type", + "training_markets", + "holdout_markets", + "target_population_id", + "n_zones", + "n_periods", + "weighting", + "simulation_config", + "policy_config", + } + missing = required.difference(policy.columns) + if missing: + raise ValueError(f"policy results missing columns: {sorted(missing)}") + if not policy["evidence_type"].astype(str).str.startswith("semi_synthetic").all(): + raise ValueError("policy rows must be labeled semi-synthetic") + if not policy["training_signal"].astype(str).str.contains("no structural truth").all(): + raise ValueError("policy artifact does not establish truth-free training") + if not policy["evaluation_engine"].astype(str).str.contains("simulator rerun").all(): + raise ValueError("policy artifact does not establish full simulator evaluation") + if not policy["planning_cost_basis"].astype(str).str.contains( + "no treated holdout" + ).all(): + raise ValueError("policy artifact uses an unsafe or undocumented holdout cost basis") + _validate_policy_provenance(policy) + for column in ("budget_feasible", "evaluation_complete", "policy_eligible"): + policy[column] = _strict_boolean(policy[column], column) + columns = [ + column + for column in ( + "policy", + "expected_incremental_outcome", + "incremental_outcome_se", + "incremental_outcome_p10", + "incremental_outcome_vs_random", + "paired_difference_se_vs_random", + "incremental_welfare", + "budget_spent", + "budget_efficiency", + "mean_model_instability", + "decision_instability", + "budget_feasible", + "evaluation_complete", + "holdout_markets", + ) + if column in policy + ] + table = markdown_table( + policy.sort_values("expected_incremental_outcome", ascending=False), + columns, + ) + eligible = policy.loc[ + policy["budget_feasible"] + & policy["evaluation_complete"] + & policy["policy_eligible"] + & np.isfinite(policy["expected_incremental_outcome"]) + & np.isfinite(policy["incremental_outcome_p10"]) + ].copy() + if eligible.empty: + summary = "No policy passes the budget, holdout-completeness, and stability gates." + else: + ordered = eligible.sort_values( + [ + "incremental_outcome_p10", + "decision_instability", + "expected_incremental_outcome", + "policy", + ], + ascending=[False, True, False, True], + ) + best = ordered.iloc[0] + unique_winner = True + if len(ordered) > 1: + runner_up = ordered.iloc[1] + p10_margin = float( + best["incremental_outcome_p10"] + - runner_up["incremental_outcome_p10"] + ) + uncertainty_buffer = 1.96 * float( + np.hypot( + best["incremental_outcome_se"], + runner_up["incremental_outcome_se"], + ) + ) + unique_winner = p10_margin > uncertainty_buffer + if unique_winner: + summary = ( + "The predeclared conservative policy rule—maximize the holdout " + "10th-percentile incremental trips, require separation beyond a 1.96-SE " + "two-policy uncertainty buffer, then minimize decision instability—chooses " + f"**{best['policy']}**. Its generated mean is " + f"{float(best['expected_incremental_outcome']):.4f} trips per holdout market " + f"(SE {float(best['incremental_outcome_se']):.4f}; p10 " + f"{float(best['incremental_outcome_p10']):.4f}). This is conditional on the " + "modeled marketplace and fixed budget." + ) + else: + summary = ( + "No unique policy winner is issued. The top two holdout p10 values are not " + "separated by the predeclared 1.96-SE uncertainty buffer, so their ordering " + "is treated as a tie; prefer the simpler eligible policy or collect more " + "holdout markets." + ) + return table, summary + + +@dataclass(frozen=True, slots=True) +class _TreatmentVersionPolicyEvidence: + summary: str + table: str + provenance: str + + +def _treatment_version_policy_status( + summary_path: str | Path | None, + manifest_path: str | Path | None, +) -> _TreatmentVersionPolicyEvidence | None: + """Validate paired rider/driver/bundled policy sensitivity evidence.""" + + if summary_path is None and manifest_path is None: + return None + if summary_path is None or manifest_path is None: + raise ValueError( + "treatment-version policy evidence requires both summary and manifest" + ) + summary_file = Path(summary_path) + manifest_file = Path(manifest_path) + if not summary_file.is_file(): + raise FileNotFoundError(f"treatment-version policy summary is required: {summary_file}") + manifest = _load_json_object( + manifest_file, "treatment-version policy manifest" + ) + metadata = manifest.get("metadata") + expected_versions = {"rider_discount", "driver_incentive", "bundled"} + pairing_contract = ( + "common training/holdout market seeds across intervention versions" + ) + if not isinstance(metadata, dict): + raise ValueError("treatment-version policy manifest metadata is missing") + declared_versions = metadata.get("treatment_versions") + if ( + metadata.get("evidence_type") + != "semi_synthetic_treatment_version_policy_sensitivity" + or not isinstance(declared_versions, list) + or not all(isinstance(value, str) for value in declared_versions) + or set(declared_versions) != expected_versions + or metadata.get("version_pairing") != pairing_contract + ): + raise ValueError("treatment-version policy manifest metadata is incompatible") + manifest_root = _manifest_root_for_artifact( + manifest, summary_file, "treatment-version policy" + ) + validated_files = _validate_manifest_files( + manifest, manifest_root, "treatment-version policy" + ) + if summary_file.resolve() not in validated_files: + raise ValueError( + "treatment-version policy summary is not covered by its manifest" + ) + ledger_candidates = [ + path + for path in validated_files + if path.name == "treatment_version_policy_market_ledger.csv" + ] + if len(ledger_candidates) != 1: + raise ValueError( + "treatment-version policy manifest must cover exactly one market ledger" + ) + + policy = pd.read_csv(summary_file) + required = { + "policy", + "treatment_version", + "version_pairing", + "version_evidence_scope", + "expected_incremental_outcome", + "incremental_outcome_se", + "incremental_outcome_p10", + "budget_spent", + "budget_feasible", + "evaluation_complete", + "policy_eligible", + "training_market_seeds", + "holdout_market_seeds", + "training_markets", + "holdout_markets", + "target_estimand", + "target_population_id", + "n_zones", + "n_periods", + "weighting", + "simulation_config", + "policy_config", + "evidence_type", + } + missing = required.difference(policy.columns) + if missing or policy.empty: + raise ValueError( + f"treatment-version policy summary missing columns: {sorted(missing)}" + ) + if set(policy["treatment_version"].astype(str)) != expected_versions: + raise ValueError("treatment-version policy summary has incomplete versions") + if not policy["evidence_type"].eq("semi_synthetic_policy_holdout").all(): + raise ValueError("treatment-version policy rows have an incompatible evidence type") + if not policy["version_pairing"].eq(pairing_contract).all(): + raise ValueError("treatment-version policy rows do not establish paired seeds") + if not policy["version_evidence_scope"].astype(str).str.contains( + "not an empirical dose response", regex=False + ).all(): + raise ValueError("treatment-version policy evidence scope is unsafe") + for column in ("budget_feasible", "evaluation_complete", "policy_eligible"): + policy[column] = _strict_boolean(policy[column], column) + numeric_columns = [ + "expected_incremental_outcome", + "incremental_outcome_se", + "incremental_outcome_p10", + "budget_spent", + ] + numeric_values = policy[numeric_columns].apply(pd.to_numeric, errors="coerce") + if not np.isfinite(numeric_values.to_numpy(dtype=float)).all(): + raise ValueError("treatment-version policy summary has non-finite decision values") + + common_training_seeds: set[int] | None = None + common_holdout_seeds: set[int] | None = None + for version, group in policy.groupby("treatment_version", sort=True): + training_seeds, holdout_seeds = _validate_policy_provenance(group) + try: + configs = [json.loads(value) for value in group["simulation_config"]] + except (TypeError, json.JSONDecodeError) as exc: + raise ValueError( + "treatment-version policy simulation config is malformed" + ) from exc + if any( + not isinstance(config, dict) + or config.get("treatment_version") != version + for config in configs + ): + raise ValueError( + "treatment-version policy rows disagree with their simulation configs" + ) + if common_training_seeds is None: + common_training_seeds = training_seeds + common_holdout_seeds = holdout_seeds + elif ( + training_seeds != common_training_seeds + or holdout_seeds != common_holdout_seeds + ): + raise ValueError( + "treatment-version policy versions do not share market seeds" + ) + assert common_training_seeds is not None + assert common_holdout_seeds is not None + if ( + metadata.get("training_markets") not in (None, len(common_training_seeds)) + or metadata.get("holdout_markets") not in (None, len(common_holdout_seeds)) + ): + raise ValueError( + "treatment-version policy manifest market counts disagree with the summary" + ) + + ledger = pd.read_csv(ledger_candidates[0]) + ledger_required = { + "policy", + "treatment_version", + "version_pairing", + "holdout_market_seed", + "evidence_type", + } + missing_ledger = ledger_required.difference(ledger.columns) + if missing_ledger or ledger.empty: + raise ValueError( + f"treatment-version policy ledger missing columns: {sorted(missing_ledger)}" + ) + if ( + set(ledger["treatment_version"].astype(str)) != expected_versions + or not ledger["version_pairing"].eq(pairing_contract).all() + or not ledger["evidence_type"].eq( + "semi_synthetic_policy_holdout_market" + ).all() + ): + raise ValueError("treatment-version policy ledger has incompatible scope") + expected_policies = set(policy["policy"].astype(str)) + for _keys, group in ledger.groupby( + ["treatment_version", "policy"], sort=True + ): + if ( + set(group["holdout_market_seed"].astype(int)) != common_holdout_seeds + or len(group) != len(common_holdout_seeds) + ): + raise ValueError( + "treatment-version policy ledger has incomplete holdout pairing" + ) + if set(ledger["policy"].astype(str)) != expected_policies: + raise ValueError("treatment-version policy ledger has incomplete policies") + + display = policy.sort_values(["treatment_version", "policy"]) + table = markdown_table( + display, + [ + "treatment_version", + "policy", + "expected_incremental_outcome", + "incremental_outcome_se", + "incremental_outcome_p10", + "budget_spent", + "budget_feasible", + "evaluation_complete", + "policy_eligible", + ], + ) + summary = ( + f"A separate paired sensitivity evaluates " + f"{_counted(len(expected_policies), 'policy', 'policies')} " + "under rider-discount, driver-incentive, and bundled simulator response functions. " + f"Every version reuses the same {len(common_training_seeds)} training and " + f"{len(common_holdout_seeds)} holdout market seeds, while fitting its own learner. " + "The table is a semi-synthetic response-function sensitivity—not an empirical " + "dose response, treatment comparison, or live-market ROI estimate—and it does not " + "replace the primary bundled-policy decision gate." + ) + provenance = "\n".join( + [ + f"- Treatment-version policy summary SHA-256: `{sha256_file(summary_file)}`", + f"- Treatment-version policy manifest SHA-256: `{sha256_file(manifest_file)}`", + f"- Treatment-version policy ledger SHA-256: `{sha256_file(ledger_candidates[0])}`", + ] + ) + return _TreatmentVersionPolicyEvidence( + summary=summary, + table=table, + provenance=provenance, + ) + + +@dataclass(frozen=True, slots=True) +class _InterferenceEvidence: + summary: str + table: str + provenance: str + + +def _interference_status( + summary_path: str | Path | None, + manifest_path: str | Path | None, +) -> _InterferenceEvidence | None: + """Validate the known-truth mapped-exposure benchmark fail closed.""" + + if summary_path is None and manifest_path is None: + return None + if summary_path is None or manifest_path is None: + raise ValueError("interference evidence requires both summary and manifest") + summary_file = Path(summary_path) + manifest_file = Path(manifest_path) + manifest = _load_json_object(manifest_file, "interference benchmark manifest") + metadata = manifest.get("metadata") + if ( + not isinstance(metadata, dict) + or metadata.get("evidence_type") + != "semi_synthetic_exposure_mapped_known_truth_benchmark" + or metadata.get("controlled_exposure_not_market_total") is not True + or not isinstance(metadata.get("benchmark_config"), dict) + or not isinstance(metadata.get("known_estimands"), dict) + ): + raise ValueError("interference benchmark manifest metadata is incompatible") + manifest_root = _manifest_root_for_artifact( + manifest, summary_file, "interference benchmark" + ) + validated = _validate_manifest_files( + manifest, manifest_root, "interference benchmark" + ) + if summary_file.resolve() not in validated: + raise ValueError("interference summary is not covered by its manifest") + expected_names = { + "interference_records.csv", + "interference_summary.csv", + "interference_failures.csv", + "interference_fit_ledger.csv", + "interference_metadata.json", + } + by_name = {path.name: path for path in validated} + if set(by_name) != expected_names: + raise ValueError("interference manifest has an unexpected file set") + + config = metadata["benchmark_config"] + replications = config.get("replications") + if isinstance(replications, bool) or not isinstance(replications, int) or replications < 2: + raise ValueError("interference benchmark replication count is invalid") + benchmark_metadata = _load_json_object( + by_name["interference_metadata.json"], "interference benchmark metadata" + ) + if ( + benchmark_metadata.get("evidence_type") + != "semi_synthetic_exposure_mapped_known_truth_benchmark" + or benchmark_metadata.get("config") != config + or benchmark_metadata.get("known_estimands") != metadata["known_estimands"] + ): + raise ValueError("interference benchmark metadata and manifest disagree") + + summary_frame = pd.read_csv(summary_file) + required = { + "estimator", + "target_estimand", + "truth", + "mean_estimate", + "bias", + "rmse", + "coverage", + "power", + "identified", + "inference_valid_for_target", + "fit_complete", + "decision_eligible", + "successful_fits", + "comparison_status", + "evidence_type", + "diagnostic_mean_gap_to_market_total", + } + missing = required.difference(summary_frame.columns) + if missing or summary_frame.empty: + raise ValueError(f"interference summary missing columns: {sorted(missing)}") + for column in ( + "identified", + "inference_valid_for_target", + "fit_complete", + "decision_eligible", + ): + summary_frame[column] = _strict_boolean(summary_frame[column], column) + mapped_targets = { + "controlled_zone_direct_effect", + "spillover_effect", + "controlled_history_exposure_response", + } + mapped = summary_frame.loc[summary_frame["target_estimand"].isin(mapped_targets)].copy() + naive = summary_frame.loc[ + summary_frame["estimator"].eq("naive_assignment_cluster_regression") + ].copy() + if set(mapped["target_estimand"]) != mapped_targets or len(mapped) != 3 or len(naive) != 1: + raise ValueError("interference summary has incomplete controlled or naive targets") + mapped_numeric = mapped[ + ["truth", "mean_estimate", "bias", "rmse", "coverage", "power"] + ].apply(pd.to_numeric, errors="coerce") + if not np.isfinite(mapped_numeric.to_numpy(dtype=float)).all(): + raise ValueError("interference mapped recovery metrics must be finite") + if not ( + mapped["identified"].all() + and mapped["inference_valid_for_target"].all() + and mapped["fit_complete"].all() + and mapped["decision_eligible"].all() + and mapped["successful_fits"].eq(replications).all() + and mapped["evidence_type"].eq( + "semi_synthetic_exposure_mapped_known_truth_monte_carlo" + ).all() + and mapped["coverage"].between(0.0, 1.0).all() + and mapped["power"].between(0.0, 1.0).all() + ): + raise ValueError("interference mapped recovery rows fail the evidence gate") + known_estimands = metadata["known_estimands"] + for row in mapped.itertuples(index=False): + expected = known_estimands.get(row.target_estimand) + if not isinstance(expected, (int, float)) or not np.isclose(row.truth, expected): + raise ValueError("interference summary truth disagrees with metadata") + withheld = naive[["bias", "rmse", "coverage", "power"]].apply( + pd.to_numeric, errors="coerce" + ) + diagnostic = pd.to_numeric( + naive["diagnostic_mean_gap_to_market_total"], errors="coerce" + ) + if ( + bool(naive["identified"].iloc[0]) + or bool(naive["decision_eligible"].iloc[0]) + or not withheld.isna().all().all() + or not np.isfinite(diagnostic.to_numpy(dtype=float)).all() + or naive["comparison_status"].iloc[0] != "target_mismatch" + ): + raise ValueError("interference naive target-mismatch row is unsafe") + + ledger = pd.read_csv(by_name["interference_fit_ledger.csv"]) + if len(ledger) != 4: + raise ValueError("interference fit ledger must contain four declared targets") + for column in ("identified", "fit_complete", "decision_eligible"): + ledger[column] = _strict_boolean(ledger[column], column) + if ( + not ledger["fit_complete"].all() + or not ledger["successful_fits"].eq(replications).all() + or int(ledger["failed_fits"].sum()) != 0 + or int(ledger["attempted_fits"].sum()) != replications * 4 + ): + raise ValueError("interference fit ledger is incomplete") + records = pd.read_csv(by_name["interference_records.csv"]) + if len(records) != replications * 4: + raise ValueError("interference records do not match the declared fit plan") + failures = pd.read_csv(by_name["interference_failures.csv"]) + if not failures.empty: + raise ValueError("interference benchmark contains failed fits") + + table = markdown_table( + summary_frame.sort_values(["identified", "target_estimand"], ascending=[False, True]), + [ + "estimator", + "target_estimand", + "truth", + "mean_estimate", + "bias", + "rmse", + "coverage", + "power", + "identified", + "inference_valid_for_target", + "decision_eligible", + "diagnostic_mean_gap_to_market_total", + ], + ) + naive_gap = float(diagnostic.iloc[0]) + summary = ( + f"A separate {replications}-replication known-truth benchmark uses " + "two-stage geographic saturation, a predeclared neighbor map, and exact treatment " + "history. The mapped cluster regression reports controlled own, neighbor, and " + "history effects with target-aligned bias, RMSE, coverage, and power. The naive " + f"saturation coefficient differs from the full-policy truth by {naive_gap:.4f}; " + "because that coefficient omits mapped exposures, its market-total bias, RMSE, " + "coverage, and power are deliberately withheld." + ) + provenance = "\n".join( + [ + f"- Interference summary SHA-256: `{sha256_file(summary_file)}`", + f"- Interference manifest SHA-256: `{sha256_file(manifest_file)}`", + f"- Interference records SHA-256: `{sha256_file(by_name['interference_records.csv'])}`", + f"- Interference fit ledger SHA-256: `{sha256_file(by_name['interference_fit_ledger.csv'])}`", + ] + ) + return _InterferenceEvidence(summary=summary, table=table, provenance=provenance) + + +@dataclass(frozen=True, slots=True) +class _NYCInformedBenchmarkEvidence: + summary: str + table: str + limitations: str + provenance: str + + +def _nyc_informed_benchmark_status( + manifest_path: str | Path | None, +) -> _NYCInformedBenchmarkEvidence | None: + """Validate the NYC-informed known-truth benchmark and its anchor lineage.""" + + bundle = _manifest_bundle(manifest_path, "NYC-informed benchmark") + if bundle is None: + return None + _require_manifest_evidence( + bundle, NYC_BENCHMARK_EVIDENCE_TYPE, "NYC-informed benchmark" + ) + if ( + bundle.payload.get("evidence_type") != NYC_BENCHMARK_EVIDENCE_TYPE + or bundle.payload.get("causal_claim") is not False + or bundle.payload.get("causal_claim_from_nyc_data") is not False + or bundle.payload.get("simulator_known_truth") is not True + or bundle.payload.get("bundle_valid") is not True + or bundle.payload.get("portable_paths") is not True + ): + raise ValueError("NYC-informed benchmark manifest metadata is incompatible") + metadata_path, metadata = _unique_json_object( + bundle, + lambda value: value.get("evidence_type") == NYC_BENCHMARK_EVIDENCE_TYPE + and "target_gates" in value, + "NYC-informed benchmark metadata", + ) + if ( + metadata.get("schema_version") != NYC_BENCHMARK_SCHEMA_VERSION + or metadata.get("nyc_empirical_causal_effect") is not False + or metadata.get("simulator_known_truth") is not True + or metadata.get("known_truth_estimand") != "market_total_effect" + or "not an NYC causal estimate" not in str(metadata.get("known_truth_scope", "")) + ): + raise ValueError("NYC-informed benchmark metadata has an unsafe evidence contract") + limitations = _required_string_list( + metadata.get("limitations"), "NYC-informed benchmark limitations" + ) + gates = metadata.get("target_gates") + if ( + not isinstance(gates, dict) + or not gates + or gates.get("all_passed") is not True + or any(value is not True for value in gates.values()) + ): + raise ValueError("NYC-informed benchmark target gates did not all pass") + config = metadata.get("benchmark_config") + if not isinstance(config, dict): + raise ValueError("NYC-informed benchmark configuration is missing") + replications = config.get("replications") + if isinstance(replications, bool) or not isinstance(replications, int) or replications < 2: + raise ValueError("NYC-informed benchmark replication count is invalid") + scenarios = metadata.get("scenario_causal_provenance") + if not isinstance(scenarios, dict) or not scenarios: + raise ValueError("NYC-informed benchmark scenario provenance is missing") + for value in scenarios.values(): + if ( + not isinstance(value, dict) + or not isinstance(value.get("causal_overrides"), dict) + or "none is an NYC causal estimate" + not in str(value.get("interpretation", "")) + ): + raise ValueError("NYC-informed benchmark scenario provenance is unsafe") + + anchor = metadata.get("anchor") + hashes = anchor.get("hashes") if isinstance(anchor, dict) else None + if ( + not isinstance(anchor, dict) + or anchor.get("evidence_label") != "semi_synthetic_descriptive_anchor" + or anchor.get("exact_reconstruction_passed") is not True + or not isinstance(hashes, dict) + ): + raise ValueError("NYC-informed benchmark anchor provenance is incomplete") + anchor_file = _file_with_declared_hash( + bundle, hashes.get("anchor_sha256"), "NYC-informed benchmark anchor hash" + ) + anchor_manifest_file = _file_with_declared_hash( + bundle, + hashes.get("anchor_manifest_sha256"), + "NYC-informed benchmark anchor-manifest hash", + ) + _nyc_anchor_status(anchor_file, anchor_manifest_file) + + summary_path, summary = _unique_csv( + bundle, + { + "scenario", + "design", + "estimator", + "target_estimand", + "mean_estimate", + "bias", + "rmse", + "coverage", + "power", + "fit_complete", + "inference_valid", + "nyc_empirical_causal_effect", + "simulator_known_truth", + "target_gate_all_passed", + }, + "NYC-informed benchmark summary", + ) + records_path, records = _unique_csv( + bundle, + { + "scenario", + "design", + "estimator", + "replication", + "estimate", + "std_error", + "truth", + "nyc_empirical_causal_effect", + "simulator_known_truth", + "target_gate_all_passed", + }, + "NYC-informed benchmark records", + ) + ledger_path, ledger = _unique_csv( + bundle, + { + "scenario", + "design", + "estimator", + "attempted_fits", + "successful_fits", + "failed_fits", + "fit_complete", + "applicable", + "nyc_empirical_causal_effect", + "target_gate_all_passed", + }, + "NYC-informed benchmark fit ledger", + excluded_columns={"mean_estimate"}, + ) + selected_paths = {summary_path, records_path, ledger_path} + failure_candidates = [ + path + for path in bundle.files + if path.suffix.lower() == ".csv" + and path not in selected_paths + and { + "evidence_type", + "nyc_empirical_causal_effect", + "target_gate_all_passed", + }.issubset(_csv_header(path, "NYC-informed benchmark failures")) + ] + if len(failure_candidates) != 1: + raise ValueError( + "NYC-informed benchmark manifest must identify exactly one failures CSV" + ) + failures_path = failure_candidates[0] + failures = pd.read_csv(failures_path) + if summary.empty or records.empty or ledger.empty or not failures.empty: + raise ValueError("NYC-informed benchmark outputs are incomplete or contain failures") + + for frame_label, frame in ( + ("summary", summary), + ("records", records), + ("fit ledger", ledger), + ): + if not frame["evidence_type"].eq(NYC_BENCHMARK_EVIDENCE_TYPE).all(): + raise ValueError(f"NYC-informed benchmark {frame_label} evidence label is invalid") + for column, expected in ( + ("nyc_empirical_causal_effect", False), + ("simulator_known_truth", True), + ("target_gate_all_passed", True), + ): + values = _strict_boolean(frame[column], column) + if not values.eq(expected).all(): + raise ValueError( + f"NYC-informed benchmark {frame_label} violates {column}" + ) + if not frame["target_estimand"].eq("market_total_effect").all(): + raise ValueError("NYC-informed benchmark target estimand changed") + for key, digest in hashes.items(): + column = f"nyc_{key}" + if column not in frame or not frame[column].eq(digest).all(): + raise ValueError("NYC-informed benchmark anchor hashes disagree") + + declared_sets = summary["declared_scenario_set"].dropna().astype(str).unique() + if len(declared_sets) != 1: + raise ValueError("NYC-informed benchmark declared scenario set is inconsistent") + try: + declared_scenarios = json.loads(declared_sets[0]) + except json.JSONDecodeError as exc: + raise ValueError("NYC-informed benchmark scenario declaration is malformed") from exc + if ( + not isinstance(declared_scenarios, list) + or set(declared_scenarios) != set(scenarios) + or set(summary["scenario"].astype(str)) != set(scenarios) + ): + raise ValueError("NYC-informed benchmark scenario coverage is incomplete") + if not pd.to_numeric(summary["replications"], errors="coerce").eq(replications).all(): + raise ValueError("NYC-informed benchmark summary replication counts disagree") + + for column in ("identified", "inference_valid", "fit_complete", "applicable"): + summary[column] = _strict_boolean(summary[column], column) + identified = summary["identified"] + valid = identified & summary["inference_valid"] + if not valid.any() or not summary.loc[summary["applicable"], "fit_complete"].all(): + raise ValueError("NYC-informed benchmark has no complete identified target cell") + identified_metrics = summary.loc[identified, ["truth", "bias", "rmse"]].apply( + pd.to_numeric, errors="coerce" + ) + valid_inference = summary.loc[valid, ["coverage", "power"]].apply( + pd.to_numeric, errors="coerce" + ) + if ( + not np.isfinite(identified_metrics.to_numpy(dtype=float)).all() + or not np.isfinite(valid_inference.to_numpy(dtype=float)).all() + or not ((valid_inference >= 0.0) & (valid_inference <= 1.0)).all().all() + or not summary.loc[ + ~identified, ["bias", "rmse", "coverage", "power"] + ].isna().all().all() + ): + raise ValueError("NYC-informed benchmark recovery metrics violate target alignment") + if not np.isfinite(pd.to_numeric(records["truth"], errors="coerce")).all(): + raise ValueError("NYC-informed benchmark record truth is non-finite") + for column in ("fit_complete", "applicable"): + ledger[column] = _strict_boolean(ledger[column], column) + applicable_ledger = ledger.loc[ledger["applicable"]] + if ( + not applicable_ledger["fit_complete"].all() + or not pd.to_numeric( + applicable_ledger["attempted_fits"], errors="coerce" + ).eq(replications).all() + or not pd.to_numeric( + applicable_ledger["successful_fits"], errors="coerce" + ).eq(replications).all() + or pd.to_numeric(ledger["failed_fits"], errors="coerce").sum() != 0 + or len(records) != int(pd.to_numeric(summary["successful_fits"]).sum()) + ): + raise ValueError("NYC-informed benchmark fit plan is incomplete") + + table = markdown_table( + summary.sort_values(["scenario", "design", "estimator"]), + [ + "scenario", + "design", + "estimator", + "spillover_strength", + "persistence", + "truth", + "mean_estimate", + "bias", + "rmse", + "coverage", + "power", + "identified", + "inference_valid", + "fit_complete", + ], + ) + summary_text = ( + f"The validated NYC-informed benchmark uses the descriptive NYC anchor to set " + f"scale and heterogeneity for {config.get('n_zones')} zones × " + f"{config.get('n_periods')} periods. It evaluates " + f"{_counted(len(scenarios), 'predeclared scenario')} with {replications} Monte " + f"Carlo replications; {int(valid.sum())} summary cells pass both identification " + "and inference gates. Every reported truth is a structural simulator " + "counterfactual under explicit assumptions—not a treatment effect estimated " + "from NYC trips." + ) + provenance = "\n".join( + [ + f"- NYC-informed benchmark manifest SHA-256: `{sha256_file(bundle.path)}`", + f"- NYC-informed benchmark metadata SHA-256: `{sha256_file(metadata_path)}`", + f"- NYC-informed benchmark summary SHA-256: `{sha256_file(summary_path)}`", + f"- NYC-informed benchmark records SHA-256: `{sha256_file(records_path)}`", + f"- NYC-informed benchmark fit ledger SHA-256: `{sha256_file(ledger_path)}`", + f"- NYC-informed benchmark failures SHA-256: `{sha256_file(failures_path)}`", + f"- Revalidated NYC anchor SHA-256: `{hashes['anchor_sha256']}`", + f"- Revalidated NYC anchor manifest SHA-256: `{hashes['anchor_manifest_sha256']}`", + ] + ) + return _NYCInformedBenchmarkEvidence( + summary=summary_text, + table=table, + limitations="\n".join(f"- {item}" for item in limitations), + provenance=provenance, + ) + + +@dataclass(frozen=True, slots=True) +class _NYCGraphEvidence: + summary: str + table: str + limitations: str + provenance: str + + +def _nyc_graph_status( + manifest_path: str | Path | None, +) -> _NYCGraphEvidence | None: + """Validate mapped known-truth recovery on the descriptive NYC OD graph.""" + + bundle = _manifest_bundle(manifest_path, "NYC graph benchmark") + if bundle is None: + return None + _require_manifest_evidence(bundle, NYC_GRAPH_EVIDENCE_TYPE, "NYC graph benchmark") + if ( + bundle.payload.get("evidence_type") != NYC_GRAPH_EVIDENCE_TYPE + or bundle.payload.get("causal_claim") is not False + or bundle.payload.get("causal_claim_from_nyc_data") is not False + or bundle.payload.get("input_graph_evidence_label") != "descriptive_real_data" + or bundle.payload.get("bundle_valid") is not True + or bundle.payload.get("portable_paths") is not True + ): + raise ValueError("NYC graph benchmark manifest metadata is incompatible") + metadata_path, metadata = _unique_json_object( + bundle, + lambda value: value.get("evidence_type") == NYC_GRAPH_EVIDENCE_TYPE + and "calibration_bundle" in value, + "NYC graph benchmark metadata", + ) + if ( + metadata.get("causal_claim_from_nyc_data") is not False + or metadata.get("input_graph_evidence_label") != "descriptive_real_data" + or "not spillover strength" not in str(metadata.get("graph_weight_role", "")) + or "target mismatch" not in str(metadata.get("naive_assignment_status", "")) + ): + raise ValueError("NYC graph benchmark metadata has an unsafe evidence contract") + config = metadata.get("config") + truths = metadata.get("known_estimands") + calibration = metadata.get("calibration_bundle") + subset = metadata.get("zone_subset") + if not all(isinstance(value, dict) for value in (config, truths, calibration, subset)): + raise ValueError("NYC graph benchmark metadata is incomplete") + replications = config.get("replications") + if isinstance(replications, bool) or not isinstance(replications, int) or replications < 2: + raise ValueError("NYC graph benchmark replication count is invalid") + if ( + subset.get("selection_uses_only_pre_treatment_graph_fields") is not True + or subset.get("selected_zone_count") != config.get("n_zones") + or not isinstance(subset.get("selected_zone_ids_in_order"), list) + or len(subset["selected_zone_ids_in_order"]) != config.get("n_zones") + or not _valid_sha256(subset.get("subset_raw_mapping_sha256")) + ): + raise ValueError("NYC graph benchmark zone selection provenance is invalid") + attestation = calibration.get("manifest_source_data_attestation") + if ( + not isinstance(attestation, dict) + or attestation.get("all_valid") is not True + or attestation.get("hashes_recomputed") is not True + or attestation.get("queried_files_listed") is not True + or attestation.get("scope_is_full_nyc_descriptive") is not True + or attestation.get("mismatches") != [] + or not _valid_sha256(attestation.get("sha256")) + ): + raise ValueError("NYC graph benchmark source-data attestation is invalid") + calibration_manifest_path = _file_with_declared_hash( + bundle, + calibration.get("manifest_sha256"), + "NYC graph calibration-manifest hash", + ) + mapping_path = _file_with_declared_hash( + bundle, + calibration.get("exposure_mapping_sha256"), + "NYC graph exposure-mapping hash", + ) + validated_graph = validate_nyc_graph_bundle(calibration_manifest_path.parent) + if ( + validated_graph.manifest_sha256 != calibration.get("manifest_sha256") + or validated_graph.mapping_sha256 != calibration.get("exposure_mapping_sha256") + or validated_graph.mapping_sha256 != sha256_file(mapping_path) + or dict(validated_graph.manifest["source_data_manifest"]) != dict(attestation) + ): + raise ValueError("NYC graph benchmark calibration lineage disagrees") + + summary_path, summary = _unique_csv( + bundle, + { + "estimator", + "target_estimand", + "truth", + "mean_estimate", + "bias", + "rmse", + "coverage", + "power", + "identified", + "inference_valid_for_target", + "fit_complete", + "decision_eligible", + "comparison_status", + "diagnostic_mean_gap_to_market_total", + "evidence_type", + }, + "NYC graph benchmark summary", + ) + records_path, records = _unique_csv( + bundle, + { + "replication", + "estimator", + "target_estimand", + "estimate", + "truth", + "identified", + "comparison_status", + "inference_valid_for_target", + "input_graph_evidence_label", + "evidence_type", + }, + "NYC graph benchmark records", + excluded_columns={"mean_estimate"}, + ) + ledger_path, ledger = _unique_csv( + bundle, + { + "estimator", + "target_estimand", + "identified", + "attempted_fits", + "successful_fits", + "failed_fits", + "fit_complete", + "decision_eligible", + "evidence_type", + }, + "NYC graph benchmark fit ledger", + excluded_columns={"estimate", "mean_estimate"}, + ) + failures_path, failures = _unique_csv( + bundle, + { + "replication", + "assignment_seed", + "outcome_seed", + "estimator", + "target_estimand", + "stage", + "error", + }, + "NYC graph benchmark failures", + excluded_columns={"estimate"}, + ) + if summary.empty or records.empty or ledger.empty or not failures.empty: + raise ValueError("NYC graph benchmark outputs are incomplete or contain failures") + if len(summary) != 4 or len(ledger) != 4 or len(records) != replications * 4: + raise ValueError("NYC graph benchmark does not match its declared fit plan") + for column in ( + "identified", + "inference_valid_for_target", + "fit_complete", + "decision_eligible", + ): + summary[column] = _strict_boolean(summary[column], column) + for column in ("identified", "fit_complete", "decision_eligible"): + ledger[column] = _strict_boolean(ledger[column], column) + mapped_targets = { + "controlled_zone_direct_effect", + "spillover_effect", + "controlled_history_exposure_response", + } + mapped = summary.loc[summary["target_estimand"].isin(mapped_targets)].copy() + naive = summary.loc[ + summary["estimator"].eq("nyc_graph_naive_assignment_cluster_regression") + ].copy() + if set(mapped["target_estimand"]) != mapped_targets or len(mapped) != 3 or len(naive) != 1: + raise ValueError("NYC graph benchmark controlled and naive targets are incomplete") + mapped_metrics = mapped[ + ["truth", "mean_estimate", "bias", "rmse", "coverage", "power"] + ].apply(pd.to_numeric, errors="coerce") + if ( + not np.isfinite(mapped_metrics.to_numpy(dtype=float)).all() + or not ((mapped_metrics[["coverage", "power"]] >= 0.0) & ( + mapped_metrics[["coverage", "power"]] <= 1.0 + )).all().all() + or not mapped["identified"].all() + or not mapped["inference_valid_for_target"].all() + or not mapped["fit_complete"].all() + or not mapped["decision_eligible"].all() + or not mapped["successful_fits"].eq(replications).all() + or not mapped["evidence_type"].eq( + "semi_synthetic_nyc_graph_known_truth_monte_carlo" + ).all() + ): + raise ValueError("NYC graph benchmark mapped recovery rows fail the evidence gate") + for row in mapped.itertuples(index=False): + expected = truths.get(row.target_estimand) + if not isinstance(expected, (int, float)) or not np.isclose(row.truth, expected): + raise ValueError("NYC graph benchmark truth disagrees with metadata") + withheld = naive[["bias", "rmse", "coverage", "power"]].apply( + pd.to_numeric, errors="coerce" + ) + diagnostic = pd.to_numeric( + naive["diagnostic_mean_gap_to_market_total"], errors="coerce" + ) + if ( + bool(naive["identified"].iloc[0]) + or bool(naive["decision_eligible"].iloc[0]) + or naive["comparison_status"].iloc[0] != "target_mismatch" + or naive["evidence_type"].iloc[0] + != "semi_synthetic_nyc_graph_target_mismatch_diagnostic" + or not withheld.isna().all().all() + or not np.isfinite(diagnostic.to_numpy(dtype=float)).all() + ): + raise ValueError("NYC graph naive target-mismatch metrics were not safely withheld") + if ( + not ledger["fit_complete"].all() + or int(pd.to_numeric(ledger["failed_fits"], errors="coerce").sum()) != 0 + or not pd.to_numeric(ledger["attempted_fits"], errors="coerce").eq( + replications + ).all() + or not pd.to_numeric(ledger["successful_fits"], errors="coerce").eq( + replications + ).all() + ): + raise ValueError("NYC graph benchmark fit ledger is incomplete") + mapped_records = records.loc[ + records["estimator"].eq("nyc_graph_exposure_mapped_cluster_regression") + ] + naive_records = records.loc[ + records["estimator"].eq("nyc_graph_naive_assignment_cluster_regression") + ] + if ( + len(mapped_records) != replications * 3 + or len(naive_records) != replications + or not mapped_records["evidence_type"].eq(NYC_GRAPH_EVIDENCE_TYPE).all() + or not naive_records["evidence_type"].eq( + "semi_synthetic_nyc_graph_target_mismatch_diagnostic" + ).all() + or not records["input_graph_evidence_label"].eq("descriptive_real_data").all() + ): + raise ValueError("NYC graph benchmark record evidence labels are incompatible") + + table = markdown_table( + summary.sort_values(["identified", "target_estimand"], ascending=[False, True]), + [ + "estimator", + "target_estimand", + "truth", + "mean_estimate", + "bias", + "rmse", + "coverage", + "power", + "identified", + "inference_valid_for_target", + "decision_eligible", + "diagnostic_mean_gap_to_market_total", + ], + ) + gap = float(diagnostic.iloc[0]) + summary_text = ( + f"A {replications}-replication known-truth benchmark applies two-stage saturation " + f"to {config.get('n_zones')} zones selected solely from the pre-treatment NYC " + "completed-trip OD graph. It separately recovers controlled own, mapped-neighbor, " + "and exact-history responses. The naive saturation coefficient differs from the " + f"declared market-total truth by {gap:.4f}; its market-total bias, RMSE, coverage, " + "and power are therefore withheld. NYC OD weights define exposure geometry only—" + "they are not estimated spillover strength or a causal effect." + ) + limitations = [ + str(metadata.get("graph_weight_role")), + str(metadata.get("market_total_bridge")), + "Known response coefficients are declared by the benchmark DGP and are not learned from NYC trips.", + ] + provenance = "\n".join( + [ + f"- NYC graph benchmark manifest SHA-256: `{sha256_file(bundle.path)}`", + f"- NYC graph benchmark metadata SHA-256: `{sha256_file(metadata_path)}`", + f"- NYC graph benchmark summary SHA-256: `{sha256_file(summary_path)}`", + f"- NYC graph benchmark records SHA-256: `{sha256_file(records_path)}`", + f"- NYC graph benchmark fit ledger SHA-256: `{sha256_file(ledger_path)}`", + f"- Revalidated NYC calibration manifest SHA-256: `{validated_graph.manifest_sha256}`", + f"- Revalidated NYC exposure map SHA-256: `{validated_graph.mapping_sha256}`", + ] + ) + return _NYCGraphEvidence( + summary=summary_text, + table=table, + limitations="\n".join(f"- {item}" for item in limitations), + provenance=provenance, + ) + + +@dataclass(frozen=True, slots=True) +class _EquilibriumEvidence: + summary: str + table: str + limitations: str + provenance: str + + +def _equilibrium_status( + manifest_path: str | Path | None, +) -> _EquilibriumEvidence | None: + """Validate a converged paired fixed-point equilibrium benchmark.""" + + bundle = _manifest_bundle(manifest_path, "equilibrium benchmark") + if bundle is None: + return None + _require_manifest_evidence( + bundle, EQUILIBRIUM_EVIDENCE_TYPE, "equilibrium benchmark" + ) + if ( + bundle.payload.get("evidence_type") != EQUILIBRIUM_EVIDENCE_TYPE + or bundle.payload.get("causal_scope") != EQUILIBRIUM_CAUSAL_SCOPE + or bundle.payload.get("empirical_calibration_status") + != EQUILIBRIUM_EMPIRICAL_STATUS + or bundle.payload.get("is_nyc_structural_estimate") is not False + or bundle.payload.get("portable_paths") is not True + or not isinstance(bundle.payload.get("checks"), dict) + or any(value is not True for value in bundle.payload["checks"].values()) + ): + raise ValueError("equilibrium benchmark manifest metadata is incompatible") + metadata_path, metadata = _unique_json_object( + bundle, + lambda value: value.get("evidence_type") == EQUILIBRIUM_EVIDENCE_TYPE + and "control_diagnostics" in value, + "equilibrium benchmark metadata", + ) + truth_path = metadata_path + truth = metadata.get("ground_truth") + if ( + metadata.get("schema_version") != 1 + or metadata.get("evidence_type") != EQUILIBRIUM_EVIDENCE_TYPE + or metadata.get("causal_scope") != EQUILIBRIUM_CAUSAL_SCOPE + or metadata.get("empirical_calibration_status") + != EQUILIBRIUM_EMPIRICAL_STATUS + or metadata.get("is_nyc_structural_estimate") is not False + or metadata.get("common_random_numbers") is not True + or metadata.get("ground_truth_status") + != "known_exactly_for_the_paired_model_counterfactuals" + or not isinstance(metadata.get("state_id"), str) + or not metadata.get("state_id") + ): + raise ValueError("equilibrium benchmark metadata has an unsafe evidence contract") + limitations = _required_string_list( + metadata.get("limitations"), "equilibrium benchmark limitations" + ) + equations = metadata.get("equations") + required_equations = { + "rider_demand", + "driver_supply", + "wait_fixed_point", + "service_probability", + "served_trips", + "welfare", + "uniqueness_and_convergence", + } + if not isinstance(equations, dict) or not required_equations.issubset(equations): + raise ValueError("equilibrium benchmark equations are incomplete") + + uniqueness = metadata.get("uniqueness_diagnostics") + if ( + not isinstance(uniqueness, dict) + or uniqueness.get("sufficient_condition_satisfied") is not True + ): + raise ValueError("equilibrium benchmark uniqueness condition did not pass") + contraction = uniqueness.get("contraction_bound") + effective_bound = uniqueness.get("effective_iteration_bound") + if ( + not isinstance(contraction, (int, float)) + or not isinstance(effective_bound, (int, float)) + or not np.isfinite([contraction, effective_bound]).all() + or not 0 <= float(contraction) < 1 + or not 0 <= float(effective_bound) < 1 + ): + raise ValueError("equilibrium benchmark contraction diagnostics are invalid") + + def validate_diagnostics(value: object, path_label: str) -> dict[str, Any]: + if not isinstance(value, dict): + raise ValueError(f"equilibrium benchmark {path_label} diagnostics are missing") + residual = value.get("residual_sup_norm") + tolerance = value.get("tolerance") + if ( + value.get("converged") is not True + or value.get("uniqueness_condition_satisfied") is not True + or value.get("termination_reason") != "residual_tolerance_satisfied" + or not isinstance(residual, (int, float)) + or not isinstance(tolerance, (int, float)) + or not np.isfinite([residual, tolerance]).all() + or residual < 0 + or tolerance <= 0 + or residual > tolerance + or not np.isclose(value.get("contraction_bound"), contraction) + or not np.isclose(value.get("effective_iteration_bound"), effective_bound) + ): + raise ValueError( + f"equilibrium benchmark {path_label} solution did not converge safely" + ) + return value + + control_diagnostics = validate_diagnostics( + metadata.get("control_diagnostics"), "control" + ) + treatment_diagnostics = validate_diagnostics( + metadata.get("treatment_diagnostics"), "treatment" + ) + budget = metadata.get("budget_diagnostics") + if not isinstance(budget, dict) or budget.get("budget_feasible") is not True: + raise ValueError("equilibrium benchmark budget feasibility did not pass") + budget_scale = budget.get("budget_scale") + realized_spend = budget.get("realized_treatment_spend") + declared_budget = budget.get("budget") + if ( + not isinstance(budget_scale, (int, float)) + or not isinstance(realized_spend, (int, float)) + or not np.isfinite([budget_scale, realized_spend]).all() + or not 0 <= float(budget_scale) <= 1 + or realized_spend < 0 + or not np.isclose(metadata.get("realized_budget_scale"), budget_scale) + ): + raise ValueError("equilibrium benchmark budget diagnostics are invalid") + if declared_budget is not None and ( + not isinstance(declared_budget, (int, float)) + or not np.isfinite(declared_budget) + or realized_spend > declared_budget + 1e-7 + ): + raise ValueError("equilibrium benchmark exceeds the declared budget") + + effects_path, effects = _unique_csv( + bundle, + { + "zone_id", + "control_trips", + "treatment_trips", + "trip_effect", + "control_wait_minutes", + "treatment_wait_minutes", + "wait_effect_minutes", + "control_welfare", + "treatment_welfare", + "welfare_effect", + "realized_treatment_intensity", + "state_id", + "evidence_type", + }, + "equilibrium benchmark zone effects", + ) + ledger_path, ledger = _unique_csv( + bundle, + { + "scenario", + "equilibrium_converged", + "equilibrium_residual_sup_norm", + "trips", + "treatment_spend", + "rider_surplus", + "driver_surplus", + "platform_net_revenue", + "total_welfare", + "welfare_accounting_residual", + "budget_binding", + "budget_scale", + }, + "equilibrium benchmark ledger", + ) + if effects.empty or ledger.empty or len(ledger) != 2: + raise ValueError("equilibrium benchmark effects or ledger are incomplete") + if set(ledger["scenario"].astype(str)) != {"control", "treatment"}: + raise ValueError("equilibrium benchmark ledger must contain control and treatment") + if ( + not effects["evidence_type"].eq(EQUILIBRIUM_EVIDENCE_TYPE).all() + or not effects["state_id"].eq(metadata["state_id"]).all() + ): + raise ValueError("equilibrium benchmark zone-effect provenance is incompatible") + numeric_effects = effects[ + [ + "control_trips", + "treatment_trips", + "trip_effect", + "control_wait_minutes", + "treatment_wait_minutes", + "wait_effect_minutes", + "control_welfare", + "treatment_welfare", + "welfare_effect", + "realized_treatment_intensity", + ] + ].apply(pd.to_numeric, errors="coerce") + if not np.isfinite(numeric_effects.to_numpy(dtype=float)).all(): + raise ValueError("equilibrium benchmark zone effects contain non-finite values") + if ( + not np.allclose( + numeric_effects["trip_effect"], + numeric_effects["treatment_trips"] - numeric_effects["control_trips"], + ) + or not np.allclose( + numeric_effects["wait_effect_minutes"], + numeric_effects["treatment_wait_minutes"] + - numeric_effects["control_wait_minutes"], + ) + or not np.allclose( + numeric_effects["welfare_effect"], + numeric_effects["treatment_welfare"] - numeric_effects["control_welfare"], + ) + ): + raise ValueError("equilibrium benchmark zone-effect arithmetic is inconsistent") + + ledger["equilibrium_converged"] = _strict_boolean( + ledger["equilibrium_converged"], "equilibrium_converged" + ) + ledger["budget_binding"] = _strict_boolean( + ledger["budget_binding"], "budget_binding" + ) + ledger_numeric_columns = [ + "equilibrium_residual_sup_norm", + "trips", + "treatment_spend", + "rider_surplus", + "driver_surplus", + "platform_net_revenue", + "total_welfare", + "welfare_accounting_residual", + "budget_scale", + ] + ledger_numeric = ledger[ledger_numeric_columns].apply(pd.to_numeric, errors="coerce") + if ( + not ledger["equilibrium_converged"].all() + or not np.isfinite(ledger_numeric.to_numpy(dtype=float)).all() + or (ledger_numeric["equilibrium_residual_sup_norm"] < 0).any() + or ledger_numeric["equilibrium_residual_sup_norm"].iloc[0] + > control_diagnostics["tolerance"] + or ledger_numeric["equilibrium_residual_sup_norm"].iloc[1] + > treatment_diagnostics["tolerance"] + or not np.allclose(ledger_numeric["welfare_accounting_residual"], 0.0, atol=1e-8) + ): + raise ValueError("equilibrium benchmark ledger fails convergence or accounting checks") + ordered = ledger.set_index("scenario") + required_truth = { + "market_total_effect", + "market_total_trip_effect", + "mean_zone_trip_effect", + "market_total_welfare_effect", + "mean_zone_wait_effect_minutes", + "mean_zone_service_probability_effect", + "treatment_spend", + "incremental_trips_per_dollar", + "incremental_welfare_per_dollar", + } + if not isinstance(truth, dict) or not required_truth.issubset(truth): + raise ValueError("equilibrium benchmark ground truth is incomplete") + finite_truth = [ + value for value in truth.values() if value is not None and not isinstance(value, bool) + ] + if not finite_truth or not np.isfinite(finite_truth).all(): + raise ValueError("equilibrium benchmark ground truth contains non-finite values") + trip_effect = float(numeric_effects["trip_effect"].sum()) + welfare_effect = float(numeric_effects["welfare_effect"].sum()) + treatment_spend = float(ordered.loc["treatment", "treatment_spend"]) + if ( + not np.isclose(truth["market_total_effect"], trip_effect) + or not np.isclose(truth["market_total_trip_effect"], trip_effect) + or not np.isclose(truth["market_total_welfare_effect"], welfare_effect) + or not np.isclose(truth["treatment_spend"], treatment_spend) + or not np.isclose(realized_spend, treatment_spend) + or not np.isclose( + float(ordered.loc["treatment", "trips"]) + - float(ordered.loc["control", "trips"]), + trip_effect, + ) + or not np.isclose( + float(ordered.loc["treatment", "total_welfare"]) + - float(ordered.loc["control", "total_welfare"]), + welfare_effect, + ) + ): + raise ValueError("equilibrium benchmark ground truth disagrees with its ledger") + if treatment_spend > 1e-12: + if ( + not np.isclose(truth["incremental_trips_per_dollar"], trip_effect / treatment_spend) + or not np.isclose( + truth["incremental_welfare_per_dollar"], welfare_effect / treatment_spend + ) + ): + raise ValueError("equilibrium benchmark efficiency ratios are inconsistent") + elif ( + truth["incremental_trips_per_dollar"] is not None + or truth["incremental_welfare_per_dollar"] is not None + ): + raise ValueError("equilibrium benchmark zero-spend ratios must be withheld") + + table = markdown_table( + ledger.sort_values("scenario"), + [ + "scenario", + "treatment_version", + "trips", + "mean_wait_minutes", + "mean_service_probability", + "treatment_spend", + "rider_surplus", + "driver_surplus", + "platform_net_revenue", + "total_welfare", + "equilibrium_converged", + "equilibrium_residual_sup_norm", + "budget_binding", + "budget_scale", + ], + ) + budget_text = ( + f"The configured budget is {float(declared_budget):,.2f}; the solver re-solves " + f"the equilibrium at a feasible intensity scale of {float(budget_scale):.4f}. " + if declared_budget is not None + else "No binding budget was configured for this benchmark. " + ) + summary_text = ( + "The theoretical two-sided-market benchmark solves paired control and policy " + "fixed points for the same seeded exogenous state. Both paths satisfy the " + f"declared residual tolerance and the sufficient contraction bound " + f"({float(contraction):.4f} < 1). {budget_text}The within-model policy contrast " + f"is {trip_effect:.4f} trips and {welfare_effect:.4f} units of modeled welfare. " + "These are exact counterfactuals only inside the declared equilibrium model; " + "parameters are not estimated from NYC data and this is not an NYC structural estimate." + ) + provenance = "\n".join( + [ + f"- Equilibrium benchmark manifest SHA-256: `{sha256_file(bundle.path)}`", + f"- Equilibrium benchmark metadata SHA-256: `{sha256_file(metadata_path)}`", + f"- Equilibrium benchmark ground truth SHA-256: `{sha256_file(truth_path)}`", + f"- Equilibrium benchmark zone effects SHA-256: `{sha256_file(effects_path)}`", + f"- Equilibrium benchmark ledger SHA-256: `{sha256_file(ledger_path)}`", + f"- Equilibrium seeded state ID: `{metadata['state_id']}`", + ] + ) + return _EquilibriumEvidence( + summary=summary_text, + table=table, + limitations="\n".join(f"- {item}" for item in limitations), + provenance=provenance, + ) + + +@dataclass(frozen=True, slots=True) +class _NYCWeatherEvidence: + summary: str + table: str + limitations: str + provenance: str + + +def _nyc_weather_status( + manifest_path: str | Path | None, +) -> _NYCWeatherEvidence | None: + """Validate descriptive NOAA weather associations against NYC panel lineage.""" + + bundle = _manifest_bundle(manifest_path, "NYC NOAA weather") + if bundle is None: + return None + _require_manifest_evidence(bundle, WEATHER_EVIDENCE_LABEL, "NYC NOAA weather") + checks = bundle.payload.get("checks") + if ( + bundle.payload.get("schema_version") != "1.0.0" + or bundle.payload.get("evidence_label") != WEATHER_EVIDENCE_LABEL + or bundle.payload.get("causal_claim") is not False + or bundle.payload.get("portable_paths") is not True + or not isinstance(checks, dict) + or checks.get("noaa_raw_hash_matches") is not True + or checks.get("calendar_complete") is not True + or checks.get("nyc_source_manifest_valid") is not True + or checks.get("trip_conservation") is not True + or isinstance(checks.get("panel_files_verified"), bool) + or not isinstance(checks.get("panel_files_verified"), int) + or checks["panel_files_verified"] < 1 + ): + raise ValueError("NYC NOAA weather manifest checks did not all pass") + summary_path, payload = _unique_json_object( + bundle, + lambda value: value.get("evidence_label") == WEATHER_EVIDENCE_LABEL + and "associations" in value, + "NYC NOAA weather association summary", + ) + if ( + payload.get("schema_version") != "1.0.0" + or payload.get("causal_claim") is not False + ): + raise ValueError("NYC NOAA weather summary has an unsafe evidence contract") + scope = payload.get("scope") + coverage = payload.get("coverage") + conservation = payload.get("conservation") + associations = payload.get("associations") + provenance_payload = payload.get("provenance") + if not all( + isinstance(value, dict) + for value in (scope, coverage, conservation, associations, provenance_payload) + ): + raise ValueError("NYC NOAA weather summary is incomplete") + if ( + scope.get("city") != "New York City" + or scope.get("population_claim") is not False + or not isinstance(scope.get("pickup_month"), str) + or not isinstance(scope.get("weather_station_id"), str) + or not scope.get("weather_station_id") + ): + raise ValueError("NYC NOAA weather scope is incompatible") + weather_rows = coverage.get("weather_rows") + joined_days = coverage.get("joined_days") + date_hours = coverage.get("joined_date_hours") + wet_days = coverage.get("wet_days") + dry_days = coverage.get("dry_days") + counts = (weather_rows, joined_days, date_hours, wet_days, dry_days) + if ( + any(isinstance(value, bool) or not isinstance(value, int) for value in counts) + or weather_rows <= 1 + or weather_rows != joined_days + or date_hours != joined_days * 24 + or wet_days <= 0 + or dry_days <= 0 + or wet_days + dry_days != joined_days + or scope.get("published_completed_trip_days") != joined_days + ): + raise ValueError("NYC NOAA weather calendar coverage is inconsistent") + daily_sum = conservation.get("daily_trip_sum") + zone_sum = conservation.get("zone_time_trip_sum") + if ( + conservation.get("passes") is not True + or isinstance(daily_sum, bool) + or not isinstance(daily_sum, int) + or daily_sum <= 0 + or daily_sum != zone_sum + ): + raise ValueError("NYC NOAA weather trip conservation is inconsistent") + + raw_path = ( + bundle.root + / _portable_manifest_path( + provenance_payload.get("noaa_raw_path"), "NYC NOAA raw path" + ) + ).resolve() + data_manifest_path = ( + bundle.root + / _portable_manifest_path( + provenance_payload.get("nyc_data_manifest_path"), + "NYC weather source-data manifest path", + ) + ).resolve() + if ( + raw_path not in bundle.files + or data_manifest_path not in bundle.files + or sha256_file(raw_path) != provenance_payload.get("noaa_raw_sha256") + or sha256_file(data_manifest_path) + != provenance_payload.get("nyc_data_manifest_sha256") + or provenance_payload.get("hashes_recomputed") is not True + or provenance_payload.get("panel_files_verified") + != checks["panel_files_verified"] + ): + raise ValueError("NYC NOAA weather provenance hashes disagree") + source_manifest = _load_json_object( + data_manifest_path, "NYC weather source-data manifest" + ) + source_config = source_manifest.get("config") + source_metadata = source_manifest.get("metadata") + if ( + not isinstance(source_config, dict) + or not isinstance(source_metadata, dict) + or source_config.get("source") != "nyc_hvfhv" + or source_config.get("mode") != "full" + or source_metadata.get("evidence_label") != "descriptive_real_data" + or source_metadata.get("causal_claim") is not False + ): + raise ValueError("NYC NOAA weather source-data manifest is incompatible") + source_trip_sum = ( + source_metadata.get("full_month_processing", {}) + .get("row_conservation", {}) + .get("zone_time_trip_sum") + ) + if source_trip_sum != daily_sum: + raise ValueError("NYC NOAA weather total disagrees with the NYC source manifest") + + normalized_path, normalized = _unique_csv( + bundle, + { + "service_date", + "station_id", + "precipitation_mm", + "temperature_midrange_c", + "wet_day", + "evidence_label", + "causal_claim", + "raw_sha256", + }, + "NYC NOAA normalized weather", + excluded_columns={"published_completed_trips"}, + ) + daily_path, daily = _unique_csv( + bundle, + { + "service_date", + "published_completed_trips", + "wet_day", + "precipitation_mm", + "evidence_label", + "causal_claim", + }, + "NYC NOAA daily trip-weather panel", + ) + hourly_path, hourly = _unique_csv( + bundle, + { + "hour", + "days_wet", + "days_dry", + "wet_minus_dry_mean_published_completed_trips", + "evidence_label", + "causal_claim", + }, + "NYC NOAA hourly contrasts", + ) + if len(normalized) != weather_rows or len(daily) != joined_days or len(hourly) != 24: + raise ValueError("NYC NOAA weather table coverage disagrees with its summary") + for frame in (normalized, daily, hourly): + if ( + not frame["evidence_label"].eq(WEATHER_EVIDENCE_LABEL).all() + or _strict_boolean(frame["causal_claim"], "causal_claim").any() + ): + raise ValueError("NYC NOAA weather tables contain an unsafe evidence label") + if ( + not normalized["station_id"].astype(str).eq(scope["weather_station_id"]).all() + or not normalized["raw_sha256"].eq(provenance_payload["noaa_raw_sha256"]).all() + or int(pd.to_numeric(daily["published_completed_trips"], errors="coerce").sum()) + != daily_sum + ): + raise ValueError("NYC NOAA weather table provenance or trip totals disagree") + + required_associations = { + "mean_daily_published_completed_trips_wet", + "mean_daily_published_completed_trips_dry", + "wet_minus_dry_mean_daily_published_completed_trips", + "wet_minus_dry_relative_to_dry", + "precipitation_daily_trip_correlation", + "temperature_midrange_daily_trip_correlation", + } + if not required_associations.issubset(associations): + raise ValueError("NYC NOAA weather associations are incomplete") + wet_mean = associations["mean_daily_published_completed_trips_wet"] + dry_mean = associations["mean_daily_published_completed_trips_dry"] + difference = associations["wet_minus_dry_mean_daily_published_completed_trips"] + relative = associations["wet_minus_dry_relative_to_dry"] + primary = [wet_mean, dry_mean, difference, relative] + if ( + not all(isinstance(value, (int, float)) for value in primary) + or not np.isfinite(primary).all() + or dry_mean <= 0 + or not np.isclose(difference, wet_mean - dry_mean) + or not np.isclose(relative, difference / dry_mean) + ): + raise ValueError("NYC NOAA wet-dry association arithmetic is inconsistent") + for key in ( + "precipitation_daily_trip_correlation", + "temperature_midrange_daily_trip_correlation", + ): + value = associations[key] + if value is not None and ( + not isinstance(value, (int, float)) + or not np.isfinite(value) + or not -1 <= value <= 1 + ): + raise ValueError("NYC NOAA weather correlation is invalid") + limitations = _required_string_list( + payload.get("limitations"), "NYC NOAA weather limitations" + ) + if "confound" not in " ".join(limitations).lower() or "not" not in " ".join( + limitations + ).lower(): + raise ValueError("NYC NOAA weather limitations omit the noncausal boundary") + + table_frame = pd.DataFrame( + [ + {"metric": "Mean daily published completed trips — wet", "value": wet_mean}, + {"metric": "Mean daily published completed trips — dry", "value": dry_mean}, + {"metric": "Wet minus dry mean daily trips", "value": difference}, + {"metric": "Wet minus dry relative to dry", "value": relative}, + { + "metric": "Precipitation / daily trips correlation", + "value": associations["precipitation_daily_trip_correlation"], + }, + { + "metric": "Temperature midrange / daily trips correlation", + "value": associations["temperature_midrange_daily_trip_correlation"], + }, + ] + ) + table = markdown_table(table_frame, ["metric", "value"]) + summary_text = ( + f"The verified NOAA Daily Summaries join covers {joined_days} days and " + f"{date_hours} NYC date-hours using station `{scope['weather_station_id']}`. " + f"Mean published completed trips were {float(wet_mean):,.1f} on wet days and " + f"{float(dry_mean):,.1f} on dry days, a descriptive difference of " + f"{float(difference):,.1f} ({float(relative):.2%} of the dry-day mean). " + "This is an observational weather-demand association for published completed " + "trips, not a causal weather effect, treatment effect, instrument, or latent-demand estimate." + ) + provenance = "\n".join( + [ + f"- NYC NOAA weather manifest SHA-256: `{sha256_file(bundle.path)}`", + f"- NYC NOAA association summary SHA-256: `{sha256_file(summary_path)}`", + f"- NYC NOAA raw response SHA-256: `{sha256_file(raw_path)}`", + f"- NYC weather source-data manifest SHA-256: `{sha256_file(data_manifest_path)}`", + f"- NYC NOAA normalized weather SHA-256: `{sha256_file(normalized_path)}`", + f"- NYC NOAA daily trip-weather panel SHA-256: `{sha256_file(daily_path)}`", + f"- NYC NOAA hourly contrasts SHA-256: `{sha256_file(hourly_path)}`", + ] + ) + return _NYCWeatherEvidence( + summary=summary_text, + table=table, + limitations="\n".join(f"- {item}" for item in limitations), + provenance=provenance, + ) + + +@dataclass(frozen=True, slots=True) +class _NYCDescriptiveEnrichmentEvidence: + summary: str + table: str + limitations: str + provenance: str + + +def _read_descriptive_role_csv( + bundle: _ManifestBundle, + role: str, + *, + evidence_label: str, + label: str, +) -> tuple[Path, pd.DataFrame]: + path = _bundle_file_by_role(bundle, role, label) + try: + frame = pd.read_csv(path) + except (OSError, pd.errors.ParserError, pd.errors.EmptyDataError) as exc: + raise ValueError(f"{label} {role} is not a readable CSV") from exc + if frame.empty or not {"evidence_label", "causal_claim"}.issubset(frame.columns): + raise ValueError(f"{label} {role} has an incomplete descriptive schema") + if ( + not frame["evidence_label"].astype(str).eq(evidence_label).all() + or _strict_boolean(frame["causal_claim"], "causal_claim").any() + ): + raise ValueError(f"{label} {role} violates the non-causal evidence contract") + return path, frame + + +def _validate_nyc_panel_source_manifest( + source_manifest_path: Path, + *, + bundle: _ManifestBundle, + expected_panel_files: int, + directly_declared_panel_inputs: set[Path] | None = None, +) -> tuple[int, set[Path]]: + source = _load_json_object(source_manifest_path, "NYC full source-data manifest") + config = source.get("config") + metadata = source.get("metadata") + if ( + not isinstance(config, dict) + or not isinstance(metadata, dict) + or config.get("source") != "nyc_hvfhv" + or config.get("mode") != "full" + or metadata.get("evidence_label") != "descriptive_real_data" + or metadata.get("causal_claim") is not False + ): + raise ValueError("NYC enrichment source-data manifest is incompatible") + raw_files = source.get("files") + if not isinstance(raw_files, list): + raise ValueError("NYC enrichment source-data manifest has no files list") + panel_entries: list[dict[str, Any]] = [] + panel_paths: set[Path] = set() + for entry in raw_files: + if not isinstance(entry, dict): + raise ValueError("NYC source-data manifest contains a non-object file entry") + rendered = _portable_manifest_path( + entry.get("path"), "NYC source-data manifest file path" + ) + if ( + rendered.suffix.lower() != ".parquet" + or "panel" not in rendered.parts + or "zone_time" not in rendered.parts + ): + continue + path = (bundle.root / rendered).resolve() + try: + path.relative_to(bundle.root) + except ValueError as exc: + raise ValueError("NYC panel source path escapes the project root") from exc + panel_entries.append(entry) + panel_paths.add(path) + if len(panel_entries) != expected_panel_files or len(panel_paths) != expected_panel_files: + raise ValueError("NYC enrichment panel file count disagrees with source lineage") + _validate_manifest_files( + {"files": panel_entries}, bundle.root, "NYC enrichment panel source" + ) + if ( + directly_declared_panel_inputs is not None + and directly_declared_panel_inputs != panel_paths + ): + raise ValueError("NYC enrichment panel inputs disagree with source lineage") + trip_sum = ( + metadata.get("full_month_processing", {}) + .get("row_conservation", {}) + .get("zone_time_trip_sum") + ) + if isinstance(trip_sum, bool) or not isinstance(trip_sum, int) or trip_sum <= 0: + raise ValueError("NYC enrichment source trip total is unavailable") + return trip_sum, panel_paths + + +def _nyc_events_status( + manifest_path: str | Path | None, +) -> _NYCDescriptiveEnrichmentEvidence | None: + """Validate official-calendar and permitted-event descriptive evidence.""" + + label = "NYC calendar/event enrichment" + bundle = _manifest_bundle(manifest_path, label) + if bundle is None: + return None + _require_manifest_evidence(bundle, EVENT_EVIDENCE_LABEL, label) + checks = bundle.payload.get("checks") + required_true_checks = { + "holiday_snapshot_hash_matches", + "event_snapshot_hash_matches", + "calendar_complete", + "holiday_schedule_coverage_complete", + "event_source_rows_verified", + "event_source_unique_ids_verified", + "invalid_source_intervals_retained_and_excluded", + "zero_duration_source_intervals_retained_and_excluded", + "daily_signal_is_citywide_not_zone_exposure", + "hourly_profiles_repeat_daily_signal_not_event_hour_exposure", + "major_event_is_researcher_defined", + "nyc_source_manifest_valid", + "trip_conservation", + "causal_claim_is_false", + } + if ( + bundle.payload.get("schema_version") != EVENT_SCHEMA_VERSION + or bundle.payload.get("evidence_label") != EVENT_EVIDENCE_LABEL + or bundle.payload.get("causal_claim") is not False + or bundle.payload.get("portable_paths") is not True + or not isinstance(checks, dict) + or any(checks.get(key) is not True for key in required_true_checks) + or checks.get("major_event_contrast_separately_identified") is not False + ): + raise ValueError("NYC calendar/event manifest has an unsafe evidence schema") + joined_days = checks.get("joined_days") + joined_hours = checks.get("joined_date_hours") + panel_files_verified = checks.get("panel_files_verified") + if ( + any( + isinstance(value, bool) or not isinstance(value, int) or value < 1 + for value in (joined_days, joined_hours, panel_files_verified) + ) + or joined_hours != joined_days * 24 + ): + raise ValueError("NYC calendar/event manifest coverage checks are inconsistent") + + expected_file_roles = { + "normalized_daily_calendar", + "normalized_permit_records", + "daily_permit_type_counts", + "joined_daily_trip_panel", + "descriptive_hourly_profiles", + "descriptive_summary", + } + observed_file_roles = [entry.get("role") for entry in bundle.files.values()] + if set(observed_file_roles) != expected_file_roles or len(observed_file_roles) != 6: + raise ValueError("NYC calendar/event manifest has an incomplete file-role set") + input_roles = [entry.get("role") for entry in bundle.inputs.values()] + singleton_input_roles = { + "official_holiday_snapshot", + "official_nyc_permitted_events_snapshot", + "nyc_full_data_manifest", + } + if ( + any(input_roles.count(role) != 1 for role in singleton_input_roles) + or input_roles.count("nyc_full_zone_time_panel") != panel_files_verified + or set(input_roles) != singleton_input_roles | {"nyc_full_zone_time_panel"} + ): + raise ValueError("NYC calendar/event manifest has an incomplete input-role set") + + summary_path = _bundle_file_by_role(bundle, "descriptive_summary", label) + summary = _load_json_object(summary_path, "NYC calendar/event summary") + scope = summary.get("scope") + definitions = summary.get("definitions") + coverage = summary.get("coverage") + associations = summary.get("associations") + identification = summary.get("identification_checks") + conservation = summary.get("conservation") + provenance_payload = summary.get("provenance") + if not all( + isinstance(value, dict) + for value in ( + scope, + definitions, + coverage, + associations, + identification, + conservation, + provenance_payload, + ) + ): + raise ValueError("NYC calendar/event summary is incomplete") + major_definition = definitions.get("researcher_defined_major_permitted_event") + if ( + summary.get("schema_version") != EVENT_SCHEMA_VERSION + or summary.get("evidence_label") != EVENT_EVIDENCE_LABEL + or summary.get("causal_claim") is not False + or scope.get("city") != "New York City" + or scope.get("population_claim") is not False + or scope.get("event_signal_spatial_granularity") != "citywide" + or scope.get("event_signal_temporal_granularity") != "service_date" + or not isinstance(major_definition, dict) + or major_definition.get("official_severity_classification") is not False + or identification.get("causal_effect_identified") is not False + or identification.get("permit_intensity_assignment_is_randomized") is not False + or identification.get("major_event_contrast_separately_identifies_event_effect") + is not False + or identification.get("major_event_days_are_subset_of_holiday_days") is not True + or identification.get("all_weekend_days_are_above_median_permit_intensity") + is not True + ): + raise ValueError("NYC calendar/event summary violates its non-causal scope") + + permit_rows = coverage.get("source_permit_rows") + unique_ids = coverage.get("source_unique_event_ids") + invalid_rows = coverage.get("invalid_interval_rows_retained_but_not_expanded") + zero_duration_rows = coverage.get( + "zero_duration_interval_rows_retained_but_not_expanded" + ) + nonpositive_rows = coverage.get( + "all_nonpositive_interval_rows_retained_but_not_expanded" + ) + valid_rows = coverage.get("valid_interval_rows") + valid_unique_ids = coverage.get("valid_unique_event_ids") + event_days = coverage.get("expanded_unique_event_days") + above_days = coverage.get("above_median_permit_intensity_days") + comparison_days = coverage.get("at_or_below_median_permit_intensity_days") + major_days = coverage.get("researcher_defined_major_event_days") + weekend_days = coverage.get("weekend_days") + above_weekend_days = coverage.get("above_median_permit_intensity_weekend_days") + lower_weekend_days = coverage.get( + "at_or_below_median_permit_intensity_weekend_days" + ) + numeric_coverage = ( + permit_rows, + unique_ids, + invalid_rows, + zero_duration_rows, + nonpositive_rows, + valid_rows, + valid_unique_ids, + event_days, + above_days, + comparison_days, + major_days, + weekend_days, + above_weekend_days, + lower_weekend_days, + ) + if ( + any(isinstance(value, bool) or not isinstance(value, int) for value in numeric_coverage) + or permit_rows < unique_ids + or unique_ids < 1 + or invalid_rows < 0 + or zero_duration_rows < 0 + or nonpositive_rows != invalid_rows + zero_duration_rows + or valid_rows != permit_rows - nonpositive_rows + or not 1 <= valid_unique_ids <= unique_ids + or event_days < valid_unique_ids + or above_days < 1 + or comparison_days < 1 + or above_days + comparison_days != joined_days + or major_days < 1 + or weekend_days < 0 + or above_weekend_days != weekend_days + or lower_weekend_days != 0 + or coverage.get("joined_days") != joined_days + or coverage.get("joined_date_hours") != joined_hours + ): + raise ValueError("NYC calendar/event summary coverage is inconsistent") + + contrast_specs = ( + ( + "above_vs_at_or_below_median_permit_intensity", + "Above-median permit intensity vs lower-intensity days", + joined_days, + ), + ( + "above_vs_at_or_below_median_permit_intensity_weekdays_only", + "Weekday-only: above-median vs lower permit intensity", + joined_days - weekend_days, + ), + ( + "official_holiday_vs_nonholiday", + "Official holiday vs nonholiday days", + joined_days, + ), + ) + table_rows: list[dict[str, Any]] = [] + for key, rendered_label, expected_days in contrast_specs: + contrast = associations.get(key) + if not isinstance(contrast, dict): + raise ValueError(f"NYC calendar/event association {key} is missing") + exposed = contrast.get("exposed_days") + comparison = contrast.get("comparison_days") + exposed_mean = contrast.get("mean_daily_published_completed_trips_exposed") + comparison_mean = contrast.get( + "mean_daily_published_completed_trips_comparison" + ) + difference = contrast.get( + "exposed_minus_comparison_mean_daily_published_completed_trips" + ) + relative = contrast.get("exposed_minus_comparison_relative_to_comparison") + numbers = (exposed_mean, comparison_mean, difference, relative) + if ( + isinstance(exposed, bool) + or not isinstance(exposed, int) + or isinstance(comparison, bool) + or not isinstance(comparison, int) + or exposed + comparison != expected_days + or not all(isinstance(value, (int, float)) for value in numbers) + or not np.isfinite(numbers).all() + or comparison_mean <= 0 + or not np.isclose(difference, exposed_mean - comparison_mean) + or not np.isclose(relative, difference / comparison_mean) + ): + raise ValueError("NYC calendar/event association arithmetic is inconsistent") + table_rows.append( + { + "descriptive contrast": rendered_label, + "exposed days": exposed, + "comparison days": comparison, + "mean exposed trips": exposed_mean, + "mean comparison trips": comparison_mean, + "difference": difference, + "relative difference": relative, + } + ) + major_contrast = associations.get("major_permitted_event_day_vs_other_days") + if not isinstance(major_contrast, dict) or major_contrast.get("exposed_days") != major_days: + raise ValueError("NYC calendar/event major-day diagnostic is inconsistent") + weekday_demeaned_correlation = associations.get( + "weekday_demeaned_active_permit_count_daily_trip_correlation" + ) + if weekday_demeaned_correlation is not None and ( + not isinstance(weekday_demeaned_correlation, (int, float)) + or not np.isfinite(weekday_demeaned_correlation) + or not -1 <= weekday_demeaned_correlation <= 1 + ): + raise ValueError("NYC calendar/event weekday-demeaned correlation is invalid") + if ( + conservation.get("passes") is not True + or conservation.get("daily_trip_sum") != conservation.get("zone_time_trip_sum") + or isinstance(conservation.get("daily_trip_sum"), bool) + or not isinstance(conservation.get("daily_trip_sum"), int) + or conservation["daily_trip_sum"] <= 0 + ): + raise ValueError("NYC calendar/event trip conservation is inconsistent") + + role_frames: dict[str, tuple[Path, pd.DataFrame]] = {} + for role in expected_file_roles - {"descriptive_summary"}: + role_frames[role] = _read_descriptive_role_csv( + bundle, + role, + evidence_label=EVENT_EVIDENCE_LABEL, + label=label, + ) + if ( + len(role_frames["normalized_daily_calendar"][1]) != joined_days + or len(role_frames["normalized_permit_records"][1]) != permit_rows + or len(role_frames["descriptive_hourly_profiles"][1]) != 24 + or len(role_frames["joined_daily_trip_panel"][1]) != joined_days + or int( + pd.to_numeric( + role_frames["joined_daily_trip_panel"][1][ + "published_completed_trips" + ], + errors="coerce", + ).sum() + ) + != conservation["daily_trip_sum"] + ): + raise ValueError("NYC calendar/event tables disagree with their summary") + + source_manifest_path = _bundle_input_by_role( + bundle, "nyc_full_data_manifest", label + ) + direct_panels = { + path + for path, entry in bundle.inputs.items() + if entry.get("role") == "nyc_full_zone_time_panel" + } + source_trip_sum, _ = _validate_nyc_panel_source_manifest( + source_manifest_path, + bundle=bundle, + expected_panel_files=panel_files_verified, + directly_declared_panel_inputs=direct_panels, + ) + if source_trip_sum != conservation["daily_trip_sum"]: + raise ValueError("NYC calendar/event trips disagree with source lineage") + for role, path_key, hash_key in ( + ("official_holiday_snapshot", "holiday_snapshot_path", "holiday_snapshot_sha256"), + ( + "official_nyc_permitted_events_snapshot", + "event_snapshot_path", + "event_snapshot_sha256", + ), + ("nyc_full_data_manifest", "nyc_data_manifest_path", "nyc_data_manifest_sha256"), + ): + input_path = _bundle_input_by_role(bundle, role, label) + if ( + _portable_manifest_path(provenance_payload.get(path_key), path_key) + != input_path.relative_to(bundle.root) + or provenance_payload.get(hash_key) != sha256_file(input_path) + ): + raise ValueError("NYC calendar/event provenance disagrees with inputs") + if ( + provenance_payload.get("hashes_recomputed") is not True + or provenance_payload.get("panel_files_verified") != panel_files_verified + ): + raise ValueError("NYC calendar/event provenance checks are incomplete") + limitations = _required_string_list( + summary.get("limitations"), "NYC calendar/event limitations" + ) + limitation_text = " ".join(limitations).lower() + if ( + "confound" not in limitation_text + or "attendance" not in limitation_text + or "weekend" not in limitation_text + ): + raise ValueError("NYC calendar/event limitations omit key evidence boundaries") + + permit_contrast = associations["above_vs_at_or_below_median_permit_intensity"] + weekday_contrast = associations[ + "above_vs_at_or_below_median_permit_intensity_weekdays_only" + ] + holiday_contrast = associations["official_holiday_vs_nonholiday"] + summary_text = ( + f"The verified January calendar/event join covers {joined_days} days and " + f"{joined_hours} date-hours from {permit_rows:,} permit rows representing " + f"{unique_ids:,} event IDs. Above-median permit-intensity days differed from " + f"lower-intensity days by {float(permit_contrast['exposed_minus_comparison_mean_daily_published_completed_trips']):,.1f} " + f"published completed trips/day ({float(permit_contrast['exposed_minus_comparison_relative_to_comparison']):.2%}), " + f"but all {weekend_days} weekend days are in the above-median group and none " + f"are in the comparison group. Restricting to weekdays reverses the descriptive " + f"difference to {float(weekday_contrast['exposed_minus_comparison_mean_daily_published_completed_trips']):,.1f}/day " + f"({float(weekday_contrast['exposed_minus_comparison_relative_to_comparison']):.2%}); " + f"official holidays differed from nonholidays by " + f"{float(holiday_contrast['exposed_minus_comparison_mean_daily_published_completed_trips']):,.1f}/day " + f"({float(holiday_contrast['exposed_minus_comparison_relative_to_comparison']):.2%}). " + "These are observational citywide daily associations. Permit windows are not " + "attendance or zone/hour exposure, and the researcher-defined major-event day " + "is holiday-confounded rather than separately identified." + ) + provenance = "\n".join( + [ + f"- NYC calendar/event manifest SHA-256: `{sha256_file(bundle.path)}`", + f"- NYC calendar/event summary SHA-256: `{sha256_file(summary_path)}`", + *[ + f"- NYC calendar/event input `{entry.get('role')}` SHA-256: `{sha256_file(path)}`" + for path, entry in bundle.inputs.items() + ], + ] + ) + return _NYCDescriptiveEnrichmentEvidence( + summary=summary_text, + table=markdown_table(pd.DataFrame(table_rows), list(table_rows[0])), + limitations="\n".join(f"- {item}" for item in limitations), + provenance=provenance, + ) + + +def _nyc_income_status( + manifest_path: str | Path | None, +) -> _NYCDescriptiveEnrichmentEvidence | None: + """Validate ecological Taxi Zone income descriptions and their official lineage.""" + + label = "NYC neighborhood-income enrichment" + bundle = _manifest_bundle(manifest_path, label) + if bundle is None: + return None + _require_manifest_evidence(bundle, INCOME_EVIDENCE_LABEL, label) + checks = bundle.payload.get("checks") + required_true_checks = { + "official_source_hashes_match", + "taxi_location_ids_unique_and_complete", + "tract_b19001_totals_equal_sixteen_bins", + "household_distribution_conserved", + "published_trip_conservation", + "ecological_noncausal_contract", + "dominant_nonresidential_primary_unclassified", + "all_zone_classification_is_sensitivity_only", + } + if ( + bundle.payload.get("schema_version") != INCOME_SCHEMA_VERSION + or bundle.payload.get("artifact_type") != "nyc_income_descriptive_bundle" + or bundle.payload.get("evidence_label") != INCOME_EVIDENCE_LABEL + or bundle.payload.get("causal_claim") is not False + or bundle.payload.get("portable_paths") is not True + or not isinstance(checks, dict) + or any(checks.get(key) is not True for key in required_true_checks) + or checks.get("median_of_medians_used") is not False + or checks.get("equal_area_crs") != "EPSG:6933" + or checks.get("dominant_nonresidential_primary_classified_zones") != 0 + or checks.get("minimum_allocated_households") != 1.0 + or checks.get("minimum_residential_taxi_zone_area_share") != 0.5 + or checks.get("residential_nta_type_codes") != ["0"] + or checks.get("zone_grouped_medians_are_point_estimates") is not True + or checks.get("zone_level_margin_of_error_propagated") is not False + ): + raise ValueError("NYC neighborhood-income manifest has an unsafe evidence schema") + panel_files_verified = checks.get("panel_files_verified") + declared_coverage = checks.get("classified_trip_coverage") + if ( + isinstance(panel_files_verified, bool) + or not isinstance(panel_files_verified, int) + or panel_files_verified < 1 + or isinstance(declared_coverage, bool) + or not isinstance(declared_coverage, (int, float)) + or not np.isfinite(declared_coverage) + or not 0 < declared_coverage <= 1 + ): + raise ValueError("NYC neighborhood-income manifest coverage checks are invalid") + + expected_file_roles = { + "taxi_zone_nta_crosswalk", + "nta_b19001_distribution_summary", + "taxi_zone_income_and_trip_summary", + "daily_income_group_description", + "monthly_income_group_description", + "income_association_summary", + } + observed_file_roles = [entry.get("role") for entry in bundle.files.values()] + if set(observed_file_roles) != expected_file_roles or len(observed_file_roles) != 6: + raise ValueError("NYC neighborhood-income manifest has an incomplete file-role set") + if any( + entry.get("evidence_label") != INCOME_EVIDENCE_LABEL + or entry.get("causal_claim") is not False + for entry in bundle.files.values() + ): + raise ValueError("NYC neighborhood-income files have unsafe evidence metadata") + expected_input_types = { + "official_tlc_taxi_zone_geometry": "official_observed_geometry", + "official_nyc_nta2020_geometry": "official_observed_geometry", + "official_nyc_tract2020_to_nta2020_mapping": "official_observed_crosswalk", + "official_census_acs_2022_5yr_b19001_nyc_tract_slice": ( + "official_observed_estimates" + ), + "verified_nyc_full_data_manifest": "descriptive_real_data_lineage", + } + observed_inputs = { + str(entry.get("role")): entry + for entry in bundle.inputs.values() + if entry.get("role") != "nyc_full_zone_time_panel" + } + panel_inputs = { + path + for path, entry in bundle.inputs.items() + if entry.get("role") == "nyc_full_zone_time_panel" + } + if ( + set(observed_inputs) != set(expected_input_types) + or len(panel_inputs) != panel_files_verified + or len(bundle.inputs) != 5 + panel_files_verified + ): + raise ValueError("NYC neighborhood-income manifest has an incomplete input-role set") + if any( + observed_inputs[role].get("source_type") != source_type + for role, source_type in expected_input_types.items() + ) or any( + entry.get("source_type") != "descriptive_real_data_panel" + for path, entry in bundle.inputs.items() + if path in panel_inputs + ): + raise ValueError("NYC neighborhood-income input evidence types are invalid") + + summary_path = _bundle_file_by_role(bundle, "income_association_summary", label) + summary = _load_json_object(summary_path, "NYC neighborhood-income summary") + scope = summary.get("scope") + definitions = summary.get("definitions") + coverage = summary.get("coverage") + associations = summary.get("associations") + conservation = summary.get("conservation") + spatial = summary.get("spatial_mapping") + acs = summary.get("acs_aggregation") + allocation = summary.get("zone_allocation") + primary_classification = summary.get("primary_classification") + uncertainty = summary.get("classification_uncertainty") + sensitivity = summary.get("sensitivity") + provenance_payload = summary.get("provenance") + if not all( + isinstance(value, dict) + for value in ( + scope, + definitions, + coverage, + associations, + conservation, + spatial, + acs, + allocation, + primary_classification, + uncertainty, + sensitivity, + provenance_payload, + ) + ): + raise ValueError("NYC neighborhood-income summary is incomplete") + if ( + summary.get("schema_version") != INCOME_SCHEMA_VERSION + or summary.get("evidence_label") != INCOME_EVIDENCE_LABEL + or summary.get("causal_claim") is not False + or scope.get("city") != "New York City" + or scope.get("population_claim") is not False + or scope.get("individual_income_claim") is not False + or "never a median" not in str(definitions.get("income_measure", "")) + or spatial.get("equal_area_crs") != "EPSG:6933" + or acs.get("median_of_medians_used") is not False + or acs.get("totals_equal_sum_of_bins") is not True + or allocation.get("all_sixteen_bins_conserved") is not True + or allocation.get("households_conserved") is not True + or allocation.get("median_of_medians_used") is not False + or allocation.get("minimum_allocated_households") != 1.0 + or allocation.get("minimum_residential_taxi_zone_area_share") != 0.5 + or allocation.get("residential_nta_type_codes") != ["0"] + or primary_classification.get("primary_result") is not True + or primary_classification.get("minimum_allocated_households") != 1.0 + or primary_classification.get("minimum_residential_taxi_zone_area_share") + != 0.5 + or primary_classification.get("residential_nta_type_codes") != ["0"] + or uncertainty.get("nta_b19001_margins_of_error_retained") is not True + or uncertainty.get("zone_grouped_medians_are_point_estimates") is not True + or uncertainty.get("zone_level_margin_of_error_propagated") is not False + or "not a confidence interval" + not in str(uncertainty.get("interpretation", "")).lower() + ): + raise ValueError("NYC neighborhood-income summary violates its ecological scope") + total_trips = coverage.get("published_completed_trips") + classified_trips = coverage.get("classified_published_completed_trips") + unclassified_trips = coverage.get("unclassified_published_completed_trips") + classified_zones = coverage.get("classified_panel_zones") + observed_days = coverage.get("observed_days") + panel_zone_rows = coverage.get("panel_zone_rows") + nonresidential_panel_zones = coverage.get("dominant_nonresidential_panel_zones") + nonresidential_trips = coverage.get( + "dominant_nonresidential_published_completed_trips" + ) + allocated_classified_zones = allocation.get("classified_zone_rows") + allocated_high_zones = allocation.get("high_income_zone_rows") + allocated_low_zones = allocation.get("low_income_zone_rows") + ratio = coverage.get("classified_trip_coverage") + if ( + any( + isinstance(value, bool) or not isinstance(value, int) + for value in ( + total_trips, + classified_trips, + unclassified_trips, + classified_zones, + observed_days, + panel_zone_rows, + nonresidential_panel_zones, + nonresidential_trips, + allocated_classified_zones, + allocated_high_zones, + allocated_low_zones, + ) + ) + or total_trips <= 0 + or classified_trips <= 0 + or classified_trips + unclassified_trips != total_trips + or classified_zones < 1 + or observed_days < 1 + or panel_zone_rows < classified_zones + or not 0 <= nonresidential_panel_zones <= panel_zone_rows + or not 0 <= nonresidential_trips <= total_trips + or isinstance(ratio, bool) + or not isinstance(ratio, (int, float)) + or not np.isfinite(ratio) + or not np.isclose(ratio, classified_trips / total_trips) + or not np.isclose(ratio, declared_coverage) + or allocated_classified_zones != classified_zones + or allocated_high_zones + allocated_low_zones != classified_zones + or conservation.get("primary_classified_plus_unclassified_trip_sum") + != total_trips + or conservation.get("primary_nonresidential_classified_zones") != 0 + ): + raise ValueError("NYC neighborhood-income coverage is inconsistent") + high_rate = associations.get( + "mean_published_completed_trips_per_zone_hour_high_income_area" + ) + low_rate = associations.get( + "mean_published_completed_trips_per_zone_hour_low_income_area" + ) + difference = associations.get( + "high_minus_low_mean_published_completed_trips_per_zone_hour" + ) + rate_ratio = associations.get( + "high_to_low_mean_published_completed_trips_per_zone_hour_ratio" + ) + association_numbers = (high_rate, low_rate, difference, rate_ratio) + if ( + any(isinstance(value, bool) for value in association_numbers) + or not all(isinstance(value, (int, float)) for value in association_numbers) + or not np.isfinite(association_numbers).all() + or low_rate <= 0 + or not np.isclose(difference, high_rate - low_rate) + or not np.isclose(rate_ratio, high_rate / low_rate) + ): + raise ValueError("NYC neighborhood-income association arithmetic is inconsistent") + + primary_groups = primary_classification.get("groups") + if not isinstance(primary_groups, dict) or set(primary_groups) != { + "high_income_area", + "low_income_area", + "unclassified", + }: + raise ValueError("NYC neighborhood-income primary groups are incomplete") + primary_group_values: dict[str, tuple[int, int, float]] = {} + for group_name, group in primary_groups.items(): + if not isinstance(group, dict): + raise ValueError("NYC neighborhood-income primary group is invalid") + zones = group.get("panel_zones") + trips = group.get("published_completed_trips") + mean_rate = group.get("mean_published_completed_trips_per_zone_hour") + trip_share = group.get("share_of_all_published_completed_trips") + count_schema_invalid = ( + isinstance(zones, bool) + or not isinstance(zones, int) + or isinstance(trips, bool) + or not isinstance(trips, int) + or zones < 0 + or trips < 0 + ) + empty_group = not count_schema_invalid and zones == 0 and trips == 0 + mean_schema_valid = mean_rate is None and empty_group + if isinstance(mean_rate, (int, float)) and not isinstance(mean_rate, bool): + mean_schema_valid = bool(np.isfinite(mean_rate)) + if ( + count_schema_invalid + or not mean_schema_valid + or isinstance(trip_share, bool) + or not isinstance(trip_share, (int, float)) + or not np.isfinite(trip_share) + or not np.isclose(trip_share, trips / total_trips) + ): + raise ValueError("NYC neighborhood-income primary group is inconsistent") + primary_group_values[group_name] = ( + zones, + trips, + float(mean_rate) if mean_rate is not None else float("nan"), + ) + primary_high = primary_group_values["high_income_area"] + primary_low = primary_group_values["low_income_area"] + primary_unclassified = primary_group_values["unclassified"] + if ( + primary_high[0] + primary_low[0] != classified_zones + or primary_high[1] + primary_low[1] != classified_trips + or primary_high[0] + primary_low[0] + primary_unclassified[0] + != panel_zone_rows + or primary_high[1] + primary_low[1] + primary_unclassified[1] + != total_trips + or not np.isclose(primary_high[2], high_rate) + or not np.isclose(primary_low[2], low_rate) + ): + raise ValueError("NYC neighborhood-income primary arithmetic is inconsistent") + + proximity = uncertainty.get("threshold_proximity") + proximity_keys = ( + "within_1000_usd", + "within_2500_usd", + "within_5000_usd", + "within_10000_usd", + ) + if not isinstance(proximity, dict) or not all( + isinstance(proximity.get(key), dict) for key in proximity_keys + ): + raise ValueError("NYC neighborhood-income uncertainty audit is incomplete") + prior_zones = -1 + prior_trips = -1 + prior_share = -1.0 + for key in proximity_keys: + item = proximity[key] + zones = item.get("primary_eligible_panel_zones") + trips = item.get("published_completed_trips") + share = item.get("share_of_primary_classified_trips") + if ( + isinstance(zones, bool) + or not isinstance(zones, int) + or isinstance(trips, bool) + or not isinstance(trips, int) + or isinstance(share, bool) + or not isinstance(share, (int, float)) + or zones < prior_zones + or trips < prior_trips + or not np.isfinite(share) + or not 0 <= share <= 1 + or share < prior_share + or not np.isclose(share, trips / classified_trips) + ): + raise ValueError("NYC neighborhood-income uncertainty audit is inconsistent") + prior_zones, prior_trips, prior_share = zones, trips, float(share) + + all_zone_sensitivity = sensitivity.get("all_zone_area_allocation") + if not isinstance(all_zone_sensitivity, dict): + raise ValueError("NYC neighborhood-income sensitivity is incomplete") + sensitivity_groups = all_zone_sensitivity.get("groups") + if not isinstance(sensitivity_groups, dict) or set(sensitivity_groups) != { + "high_income_area", + "low_income_area", + "unclassified", + }: + raise ValueError("NYC neighborhood-income sensitivity groups are incomplete") + sensitivity_group_values: dict[str, tuple[int, int, float, float]] = {} + for group_name, group in sensitivity_groups.items(): + if not isinstance(group, dict): + raise ValueError("NYC neighborhood-income sensitivity group is invalid") + zones = group.get("panel_zones") + trips = group.get("published_completed_trips") + mean_rate = group.get("mean_published_completed_trips_per_zone_hour") + trip_share = group.get("share_of_all_published_completed_trips") + count_schema_invalid = ( + isinstance(zones, bool) + or not isinstance(zones, int) + or isinstance(trips, bool) + or not isinstance(trips, int) + or zones < 0 + or trips < 0 + ) + empty_group = not count_schema_invalid and zones == 0 and trips == 0 + mean_schema_valid = mean_rate is None and empty_group + if isinstance(mean_rate, (int, float)) and not isinstance(mean_rate, bool): + mean_schema_valid = bool(np.isfinite(mean_rate)) + if ( + count_schema_invalid + or not mean_schema_valid + or isinstance(trip_share, bool) + or not isinstance(trip_share, (int, float)) + or not np.isfinite(trip_share) + or not np.isclose(trip_share, trips / total_trips) + ): + raise ValueError("NYC neighborhood-income sensitivity group is inconsistent") + sensitivity_group_values[group_name] = ( + zones, + trips, + float(mean_rate) if mean_rate is not None else float("nan"), + float(trip_share), + ) + sensitivity_classified_zones = all_zone_sensitivity.get("classified_panel_zones") + sensitivity_classified_trips = all_zone_sensitivity.get( + "classified_published_completed_trips" + ) + sensitivity_coverage = all_zone_sensitivity.get("classified_trip_coverage") + sensitivity_high_rate = all_zone_sensitivity.get( + "mean_published_completed_trips_per_zone_hour_high_income_area" + ) + sensitivity_low_rate = all_zone_sensitivity.get( + "mean_published_completed_trips_per_zone_hour_low_income_area" + ) + sensitivity_difference = all_zone_sensitivity.get( + "high_minus_low_mean_published_completed_trips_per_zone_hour" + ) + sensitivity_ratio = all_zone_sensitivity.get( + "high_to_low_mean_published_completed_trips_per_zone_hour_ratio" + ) + sensitivity_nonresidential_zones = all_zone_sensitivity.get( + "dominant_nonresidential_zones_classified" + ) + sensitivity_nonresidential_trips = all_zone_sensitivity.get( + "dominant_nonresidential_classified_published_completed_trips" + ) + sensitivity_numbers = ( + sensitivity_coverage, + sensitivity_high_rate, + sensitivity_low_rate, + sensitivity_difference, + sensitivity_ratio, + ) + high_group = sensitivity_group_values["high_income_area"] + low_group = sensitivity_group_values["low_income_area"] + unclassified_group = sensitivity_group_values["unclassified"] + if ( + all_zone_sensitivity.get("primary_result") is not False + or all_zone_sensitivity.get( + "ignored_primary_residential_taxi_zone_area_share_threshold" + ) + != 0.5 + or isinstance(sensitivity_classified_zones, bool) + or not isinstance(sensitivity_classified_zones, int) + or isinstance(sensitivity_classified_trips, bool) + or not isinstance(sensitivity_classified_trips, int) + or isinstance(sensitivity_nonresidential_zones, bool) + or not isinstance(sensitivity_nonresidential_zones, int) + or isinstance(sensitivity_nonresidential_trips, bool) + or not isinstance(sensitivity_nonresidential_trips, int) + or sensitivity_nonresidential_zones < 0 + or sensitivity_nonresidential_trips < 0 + or any(isinstance(value, bool) for value in sensitivity_numbers) + or not all(isinstance(value, (int, float)) for value in sensitivity_numbers) + or not np.isfinite(sensitivity_numbers).all() + or sensitivity_low_rate <= 0 + or sensitivity_classified_zones != high_group[0] + low_group[0] + or sensitivity_classified_trips != high_group[1] + low_group[1] + or panel_zone_rows != high_group[0] + low_group[0] + unclassified_group[0] + or total_trips != high_group[1] + low_group[1] + unclassified_group[1] + or not np.isclose(sensitivity_coverage, sensitivity_classified_trips / total_trips) + or not np.isclose(sensitivity_high_rate, high_group[2]) + or not np.isclose(sensitivity_low_rate, low_group[2]) + or not np.isclose(sensitivity_difference, sensitivity_high_rate - sensitivity_low_rate) + or not np.isclose(sensitivity_ratio, sensitivity_high_rate / sensitivity_low_rate) + or sensitivity_nonresidential_zones + != allocation.get("dominant_nonresidential_zones_classified_only_in_sensitivity") + or conservation.get("sensitivity_group_trip_sum") != total_trips + ): + raise ValueError("NYC neighborhood-income sensitivity arithmetic is inconsistent") + if ( + conservation.get("passes") is not True + or any( + conservation.get(key) != total_trips + for key in ("zone_trip_sum", "daily_group_trip_sum", "monthly_group_trip_sum") + ) + ): + raise ValueError("NYC neighborhood-income trip conservation is inconsistent") + + role_frames: dict[str, tuple[Path, pd.DataFrame]] = {} + for role in expected_file_roles - {"income_association_summary"}: + role_frames[role] = _read_descriptive_role_csv( + bundle, + role, + evidence_label=INCOME_EVIDENCE_LABEL, + label=label, + ) + monthly = role_frames["monthly_income_group_description"][1] + daily = role_frames["daily_income_group_description"][1] + required_groups = {"high_income_area", "low_income_area"} + if ( + not required_groups.issubset(set(monthly["income_group"].astype(str))) + or int(pd.to_numeric(monthly["published_completed_trips"], errors="coerce").sum()) + != total_trips + or int(pd.to_numeric(daily["published_completed_trips"], errors="coerce").sum()) + != total_trips + ): + raise ValueError("NYC neighborhood-income tables disagree with their summary") + + source_manifest_path = _bundle_input_by_role( + bundle, "verified_nyc_full_data_manifest", label + ) + source_trip_sum, _ = _validate_nyc_panel_source_manifest( + source_manifest_path, + bundle=bundle, + expected_panel_files=panel_files_verified, + directly_declared_panel_inputs=panel_inputs, + ) + if source_trip_sum != total_trips: + raise ValueError("NYC neighborhood-income trips disagree with source lineage") + provenance_roles = ( + ( + "official_tlc_taxi_zone_geometry", + "tlc_taxi_zone_path", + "tlc_taxi_zone_sha256", + ), + ("official_nyc_nta2020_geometry", "nyc_nta2020_path", "nyc_nta2020_sha256"), + ( + "official_nyc_tract2020_to_nta2020_mapping", + "nyc_tract_to_nta_path", + "nyc_tract_to_nta_sha256", + ), + ( + "official_census_acs_2022_5yr_b19001_nyc_tract_slice", + "acs_nyc_slice_path", + "acs_nyc_slice_sha256", + ), + ( + "verified_nyc_full_data_manifest", + "nyc_data_manifest_path", + "nyc_data_manifest_sha256", + ), + ) + for role, path_key, hash_key in provenance_roles: + input_path = _bundle_input_by_role(bundle, role, label) + if ( + _portable_manifest_path(provenance_payload.get(path_key), path_key) + != input_path.relative_to(bundle.root) + or provenance_payload.get(hash_key) != sha256_file(input_path) + ): + raise ValueError("NYC neighborhood-income provenance disagrees with inputs") + if ( + provenance_payload.get("hashes_recomputed") is not True + or provenance_payload.get("panel_files_verified") != panel_files_verified + ): + raise ValueError("NYC neighborhood-income provenance checks are incomplete") + limitations = _required_string_list( + summary.get("limitations"), "NYC neighborhood-income limitations" + ) + limitation_text = " ".join(limitations).lower() + if "observational" not in limitation_text or "individual income" not in limitation_text: + raise ValueError("NYC neighborhood-income limitations omit ecological boundaries") + + table_rows = pd.DataFrame( + [ + { + "area group": "High-income Taxi Zones", + "mean published completed trips / zone-hour": high_rate, + }, + { + "area group": "Low-income Taxi Zones", + "mean published completed trips / zone-hour": low_rate, + }, + { + "area group": "High minus low", + "mean published completed trips / zone-hour": difference, + }, + { + "area group": "High / low ratio", + "mean published completed trips / zone-hour": rate_ratio, + }, + ] + ) + summary_text = ( + f"The verified Taxi Zone→NTA→ACS B19001 enrichment classifies " + f"{classified_zones:,} observed Taxi Zones and covers {float(ratio):.2%} of " + f"{total_trips:,} published completed trips. Mean completed trips per zone-hour " + f"were {float(high_rate):,.2f} in high-income areas and {float(low_rate):,.2f} " + f"in low-income areas, a descriptive difference of {float(difference):,.2f} " + f"(ratio {float(rate_ratio):.3f}). Income is an area-level, equal-area-allocated " + "household distribution—not rider or driver income. Allocation assumes households " + "are uniform within each NTA; ACS margins of error are retained at NTA level, but " + "there is no exact margin of error for allocated Taxi Zone grouped medians. This " + "ecological contrast does not identify a causal income effect. The explicitly " + "non-primary all-zone allocation sensitivity reports a high-minus-low difference " + f"of {float(sensitivity_difference):,.2f}, but it classifies " + f"{sensitivity_nonresidential_zones:,} " + "dominant-nonresidential zones representing " + f"{sensitivity_nonresidential_trips:,} " + "published completed trips. Because that sensitivity intentionally ignores the " + "primary residential-eligibility gate, it is not the primary result." + ) + provenance = "\n".join( + [ + f"- NYC neighborhood-income manifest SHA-256: `{sha256_file(bundle.path)}`", + f"- NYC neighborhood-income summary SHA-256: `{sha256_file(summary_path)}`", + *[ + f"- NYC neighborhood-income input `{entry.get('role')}` SHA-256: `{sha256_file(path)}`" + for path, entry in bundle.inputs.items() + ], + ] + ) + return _NYCDescriptiveEnrichmentEvidence( + summary=summary_text, + table=markdown_table(table_rows, list(table_rows.columns)), + limitations="\n".join(f"- {item}" for item in limitations), + provenance=provenance, + ) + + +def _descriptive_status(path: str | Path | None) -> str: + if path is None or not Path(path).is_file(): + return "Descriptive artifact not supplied." + payload = json.loads(Path(path).read_text(encoding="utf-8")) + if payload.get("evidence_type") != "empirical_association": + raise ValueError("descriptive moments must be labeled empirical_association") + panel_rows = payload.get("panel_rows") + observed_trips = payload.get("total_observed_trips") + panel_label = ( + _counted(int(panel_rows), "observed zone-time cell") + if isinstance(panel_rows, int) and not isinstance(panel_rows, bool) + else f"{panel_rows or '—'} observed zone-time cells" + ) + trip_label = ( + _counted(int(observed_trips), "trip") + if isinstance(observed_trips, int) and not isinstance(observed_trips, bool) + else f"{observed_trips or '—'} trips" + ) + return ( + f"The supplied public-data panel contains {panel_label} and {trip_label}. These are " + "descriptive fixture quantities, not causal treatment effects or representative city totals." + ) + + +def _hte_status( + summary_path: str | Path | None, + calibration_path: str | Path | None, + stability_path: str | Path | None, +) -> tuple[str, str]: + """Validate and summarize known-truth heterogeneous-effect recovery artifacts.""" + + if summary_path is None or not Path(summary_path).is_file(): + return ( + "HTE recovery artifacts were not supplied; no heterogeneous-effect claim is issued.", + "No HTE calibration table was available.", + ) + payload = json.loads(Path(summary_path).read_text(encoding="utf-8")) + if payload.get("evidence_type") != "semi_synthetic_hte_known_truth_recovery": + raise ValueError("HTE summary must be labeled semi_synthetic_hte_known_truth_recovery") + if payload.get("target_estimand") != "controlled_zone_direct_effect": + raise ValueError("HTE summary has an unsupported or missing target estimand") + required_summary = { + "rows", + "bias", + "rmse", + "fold_mean_cate_sd", + "known_truth_sd", + "oracle_constant_effect_rmse", + "predicted_truth_correlation", + "predicted_truth_rank_correlation", + "hte_beats_oracle_constant", + "recovery_gate", + "crossfit_group", + "interference", + "persistence", + } + missing_summary = required_summary.difference(payload) + if missing_summary: + raise ValueError(f"HTE summary missing fields: {sorted(missing_summary)}") + if payload["crossfit_group"] != "geographic_randomization_cluster": + raise ValueError("HTE recovery must hold out geographic randomization clusters") + numeric_summary = { + key: float(payload[key]) + for key in ( + "rows", + "bias", + "rmse", + "fold_mean_cate_sd", + "known_truth_sd", + "oracle_constant_effect_rmse", + "predicted_truth_correlation", + "predicted_truth_rank_correlation", + "interference", + "persistence", + ) + } + if not all(np.isfinite(value) for value in numeric_summary.values()): + raise ValueError("HTE recovery summary contains non-finite diagnostics") + if numeric_summary["rows"] <= 0 or not numeric_summary["rows"].is_integer(): + raise ValueError("HTE recovery rows must be a positive integer") + if numeric_summary["interference"] != 0.0 or numeric_summary["persistence"] != 0.0: + raise ValueError( + "HTE recovery is validated only with interference and persistence disabled" + ) + if not isinstance(payload["hte_beats_oracle_constant"], bool): + raise ValueError("HTE recovery gate must be a JSON boolean") + if payload["recovery_gate"] != "rmse_below_oracle_constant_effect_rmse": + raise ValueError("HTE recovery summary has an unsupported recovery gate") + expected_gate = ( + numeric_summary["rmse"] + < numeric_summary["oracle_constant_effect_rmse"] + ) + if payload["hte_beats_oracle_constant"] != expected_gate: + raise ValueError("HTE recovery gate is inconsistent with the supplied RMSE values") + if calibration_path is None or not Path(calibration_path).is_file(): + raise ValueError("HTE calibration artifact is required when an HTE summary is supplied") + if stability_path is None or not Path(stability_path).is_file(): + raise ValueError("HTE fold-stability artifact is required when an HTE summary is supplied") + + calibration = pd.read_csv(calibration_path) + calibration_required = { + "score_bin", + "mean_predicted_cate", + "mean_known_truth", + "mean_error", + "rmse", + "rows", + } + missing_calibration = calibration_required.difference(calibration.columns) + if missing_calibration or calibration.empty: + raise ValueError( + f"HTE calibration artifact missing columns: {sorted(missing_calibration)}" + ) + stability = pd.read_csv(stability_path) + stability_required = { + "crossfit_fold", + "mean_predicted_cate", + "mean_known_truth", + "mean_error", + "rmse", + "rows", + } + missing_stability = stability_required.difference(stability.columns) + if missing_stability or stability.empty: + raise ValueError( + f"HTE stability artifact missing columns: {sorted(missing_stability)}" + ) + expected_rows = int(numeric_summary["rows"]) + for label, frame in (("calibration", calibration), ("stability", stability)): + counts = pd.to_numeric(frame["rows"], errors="coerce") + numeric_columns = [ + "mean_predicted_cate", + "mean_known_truth", + "mean_error", + "rmse", + ] + numeric_values = frame[numeric_columns].apply(pd.to_numeric, errors="coerce") + if ( + counts.isna().any() + or int(counts.sum()) != expected_rows + or not np.isfinite(numeric_values.to_numpy(dtype=float)).all() + ): + raise ValueError(f"HTE {label} artifact has inconsistent rows or diagnostics") + recovery_conclusion = ( + "It clears the predeclared oracle-constant RMSE gate, but remains conditional on " + "this simulator." + if payload["hte_beats_oracle_constant"] + else "It does not beat the oracle constant-effect baseline and is not decision-ready." + ) + summary = ( + "The cross-fitted semi-synthetic HTE benchmark targets the aggregate " + "`controlled_zone_direct_effect` with geographic randomization clusters held " + f"out. Across {int(payload.get('rows', 0))} held-out rows, generated bias is " + f"{float(payload.get('bias', np.nan)):.4f} and RMSE is " + f"{float(payload.get('rmse', np.nan)):.4f}. The SD of fold-level mean CATE is " + f"{float(payload.get('fold_mean_cate_sd', np.nan)):.4f}. The oracle constant-effect " + f"RMSE is {float(payload.get('oracle_constant_effect_rmse', np.nan)):.4f}; Pearson " + f"and rank correlations with truth are " + f"{float(payload.get('predicted_truth_correlation', np.nan)):.4f} and " + f"{float(payload.get('predicted_truth_rank_correlation', np.nan)):.4f}. " + f"{recovery_conclusion} These are known-truth model-recovery diagnostics, not " + "public-data causal estimates." + ) + table = markdown_table( + calibration.sort_values("score_bin"), + [ + "score_bin", + "mean_predicted_cate", + "mean_known_truth", + "mean_error", + "rmse", + "rows", + ], + ) + return summary, table + + +def generate_report_bundle( + benchmark_path: str | Path, + *, + output_directory: str | Path, + policy_path: str | Path | None = None, + descriptive_path: str | Path | None = None, + calibration_path: str | Path | None = None, + failures_path: str | Path | None = None, + hte_summary_path: str | Path | None = None, + hte_calibration_path: str | Path | None = None, + hte_stability_path: str | Path | None = None, + nyc_full_validation_path: str | Path | None = None, + nyc_full_manifest_path: str | Path | None = None, + treatment_version_policy_path: str | Path | None = None, + treatment_version_policy_manifest_path: str | Path | None = None, + interference_summary_path: str | Path | None = None, + interference_manifest_path: str | Path | None = None, + nyc_simulation_anchor_path: str | Path | None = None, + nyc_simulation_anchor_manifest_path: str | Path | None = None, + nyc_benchmark_manifest_path: str | Path | None = None, + nyc_graph_benchmark_manifest_path: str | Path | None = None, + equilibrium_manifest_path: str | Path | None = None, + nyc_weather_manifest_path: str | Path | None = None, + nyc_events_manifest_path: str | Path | None = None, + nyc_income_manifest_path: str | Path | None = None, + target_estimand: str | None = None, +) -> dict[str, Path]: + """Generate technical, executive, and appendix artifacts from computed inputs.""" + + benchmark_file = Path(benchmark_path) + benchmark = pd.read_csv(benchmark_file) + _validate_benchmark(benchmark) + available_targets = sorted(benchmark["target_estimand"].dropna().astype(str).unique()) + selected_target = target_estimand or available_targets[0] + relevant = benchmark.loc[benchmark["target_estimand"] == selected_target].copy() + if relevant.empty: + raise ValueError(f"no benchmark rows target {selected_target!r}") + + recommendation, recommendation_text = _recommendation_status(benchmark, selected_target) + policy_table, policy_summary = _policy_table(policy_path) + treatment_version_evidence = _treatment_version_policy_status( + treatment_version_policy_path, + treatment_version_policy_manifest_path, + ) + treatment_version_summary = ( + treatment_version_evidence.summary + if treatment_version_evidence is not None + else ( + "Paired rider/driver/bundled policy sensitivity artifacts were not supplied; " + "no cross-version policy claim is issued." + ) + ) + treatment_version_table = ( + treatment_version_evidence.table + if treatment_version_evidence is not None + else "No treatment-version sensitivity table was available." + ) + interference_evidence = _interference_status( + interference_summary_path, + interference_manifest_path, + ) + interference_summary = ( + interference_evidence.summary + if interference_evidence is not None + else ( + "A verified exposure-aware benchmark was not supplied; no claim is issued " + "about recovery under mapped interference or treatment history." + ) + ) + interference_table = ( + interference_evidence.table + if interference_evidence is not None + else "No mapped-interference recovery table was available." + ) + descriptive_summary = _descriptive_status(descriptive_path) + nyc_full_evidence = _nyc_full_status( + nyc_full_validation_path, + nyc_full_manifest_path, + ) + nyc_full_summary = ( + nyc_full_evidence.summary + if nyc_full_evidence is not None + else ( + "Verified NYC full-month artifacts were not supplied; no full-month empirical " + "scale or laptop-resource claim is issued." + ) + ) + nyc_full_limitations = ( + nyc_full_evidence.limitations + if nyc_full_evidence is not None + else ( + "- No verified NYC full-month evidence was supplied to this report; the " + "bounded fixture remains the only empirical input represented here." + ) + ) + nyc_anchor_evidence = _nyc_anchor_status( + nyc_simulation_anchor_path, + nyc_simulation_anchor_manifest_path, + ) + nyc_anchor_summary = ( + nyc_anchor_evidence.summary + if nyc_anchor_evidence is not None + else ( + "A validated NYC simulation anchor was not supplied. Simulator scale and " + "heterogeneity parameters therefore remain disconnected from the full-month " + "descriptive bundle in this report." + ) + ) + nyc_anchor_limitations = ( + nyc_anchor_evidence.limitations + if nyc_anchor_evidence is not None + else "- No validated NYC semi-synthetic simulation anchor was supplied." + ) + nyc_benchmark_evidence = _nyc_informed_benchmark_status( + nyc_benchmark_manifest_path + ) + nyc_benchmark_summary = ( + nyc_benchmark_evidence.summary + if nyc_benchmark_evidence is not None + else ( + "A verified NYC-informed known-truth benchmark was not supplied; no claim " + "is issued about estimator recovery under NYC-anchored simulator scale." + ) + ) + nyc_benchmark_table = ( + nyc_benchmark_evidence.table + if nyc_benchmark_evidence is not None + else "No NYC-informed known-truth recovery table was available." + ) + nyc_benchmark_limitations = ( + nyc_benchmark_evidence.limitations + if nyc_benchmark_evidence is not None + else "- NYC-informed known-truth benchmark: not supplied." + ) + nyc_graph_evidence = _nyc_graph_status(nyc_graph_benchmark_manifest_path) + nyc_graph_summary = ( + nyc_graph_evidence.summary + if nyc_graph_evidence is not None + else ( + "A verified NYC OD-graph known-truth benchmark was not supplied; no claim " + "is issued about mapped exposure recovery on NYC graph geometry." + ) + ) + nyc_graph_table = ( + nyc_graph_evidence.table + if nyc_graph_evidence is not None + else "No NYC OD-graph recovery table was available." + ) + nyc_graph_limitations = ( + nyc_graph_evidence.limitations + if nyc_graph_evidence is not None + else "- NYC OD-graph known-truth benchmark: not supplied." + ) + equilibrium_evidence = _equilibrium_status(equilibrium_manifest_path) + equilibrium_summary = ( + equilibrium_evidence.summary + if equilibrium_evidence is not None + else ( + "A verified fixed-point equilibrium benchmark was not supplied; no " + "equilibrium, welfare, or market-clearing claim is issued." + ) + ) + equilibrium_table = ( + equilibrium_evidence.table + if equilibrium_evidence is not None + else "No fixed-point equilibrium ledger was available." + ) + equilibrium_limitations = ( + equilibrium_evidence.limitations + if equilibrium_evidence is not None + else "- Fixed-point equilibrium benchmark: not supplied." + ) + nyc_weather_evidence = _nyc_weather_status(nyc_weather_manifest_path) + nyc_weather_summary = ( + nyc_weather_evidence.summary + if nyc_weather_evidence is not None + else ( + "Verified NYC NOAA weather artifacts were not supplied; no weather-demand " + "association or weather-effect claim is issued." + ) + ) + nyc_weather_table = ( + nyc_weather_evidence.table + if nyc_weather_evidence is not None + else "No NYC NOAA weather association table was available." + ) + nyc_weather_limitations = ( + nyc_weather_evidence.limitations + if nyc_weather_evidence is not None + else "- NYC NOAA weather evidence: not supplied." + ) + nyc_events_evidence = _nyc_events_status(nyc_events_manifest_path) + nyc_events_summary = ( + nyc_events_evidence.summary + if nyc_events_evidence is not None + else ( + "Verified NYC calendar/event artifacts were not supplied; no permitted-event, " + "holiday, attendance, or event-effect claim is issued." + ) + ) + nyc_events_table = ( + nyc_events_evidence.table + if nyc_events_evidence is not None + else "No NYC calendar/event association table was available." + ) + nyc_events_limitations = ( + nyc_events_evidence.limitations + if nyc_events_evidence is not None + else "- NYC official-calendar and permitted-event evidence: not supplied." + ) + nyc_income_evidence = _nyc_income_status(nyc_income_manifest_path) + nyc_income_summary = ( + nyc_income_evidence.summary + if nyc_income_evidence is not None + else ( + "Verified NYC neighborhood-income artifacts were not supplied; no high/low-" + "income-area heterogeneity or income-effect claim is issued." + ) + ) + nyc_income_table = ( + nyc_income_evidence.table + if nyc_income_evidence is not None + else "No NYC neighborhood-income descriptive table was available." + ) + nyc_income_limitations = ( + nyc_income_evidence.limitations + if nyc_income_evidence is not None + else "- NYC neighborhood-income evidence: not supplied." + ) + hte_summary, hte_table = _hte_status( + hte_summary_path, + hte_calibration_path, + hte_stability_path, + ) + benchmark_columns = [ + column + for column in ( + "scenario", + "varied_dimension", + "treatment_version", + "spillover_strength", + "persistence", + "treatment_duration", + "washout_periods", + "treatment_saturation", + "configured_geo_clusters", + "cluster_size", + "n_zones", + "budget", + "budget_binding_rate", + "design", + "estimator", + "identified", + "inference_valid", + "fit_complete", + "applicable", + "applicability_reason", + "attempted_fits", + "successful_fits", + "bias", + "diagnostic_mean_gap", + "rmse", + "coverage", + "power", + ) + if column in relevant + ] + benchmark_table = markdown_table( + relevant.sort_values(["scenario", "design", "estimator"]), + benchmark_columns, + ) + provenance = "\n".join( + [ + f"- Benchmark SHA-256: `{sha256_file(benchmark_file)}`", + _optional_hash(policy_path, "Policy"), + _optional_hash(descriptive_path, "Descriptive moments"), + _optional_hash(calibration_path, "Calibration"), + _optional_hash(failures_path, "Fit failures"), + _optional_hash(hte_summary_path, "HTE recovery summary"), + _optional_hash(hte_calibration_path, "HTE calibration"), + _optional_hash(hte_stability_path, "HTE fold stability"), + ( + nyc_full_evidence.provenance + if nyc_full_evidence is not None + else "- NYC full-month evidence: not supplied" + ), + ( + treatment_version_evidence.provenance + if treatment_version_evidence is not None + else "- Treatment-version policy sensitivity: not supplied" + ), + ( + interference_evidence.provenance + if interference_evidence is not None + else "- Exposure-aware interference benchmark: not supplied" + ), + ( + nyc_anchor_evidence.provenance + if nyc_anchor_evidence is not None + else "- NYC semi-synthetic simulation anchor: not supplied" + ), + ( + nyc_benchmark_evidence.provenance + if nyc_benchmark_evidence is not None + else "- NYC-informed known-truth benchmark: not supplied" + ), + ( + nyc_graph_evidence.provenance + if nyc_graph_evidence is not None + else "- NYC OD-graph known-truth benchmark: not supplied" + ), + ( + equilibrium_evidence.provenance + if equilibrium_evidence is not None + else "- Fixed-point equilibrium benchmark: not supplied" + ), + ( + nyc_weather_evidence.provenance + if nyc_weather_evidence is not None + else "- NYC NOAA weather evidence: not supplied" + ), + ( + nyc_events_evidence.provenance + if nyc_events_evidence is not None + else "- NYC official-calendar and permitted-event evidence: not supplied" + ), + ( + nyc_income_evidence.provenance + if nyc_income_evidence is not None + else "- NYC neighborhood-income evidence: not supplied" + ), + ] + ) + fit_failures = ( + int(pd.to_numeric(relevant["failed_fits"], errors="coerce").fillna(0).sum()) + if "failed_fits" in relevant + else 0 + ) + fit_failure_label = _counted(fit_failures, "failed attempted fit") + identified_rows = ( + int(relevant["identified"].fillna(False).astype(bool).sum()) + if "identified" in relevant + else 0 + ) + valid_rows = ( + int(relevant["inference_valid"].fillna(False).astype(bool).sum()) + if "inference_valid" in relevant + else 0 + ) + selection_details = ( + "No row passed the complete cross-scenario recommendation gate." + if recommendation is None + else ( + f"The displayed worst case is `{recommendation.get('scenario', '—')}` with " + f"generated RMSE {float(recommendation['rmse']):.4f}, coverage " + f"{float(recommendation['coverage']):.4f}, and power " + f"{float(recommendation['power']):.4f}." + ) + ) + + technical = f"""# Generated Technical Report + +> Evidence separation: public trip quantities are empirical/descriptive; benchmark and policy quantities are semi-synthetic causal results under known simulator assumptions. No observational fare association is interpreted causally. + +## Target and decision gate + +Primary generated target: `{selected_target}`. + +{recommendation_text} + +{selection_details} + +## Public-data scale anchor + +{descriptive_summary} + +The calibration artifact is an illustrative scale anchor. Available drivers, behavioral response, spillovers, persistence, and welfare are not identified by the public fixture. + +### Verified NYC full-month descriptive evidence + +{nyc_full_summary} + +### Verified NYC NOAA weather associations + +{nyc_weather_summary} + +{nyc_weather_table} + +### Verified NYC calendar and permitted-event associations + +{nyc_events_summary} + +{nyc_events_table} + +### Verified NYC neighborhood-income heterogeneity + +{nyc_income_summary} + +{nyc_income_table} + +### NYC-informed semi-synthetic scale anchor + +{nyc_anchor_summary} + +### NYC-informed known-truth design benchmark + +{nyc_benchmark_summary} + +{nyc_benchmark_table} + +### NYC OD-graph mapped-interference benchmark + +{nyc_graph_summary} + +{nyc_graph_table} + +## Monte Carlo results + +The artifact contains {_counted(len(relevant), 'summary row')}; {identified_rows} pass the row-level identification screen, {valid_rows} pass the assignment-aware inference screen, and the fit ledger records {fit_failure_label}. Bias is populated only for rows whose estimate and structural truth share the declared target; other differences are labeled diagnostic gaps. + +{benchmark_table} + +### Exposure-aware interference recovery + +{interference_summary} + +{interference_table} + +## Theoretical fixed-point equilibrium benchmark + +{equilibrium_summary} + +{equilibrium_table} + +## Heterogeneous-effect recovery + +{hte_summary} + +{hte_table} + +## Honest-holdout policy evaluation + +{policy_table} + +{policy_summary} + +Each nonzero policy is re-evaluated through the marketplace simulator on unseen seeds. The policy learner does not fit on structural truth, and independent summation of unit effects is not used as the decision value. + +### Treatment-version policy sensitivity + +{treatment_version_summary} + +{treatment_version_table} + +## Identification and limitations + +- Interference and persistence are varied factorially, with additional one-at-a-time duration, cluster-count, saturation, washout, and shared-budget diagnostics; failure of a design in any declared scenario blocks a robust recommendation. +- Few-cluster or incorrectly clustered uncertainty is excluded from selection even when a point estimate is shown. +- The Chicago fixture is deterministic and nonrepresentative; it validates the pipeline but not transportability. +- The time-stratified fixture panel contains occupied cells only; absent zone-hours are unknown rather than zero-demand observations. +{nyc_full_limitations} +{nyc_anchor_limitations} +{nyc_weather_limitations} +{nyc_events_limitations} +{nyc_income_limitations} +{nyc_benchmark_limitations} +{nyc_graph_limitations} +{equilibrium_limitations} +- Simulator welfare and policy value are conditional on the configured reduced-form marketplace model. + +## Reproducibility inputs + +{provenance} + +This report was generated from the machine-readable artifacts above; numerical results are not embedded in the template. +""" + + executive = f"""# Generated Product Decision Memo + +## Decision + +{recommendation_text} + +{policy_summary} + +{treatment_version_summary} + +## Heterogeneity evidence + +{hte_summary} + +## Exposure-aware design evidence + +{interference_summary} + +### NYC OD-graph evidence + +{nyc_graph_summary} + +### NYC-informed known-truth recovery + +{nyc_benchmark_summary} + +## Theoretical equilibrium evidence + +{equilibrium_summary} + +## Success metric + +Use full-horizon incremental completed trips, modeled contribution, and credible welfare per incremental dollar as decision metrics. Track wait time, rider service, driver earnings/utilization, geographic displacement, compliance, and budget delivery as guardrails. + +## Experiment conditions + +The primary causal target is `{selected_target}` over a fixed all-zone, full-horizon population. Duration, block size, and washout must be predeclared from persistence sensitivity and operational constraints; they are not chosen from observational public-trip associations. + +## Go/no-go rule + +Proceed to an operational pilot only after assignment integrity, exposure logging, enough effective randomized clusters, valid uncertainty, budget feasibility, and holdout policy stability are demonstrated. If no candidate passes every declared scenario, the generated decision is **no robust rollout recommendation**. + +## Evidence boundary + +Public data provide descriptive demand, fare, geography, and measurement-quality facts only. All causal performance values here are semi-synthetic and require validation in a properly randomized live experiment before launch. + +## Verified NYC full-month descriptive evidence + +{nyc_full_summary} + +## Verified NYC NOAA weather associations + +{nyc_weather_summary} + +## Verified NYC calendar and permitted-event associations + +{nyc_events_summary} + +## Verified NYC neighborhood-income heterogeneity + +{nyc_income_summary} + +## NYC-informed semi-synthetic scale anchor + +{nyc_anchor_summary} + +## Reproducibility inputs + +{provenance} +""" + + appendix = f"""# Generated Decision Appendix + +## Selected estimand + +`{selected_target}` + +## Recommendation gate + +{recommendation_text} + +## Benchmark table + +{benchmark_table} + +## Exposure-aware interference recovery + +{interference_summary} + +{interference_table} + +## NYC-informed known-truth design benchmark + +{nyc_benchmark_summary} + +{nyc_benchmark_table} + +## NYC OD-graph mapped-interference benchmark + +{nyc_graph_summary} + +{nyc_graph_table} + +## Theoretical fixed-point equilibrium benchmark + +{equilibrium_summary} + +{equilibrium_table} + +## Policy table + +{policy_table} + +## Treatment-version policy sensitivity + +{treatment_version_summary} + +{treatment_version_table} + +## HTE known-truth recovery + +{hte_summary} + +{hte_table} + +## Verified NYC full-month descriptive evidence + +{nyc_full_summary} + +## Verified NYC NOAA weather associations + +{nyc_weather_summary} + +{nyc_weather_table} + +## Verified NYC calendar and permitted-event associations + +{nyc_events_summary} + +{nyc_events_table} + +## Verified NYC neighborhood-income heterogeneity + +{nyc_income_summary} + +{nyc_income_table} + +## NYC-informed semi-synthetic scale anchor + +{nyc_anchor_summary} + +## Input hashes + +{provenance} +""" + + destination = Path(output_directory) + destination.mkdir(parents=True, exist_ok=True) + paths = { + "technical": destination / "technical_report_generated.md", + "executive": destination / "product_decision_memo_generated.md", + "appendix": destination / "generated_decision_appendix.md", + } + paths["technical"].write_text(technical, encoding="utf-8") + paths["executive"].write_text(executive, encoding="utf-8") + paths["appendix"].write_text(appendix, encoding="utf-8") + return paths diff --git a/CasualLab/src/casuallab/heterogeneity.py b/CasualLab/src/casuallab/heterogeneity.py new file mode 100644 index 0000000000000000000000000000000000000000..26bc1a8b74389bf4d9bbcf7b4f8b9fa05b2a8b1e --- /dev/null +++ b/CasualLab/src/casuallab/heterogeneity.py @@ -0,0 +1,169 @@ +"""Transparent heterogeneous-effect summaries and a cross-fitted S-learner.""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass + +import numpy as np +import pandas as pd +from sklearn.ensemble import RandomForestRegressor +from sklearn.model_selection import GroupKFold, KFold + +DEFAULT_HTE_FEATURES = ( + "baseline_demand", + "market_tightness", + "hour_sin", + "hour_cos", +) + + +@dataclass(frozen=True) +class HTEResult: + predictions: pd.DataFrame + feature_importance: pd.DataFrame + method: str + evidence_type: str = "model_based_conditional_contrast" + + +def cross_fitted_s_learner( + data: pd.DataFrame, + *, + outcome: str = "outcome", + treatment: str = "assigned_treatment", + features: Sequence[str] = DEFAULT_HTE_FEATURES, + group: str | None = None, + folds: int = 5, + trees: int = 160, + min_samples_leaf: int = 10, + seed: int = 202503, + evidence_type: str = "model_based_conditional_contrast", +) -> HTEResult: + """Estimate conditional contrasts with honest cross-fitted predictions. + + This benchmark follows simpler aggregate estimators in the method ladder. It is + not used as evidence that a causal forest is necessary or superior. If a cluster + column is supplied, entire clusters are held out together. + """ + + required = {outcome, treatment, *features} + if group is not None: + required.add(group) + missing = required.difference(data.columns) + if missing: + raise ValueError(f"HTE data missing columns: {sorted(missing)}") + if len(data) < 2 * folds: + raise ValueError("HTE data need at least two rows per fold") + if folds < 2: + raise ValueError("folds must be at least 2") + if trees < 10: + raise ValueError("trees must be at least 10") + + frame = data.reset_index(drop=True).copy() + numeric_columns = [outcome, treatment, *features] + numeric = frame[numeric_columns].apply(pd.to_numeric, errors="coerce") + if not np.isfinite(numeric.to_numpy(dtype=float)).all(): + raise ValueError("HTE outcome, treatment, and features must be finite") + treatment_values = numeric[treatment].to_numpy(dtype=float) + if ((treatment_values < 0) | (treatment_values > 1)).any(): + raise ValueError("treatment must lie in [0, 1]") + if np.ptp(treatment_values) <= 1e-12: + raise ValueError("treatment must vary") + + if group is None: + splitter = KFold(n_splits=folds, shuffle=True, random_state=seed) + splits = splitter.split(frame) + else: + unique_groups = frame[group].nunique() + if unique_groups < folds: + raise ValueError("number of cross-fitting groups must be at least folds") + splitter = GroupKFold(n_splits=folds) + splits = splitter.split(frame, groups=frame[group]) + + cate = np.full(len(frame), np.nan, dtype=float) + y1 = np.full(len(frame), np.nan, dtype=float) + y0 = np.full(len(frame), np.nan, dtype=float) + fold_id = np.full(len(frame), -1, dtype=int) + importances: list[np.ndarray] = [] + model_columns = [*features, treatment] + for fold, (train_indices, test_indices) in enumerate(splits): + train = numeric.iloc[train_indices] + test = numeric.iloc[test_indices] + if np.ptp(train[treatment].to_numpy(dtype=float)) <= 1e-12: + raise ValueError(f"treatment does not vary in training fold {fold}") + model = RandomForestRegressor( + n_estimators=trees, + min_samples_leaf=min_samples_leaf, + max_depth=8, + max_features="sqrt", + random_state=seed + fold, + n_jobs=1, + ) + model.fit(train[model_columns], train[outcome]) + treated_features = test[model_columns].copy() + control_features = test[model_columns].copy() + treated_features[treatment] = 1.0 + control_features[treatment] = 0.0 + y1[test_indices] = model.predict(treated_features) + y0[test_indices] = model.predict(control_features) + cate[test_indices] = y1[test_indices] - y0[test_indices] + fold_id[test_indices] = fold + importances.append(model.feature_importances_) + + if not np.isfinite(cate).all() or (fold_id < 0).any(): + raise AssertionError("cross-fitting did not produce every holdout prediction") + predictions = frame[[column for column in ("unit_id", "zone_id", "period_id") if column in frame]].copy() + predictions["predicted_y1"] = y1 + predictions["predicted_y0"] = y0 + predictions["estimated_cate"] = cate + predictions["crossfit_fold"] = fold_id + predictions["evidence_type"] = evidence_type + importance = pd.DataFrame( + { + "feature": model_columns, + "mean_importance": np.vstack(importances).mean(axis=0), + "importance_sd_across_folds": np.vstack(importances).std(axis=0, ddof=1), + "evidence_type": "model_diagnostic", + } + ).sort_values("mean_importance", ascending=False, ignore_index=True) + return HTEResult( + predictions, + importance, + method="cross_fitted_random_forest_s_learner", + evidence_type=evidence_type, + ) + + +def subgroup_effect_summary( + data: pd.DataFrame, + estimated_cate: Sequence[float] | pd.Series, + *, + modifier: str, + bins: int = 4, +) -> pd.DataFrame: + """Summarize predicted heterogeneity across pre-treatment modifier bins.""" + + if modifier not in data: + raise ValueError(f"modifier {modifier!r} is missing") + if bins < 2: + raise ValueError("bins must be at least 2") + values = pd.to_numeric(data[modifier], errors="coerce") + cate = np.asarray(estimated_cate, dtype=float) + if len(cate) != len(data): + raise ValueError("estimated_cate must align with data") + if not np.isfinite(cate).all(): + raise ValueError("estimated_cate must be finite") + valid = values.notna() + if valid.sum() < bins: + raise ValueError("too few observed modifier values for requested bins") + labels = pd.qcut(values.loc[valid], q=bins, duplicates="drop") + summary = ( + pd.DataFrame({"modifier_bin": labels, "estimated_cate": cate[valid.to_numpy()]}) + .groupby("modifier_bin", observed=True)["estimated_cate"] + .agg(mean_estimated_cate="mean", sd_estimated_cate="std", rows="size") + .reset_index() + ) + summary.insert(0, "modifier", modifier) + summary["modifier_bin"] = summary["modifier_bin"].astype(str) + summary["evidence_type"] = "model_based_conditional_contrast_summary" + return summary diff --git a/CasualLab/src/casuallab/interference.py b/CasualLab/src/casuallab/interference.py new file mode 100644 index 0000000000000000000000000000000000000000..541f1c1c3fac4da17b1272f0f7117079c13f7ce6 --- /dev/null +++ b/CasualLab/src/casuallab/interference.py @@ -0,0 +1,412 @@ +"""Design and estimation helpers for mapped marketplace interference. + +The canonical marketplace benchmark deliberately withholds a full-policy recommendation +when a plain assignment coefficient does not identify the all-market policy contrast. This +module supplies a narrower, explicit alternative: randomize geographic clusters to treatment +saturations, map neighboring exposure with pre-treatment weights, and estimate controlled +own/neighbor exposure-response slopes. Those slopes are *not* relabeled as the full-policy +market-total effect. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from hashlib import sha256 +from math import isclose, isfinite +from numbers import Integral +from typing import Any + +import numpy as np +import pandas as pd +import statsmodels.api as sm +from scipy.stats import t as student_t + + +@dataclass(frozen=True, slots=True) +class TwoStageSaturationConfig: + """Configuration for a geographic two-stage saturation experiment. + + Stage one assigns geographic clusters to one of ``saturation_levels`` using a + balanced complete randomization. Stage two independently assigns the configured + number of opportunities inside each zone-period cell at that cluster's saturation. + Aggregate cells therefore retain a transparent randomized treated share. + """ + + n_clusters: int = 8 + individuals_per_cell: int = 100 + saturation_levels: tuple[float, ...] = (0.0, 0.5, 1.0) + saturation_probabilities: tuple[float, ...] | None = None + seed: int = 202503 + + def __post_init__(self) -> None: + for name, value in { + "n_clusters": self.n_clusters, + "individuals_per_cell": self.individuals_per_cell, + "seed": self.seed, + }.items(): + if isinstance(value, bool) or not isinstance(value, Integral): + raise ValueError(f"{name} must be an integer") + if self.n_clusters < 2: + raise ValueError("n_clusters must be at least two") + if self.individuals_per_cell < 1: + raise ValueError("individuals_per_cell must be positive") + levels = tuple(float(value) for value in self.saturation_levels) + if len(levels) < 2 or len(set(levels)) != len(levels): + raise ValueError("saturation_levels must contain at least two unique values") + if any(not isfinite(value) or not 0 <= value <= 1 for value in levels): + raise ValueError("saturation_levels must lie in [0, 1]") + if self.n_clusters < len(levels): + raise ValueError("n_clusters must be at least the number of saturation levels") + object.__setattr__(self, "saturation_levels", levels) + + if self.saturation_probabilities is None: + return + probabilities = tuple(float(value) for value in self.saturation_probabilities) + if len(probabilities) != len(levels): + raise ValueError("saturation_probabilities must align with saturation_levels") + if any(not isfinite(value) or value <= 0 for value in probabilities): + raise ValueError("saturation_probabilities must be finite and positive") + if not isclose(sum(probabilities), 1.0, rel_tol=0.0, abs_tol=1e-9): + raise ValueError("saturation_probabilities must sum to one") + object.__setattr__(self, "saturation_probabilities", probabilities) + + +@dataclass(frozen=True, slots=True) +class ExposureMappingConfig: + """Column and inference contract for a mapped exposure-response regression.""" + + outcome: str = "outcome" + own_exposure: str = "treatment" + neighbor_exposure: str = "neighbor_exposure" + history_exposure: str | None = "history_exposure" + cluster: str = "randomization_cluster" + covariates: tuple[str, ...] = () + alpha: float = 0.05 + minimum_inference_clusters: int = 8 + + def __post_init__(self) -> None: + if not 0 < self.alpha < 1: + raise ValueError("alpha must lie strictly between zero and one") + if ( + isinstance(self.minimum_inference_clusters, bool) + or not isinstance(self.minimum_inference_clusters, Integral) + or self.minimum_inference_clusters < 2 + ): + raise ValueError("minimum_inference_clusters must be an integer of at least two") + if len({self.own_exposure, self.neighbor_exposure}) != 2: + raise ValueError("own and neighbor exposure columns must be distinct") + if self.history_exposure in {self.own_exposure, self.neighbor_exposure}: + raise ValueError("history exposure must be distinct from current exposures") + + +def _balanced_arm_counts(n_clusters: int, probabilities: np.ndarray) -> np.ndarray: + """Return positive fixed arm counts with largest-remainder allocation.""" + + raw = probabilities * n_clusters + counts = np.floor(raw).astype(int) + counts[counts == 0] = 1 + while int(counts.sum()) > n_clusters: + candidates = np.flatnonzero(counts > 1) + if not len(candidates): + raise ValueError("not enough clusters to represent every saturation arm") + remove = candidates[np.argmax(counts[candidates] - raw[candidates])] + counts[remove] -= 1 + while int(counts.sum()) < n_clusters: + add = int(np.argmax(raw - counts)) + counts[add] += 1 + return counts + + +def two_stage_saturation_assignment( + units: pd.DataFrame, + config: TwoStageSaturationConfig | None = None, +) -> pd.DataFrame: + """Generate a deterministic two-stage geographic saturation assignment. + + The input must contain one row per ``zone_id`` × ``period_id`` cell. Geographic + clusters are deterministic functions of sorted zone IDs; cluster saturation arms + and within-cell opportunity assignments are randomized with the recorded seed. + """ + + cfg = config or TwoStageSaturationConfig() + if not isinstance(units, pd.DataFrame): + raise TypeError("units must be a pandas DataFrame") + required = {"zone_id", "period_id"} + missing = required.difference(units.columns) + if missing: + raise ValueError(f"assignment units missing columns: {sorted(missing)}") + frame = units.copy().reset_index(drop=True) + if frame.empty: + raise ValueError("assignment units must not be empty") + if frame[["zone_id", "period_id"]].isna().any().any(): + raise ValueError("zone_id and period_id cannot contain missing values") + if frame.duplicated(["zone_id", "period_id"]).any(): + raise ValueError("assignment units must be unique by zone_id and period_id") + + zones = np.asarray(sorted(frame["zone_id"].unique())) + if cfg.n_clusters > len(zones): + raise ValueError("n_clusters cannot exceed the number of observed zones") + cluster_rank = np.floor(np.arange(len(zones)) * cfg.n_clusters / len(zones)).astype(int) + zone_to_cluster = dict(zip(zones.tolist(), cluster_rank.tolist(), strict=True)) + frame["cluster_id"] = frame["zone_id"].map(zone_to_cluster).astype(int) + + levels = np.asarray(cfg.saturation_levels, dtype=float) + probabilities = ( + np.full(len(levels), 1.0 / len(levels), dtype=float) + if cfg.saturation_probabilities is None + else np.asarray(cfg.saturation_probabilities, dtype=float) + ) + arm_counts = _balanced_arm_counts(cfg.n_clusters, probabilities) + saturation_arms = np.repeat(levels, arm_counts) + rng = np.random.default_rng(cfg.seed) + saturation_arms = saturation_arms[rng.permutation(cfg.n_clusters)] + cluster_to_saturation = dict(enumerate(saturation_arms.tolist())) + realized_stage_one_probability = { + float(level): float(count / cfg.n_clusters) + for level, count in zip(levels, arm_counts, strict=True) + } + frame["cluster_saturation"] = frame["cluster_id"].map(cluster_to_saturation).astype(float) + frame["saturation_arm"] = frame["cluster_saturation"] + frame["saturation_assignment_probability"] = frame["cluster_saturation"].map( + realized_stage_one_probability + ) + frame["unit_count"] = int(cfg.individuals_per_cell) + frame["treated_units"] = rng.binomial( + cfg.individuals_per_cell, + frame["cluster_saturation"].to_numpy(dtype=float), + ) + frame["assigned_treatment"] = frame["treated_units"] / cfg.individuals_per_cell + frame["treatment"] = frame["assigned_treatment"] + frame["treatment_intensity"] = frame["treatment"] + frame["treatment_probability"] = frame["cluster_saturation"] + frame["planned_treatment"] = frame["treatment"] + frame["randomization_cluster"] = "saturation_geo_" + frame["cluster_id"].astype(str) + frame["design"] = "two_stage_saturation" + frame["assignment_seed"] = int(cfg.seed) + frame["analysis_eligible"] = 1 + frame["washout"] = 0 + frame["evidence_type"] = "randomized_design_assignment" + return frame + + +def _mapping_digest(edges: pd.DataFrame) -> str: + records = edges.sort_values(["focal_zone_id", "neighbor_zone_id"]).to_dict("records") + payload = json.dumps(records, sort_keys=True, separators=(",", ":"), default=str) + return sha256(payload.encode("utf-8")).hexdigest() + + +def add_mapped_exposures( + assignments: pd.DataFrame, + edges: pd.DataFrame, + *, + zone_column: str = "zone_id", + time_column: str = "period_id", + treatment_column: str = "treatment", + history_lags: int = 0, +) -> pd.DataFrame: + """Attach normalized neighbor and exact-lag own-treatment exposures. + + ``edges`` must contain ``focal_zone_id``, ``neighbor_zone_id``, and nonnegative + ``weight``. Weights are normalized within focal zone. A focal zone with no mapped + neighbors receives a missing exposure—not a fabricated zero. Exact lag support is + obtained by key joins, so gaps in the time index are never treated as adjacent. + """ + + if not isinstance(assignments, pd.DataFrame) or not isinstance(edges, pd.DataFrame): + raise TypeError("assignments and edges must be pandas DataFrames") + if isinstance(history_lags, bool) or not isinstance(history_lags, Integral) or history_lags < 0: + raise ValueError("history_lags must be a non-negative integer") + required_assignment = {zone_column, time_column, treatment_column} + missing_assignment = required_assignment.difference(assignments.columns) + if missing_assignment: + raise ValueError(f"assignment data missing columns: {sorted(missing_assignment)}") + required_edges = {"focal_zone_id", "neighbor_zone_id", "weight"} + missing_edges = required_edges.difference(edges.columns) + if missing_edges: + raise ValueError(f"exposure map missing columns: {sorted(missing_edges)}") + frame = assignments.copy().reset_index(drop=True) + if frame.duplicated([zone_column, time_column]).any(): + raise ValueError("assignment data must be unique by zone and time") + try: + treatment = frame[treatment_column].to_numpy(dtype=float) + periods = frame[time_column].to_numpy(dtype=int) + except (TypeError, ValueError) as exc: + raise ValueError("treatment and time columns must be numeric") from exc + if not np.isfinite(treatment).all(): + raise ValueError("treatment must be finite") + if not np.allclose(periods, frame[time_column].to_numpy(dtype=float)): + raise ValueError("time values must be integer-like for exact-lag mapping") + + mapping = edges[["focal_zone_id", "neighbor_zone_id", "weight"]].copy() + if mapping.empty: + raise ValueError("exposure map must not be empty") + if mapping.duplicated(["focal_zone_id", "neighbor_zone_id"]).any(): + raise ValueError("exposure map must be unique by focal-neighbor pair") + weights = pd.to_numeric(mapping["weight"], errors="coerce") + if weights.isna().any() or (weights < 0).any() or not np.isfinite(weights).all(): + raise ValueError("exposure-map weights must be finite and non-negative") + if (mapping["focal_zone_id"] == mapping["neighbor_zone_id"]).any(): + raise ValueError("neighbor exposure map must not contain self edges") + mapping["weight"] = weights.astype(float) + weight_sum = mapping.groupby("focal_zone_id")["weight"].transform("sum") + if (weight_sum <= 0).any(): + raise ValueError("every mapped focal zone must have positive total neighbor weight") + mapping["normalized_weight"] = mapping["weight"] / weight_sum + + neighbor_values = frame[[zone_column, time_column, treatment_column]].rename( + columns={zone_column: "neighbor_zone_id", treatment_column: "neighbor_treatment"} + ) + expanded = mapping.merge(neighbor_values, on="neighbor_zone_id", how="left", validate="m:m") + expanded["weighted_neighbor_treatment"] = ( + expanded["normalized_weight"] * expanded["neighbor_treatment"] + ) + exposure = ( + expanded.groupby(["focal_zone_id", time_column], as_index=False) + .agg( + neighbor_exposure=("weighted_neighbor_treatment", "sum"), + mapped_neighbor_count=("neighbor_treatment", "count"), + mapped_neighbor_weight=("normalized_weight", "sum"), + ) + .rename(columns={"focal_zone_id": zone_column}) + ) + expected_neighbors = mapping.groupby("focal_zone_id")["neighbor_zone_id"].nunique() + exposure["expected_neighbor_count"] = exposure[zone_column].map(expected_neighbors) + incomplete = exposure["mapped_neighbor_count"] != exposure["expected_neighbor_count"] + exposure.loc[incomplete, ["neighbor_exposure", "mapped_neighbor_weight"]] = np.nan + result = frame.merge(exposure, on=[zone_column, time_column], how="left", validate="1:1") + + result["history_support"] = 0 + lag_columns: list[str] = [] + for lag in range(1, int(history_lags) + 1): + lag_name = f"own_history_lag_{lag}" + prior = frame[[zone_column, time_column, treatment_column]].copy() + prior[time_column] = prior[time_column].astype(int) + lag + prior = prior.rename(columns={treatment_column: lag_name}) + result = result.merge(prior, on=[zone_column, time_column], how="left", validate="1:1") + lag_columns.append(lag_name) + if lag_columns: + result["history_support"] = result[lag_columns].notna().sum(axis=1) + result["history_exposure"] = result[lag_columns].mean(axis=1, skipna=False) + else: + result["history_exposure"] = np.nan + result["exposure_mapping_id"] = _mapping_digest(mapping) + result["exposure_mapping_evidence"] = "pre_treatment_user_supplied_weight_map" + return result + + +def estimate_exposure_response( + data: pd.DataFrame, + config: ExposureMappingConfig | None = None, +) -> pd.DataFrame: + """Estimate controlled own and neighbor exposure-response slopes jointly. + + The returned rows name controlled exposure-response targets. They do not identify + the all-zone policy effect unless an external identification argument supplies that + bridge. Cluster-robust CR1/t inference follows the supplied randomization cluster. + """ + + cfg = config or ExposureMappingConfig() + if not isinstance(data, pd.DataFrame): + raise TypeError("data must be a pandas DataFrame") + exposure_terms = [cfg.own_exposure, cfg.neighbor_exposure] + if cfg.history_exposure is not None: + if cfg.history_exposure not in data.columns: + raise ValueError( + "exposure estimator data missing configured history column: " + f"{cfg.history_exposure!r}; set history_exposure=None only when history " + "is deliberately excluded from the estimand" + ) + exposure_terms.append(cfg.history_exposure) + required = [cfg.outcome, cfg.cluster, *exposure_terms, *cfg.covariates] + missing = set(required).difference(data.columns) + if missing: + raise ValueError(f"exposure estimator data missing columns: {sorted(missing)}") + frame = data.dropna(subset=list(dict.fromkeys(required))).copy() + if frame.empty: + raise ValueError("no complete exposure-mapped observations remain") + mapping_ids = ( + sorted(frame["exposure_mapping_id"].dropna().astype(str).unique().tolist()) + if "exposure_mapping_id" in frame + else [] + ) + if len(mapping_ids) > 1: + raise ValueError( + "exposure estimator requires one predeclared exposure mapping; " + f"found {len(mapping_ids)} exposure_mapping_id values" + ) + + numeric = frame[[cfg.outcome, *exposure_terms]].apply(pd.to_numeric, errors="coerce") + if numeric.isna().any().any() or not np.isfinite(numeric.to_numpy(dtype=float)).all(): + raise ValueError("outcome and exposure columns must be finite numeric values") + covariates = ( + pd.get_dummies(frame[list(cfg.covariates)], drop_first=True, dtype=float) + if cfg.covariates + else pd.DataFrame(index=frame.index) + ) + if not np.isfinite(covariates.to_numpy(dtype=float)).all(): + raise ValueError("covariates must be finite") + design = pd.concat([numeric[exposure_terms], covariates], axis=1).astype(float) + design = sm.add_constant(design, has_constant="add") + matrix = design.to_numpy(dtype=float) + if np.linalg.matrix_rank(matrix) < matrix.shape[1]: + raise ValueError("mapped exposure design matrix is rank deficient") + groups = frame[cfg.cluster] + n_clusters = int(groups.nunique()) + if n_clusters < 2: + raise ValueError("cluster-aware exposure inference requires at least two clusters") + fit = sm.OLS(numeric[cfg.outcome], design).fit( + cov_type="cluster", + cov_kwds={"groups": groups, "use_correction": True}, + use_t=True, + ) + degrees_freedom = n_clusters - 1 + critical = float(student_t.ppf(1.0 - cfg.alpha / 2.0, degrees_freedom)) + target_for_term = { + cfg.own_exposure: "controlled_zone_direct_effect", + cfg.neighbor_exposure: "spillover_effect", + } + if cfg.history_exposure is not None: + target_for_term[cfg.history_exposure] = "controlled_history_exposure_response" + rows: list[dict[str, Any]] = [] + for term in exposure_terms: + estimate = float(fit.params[term]) + standard_error = float(fit.bse[term]) + statistic = estimate / standard_error if standard_error > 0 else np.inf + rows.append( + { + "method": "exposure_mapped_cluster_regression", + "exposure_term": term, + "target_estimand": target_for_term[term], + "estimate": estimate, + "standard_error": standard_error, + "ci_low": estimate - critical * standard_error, + "ci_high": estimate + critical * standard_error, + "p_value": float(2.0 * student_t.sf(abs(statistic), degrees_freedom)), + "n_obs": int(fit.nobs), + "n_clusters": n_clusters, + "degrees_freedom": degrees_freedom, + "inference_valid": n_clusters >= cfg.minimum_inference_clusters, + "minimum_inference_clusters": int(cfg.minimum_inference_clusters), + "variance_estimator": "CR1 cluster-t", + "effect_scale": "per-unit exposure slope; not the full-policy market total", + "identification_scope": ( + "conditional on randomized support, a correct pre-treatment exposure map, " + "and no unmapped interference or omitted exposure history" + ), + "evidence_type": "exposure_mapped_response_conditional_on_design_validity", + "mapping_ids": mapping_ids, + "covariates": list(cfg.covariates), + "r_squared": float(fit.rsquared), + } + ) + return pd.DataFrame(rows) + + +__all__ = [ + "ExposureMappingConfig", + "TwoStageSaturationConfig", + "add_mapped_exposures", + "estimate_exposure_response", + "two_stage_saturation_assignment", +] diff --git a/CasualLab/src/casuallab/interference_benchmark.py b/CasualLab/src/casuallab/interference_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..17f1b9e5d45e0fde1aa0ce68b2f63046dbd1f1c1 --- /dev/null +++ b/CasualLab/src/casuallab/interference_benchmark.py @@ -0,0 +1,679 @@ +"""Known-truth benchmark for exposure-aware marketplace estimation. + +This module deliberately targets a narrower question than the full marketplace +simulator: can a predeclared two-stage saturation design recover controlled own, +neighbor, and lagged exposure-response slopes when the exposure map is correct? +The data-generating process is transparent and additive so every target is known. + +A naive coefficient on the stage-one saturation arm is also recorded. It is a +randomized assignment diagnostic, but it is not relabeled as the all-market policy +effect when neighbor exposure and treatment history are omitted. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import asdict, dataclass +from math import isfinite +from numbers import Integral, Real +from typing import Any, Final + +import numpy as np +import pandas as pd + +from .benchmark import summarize_monte_carlo +from .config import EstimatorConfig +from .estimators import cluster_robust +from .interference import ( + ExposureMappingConfig, + TwoStageSaturationConfig, + add_mapped_exposures, + estimate_exposure_response, + two_stage_saturation_assignment, +) + +MAPPED_TARGETS: Final[Mapping[str, str]] = { + "treatment": "controlled_zone_direct_effect", + "neighbor_exposure": "spillover_effect", + "history_exposure": "controlled_history_exposure_response", +} + +ESTIMAND_DEFINITIONS: Final[Mapping[str, str]] = { + "controlled_zone_direct_effect": ( + "Per-unit own-treatment response holding mapped neighbor and lagged exposure fixed." + ), + "spillover_effect": ( + "Per-unit response to the predeclared mapped-neighbor exposure holding own and " + "lagged exposure fixed." + ), + "controlled_history_exposure_response": ( + "Per-unit response to the exact-lag own-treatment history holding current own and " + "mapped-neighbor exposure fixed." + ), + "market_total_effect": ( + "Full-horizon all-zone treatment versus all-zero under the benchmark's additive " + "exposure mapping and startup history convention." + ), +} + + +@dataclass(frozen=True, slots=True) +class InterferenceBenchmarkConfig: + """Laptop-safe configuration for the mapped-exposure Monte Carlo benchmark. + + The benchmark uses one randomized geographic cluster per zone. This makes the + ring exposure map cross randomized arms and keeps cluster counts unambiguous. + Stage two randomizes individual opportunities within each zone-period cell. + """ + + replications: int = 24 + seed: int = 880_321 + n_zones: int = 32 + n_clusters: int = 32 + n_periods: int = 32 + individuals_per_cell: int = 20 + saturation_levels: tuple[float, ...] = (0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0) + history_lags: int = 1 + own_effect: float = 2.0 + neighbor_effect: float = 1.5 + history_effect: float = 0.7 + outcome_noise_sd: float = 0.08 + cluster_noise_sd: float = 0.04 + confidence_level: float = 0.95 + minimum_inference_clusters: int = 8 + + def __post_init__(self) -> None: + integer_values = { + "replications": self.replications, + "seed": self.seed, + "n_zones": self.n_zones, + "n_clusters": self.n_clusters, + "n_periods": self.n_periods, + "individuals_per_cell": self.individuals_per_cell, + "history_lags": self.history_lags, + "minimum_inference_clusters": self.minimum_inference_clusters, + } + for name, value in integer_values.items(): + if isinstance(value, bool) or not isinstance(value, Integral): + raise ValueError(f"{name} must be an integer") + if self.replications < 2: + raise ValueError("replications must be at least two") + if self.n_zones < 4: + raise ValueError("n_zones must be at least four for the two-neighbor ring") + if self.n_clusters != self.n_zones: + raise ValueError("this benchmark requires one randomized cluster per zone") + if self.n_periods <= self.history_lags + 1: + raise ValueError("n_periods must leave at least two complete history periods") + if self.individuals_per_cell < 1: + raise ValueError("individuals_per_cell must be positive") + if self.history_lags < 1: + raise ValueError("history_lags must be at least one") + if self.minimum_inference_clusters < 2: + raise ValueError("minimum_inference_clusters must be at least two") + if not 0.5 < self.confidence_level < 1.0: + raise ValueError("confidence_level must lie between 0.5 and 1") + + numeric_values = { + "own_effect": self.own_effect, + "neighbor_effect": self.neighbor_effect, + "history_effect": self.history_effect, + "outcome_noise_sd": self.outcome_noise_sd, + "cluster_noise_sd": self.cluster_noise_sd, + } + for name, value in numeric_values.items(): + if not isinstance(value, Real) or not isfinite(float(value)): + raise ValueError(f"{name} must be a finite number") + if self.outcome_noise_sd < 0 or self.cluster_noise_sd < 0: + raise ValueError("noise standard deviations must be non-negative") + + levels = tuple(float(value) for value in self.saturation_levels) + object.__setattr__(self, "saturation_levels", levels) + # Reuse the assignment contract as the canonical saturation validation. + TwoStageSaturationConfig( + n_clusters=self.n_clusters, + individuals_per_cell=self.individuals_per_cell, + saturation_levels=levels, + seed=self.seed, + ) + if not any(0.0 < level < 1.0 for level in levels): + raise ValueError( + "saturation_levels must include an interior arm to separate current " + "treatment from lagged history in this benchmark" + ) + + +@dataclass(frozen=True, slots=True) +class InterferenceEstimands: + """Known controlled slopes and the distinct full-policy market contrast.""" + + controlled_zone_direct_effect: float + spillover_effect: float + controlled_history_exposure_response: float + full_horizon_persistent_effect: float + market_total_effect: float + + def to_dict(self) -> dict[str, float]: + return { + name: float(value) + for name, value in asdict(self).items() + } + + +@dataclass(frozen=True) +class InterferenceBenchmarkResult: + """Replication records, fit audit, summaries, failures, and provenance.""" + + records: pd.DataFrame + summary: pd.DataFrame + fit_ledger: pd.DataFrame + failures: pd.DataFrame + metadata: Mapping[str, Any] + + +def known_interference_estimands( + config: InterferenceBenchmarkConfig | None = None, +) -> InterferenceEstimands: + """Return the benchmark truths without running a Monte Carlo simulation.""" + + cfg = config or InterferenceBenchmarkConfig() + supported_history_periods = cfg.n_periods - cfg.history_lags + persistent = cfg.history_effect * supported_history_periods / cfg.n_periods + return InterferenceEstimands( + controlled_zone_direct_effect=float(cfg.own_effect), + spillover_effect=float(cfg.neighbor_effect), + controlled_history_exposure_response=float(cfg.history_effect), + full_horizon_persistent_effect=float(persistent), + market_total_effect=float(cfg.own_effect + cfg.neighbor_effect + persistent), + ) + + +def _ring_edges(n_zones: int) -> pd.DataFrame: + focal = np.repeat(np.arange(n_zones), 2) + return pd.DataFrame( + { + "focal_zone_id": focal, + "neighbor_zone_id": np.column_stack( + [ + (np.arange(n_zones) - 1) % n_zones, + (np.arange(n_zones) + 1) % n_zones, + ] + ).reshape(-1), + "weight": 0.5, + } + ) + + +def _replication_seeds(seed: int, replications: int) -> tuple[tuple[int, int], ...]: + children = np.random.SeedSequence(seed).spawn(replications) + pairs: list[tuple[int, int]] = [] + for child in children: + state = child.generate_state(2, dtype=np.uint32) + pairs.append((int(state[0]), int(state[1]))) + return tuple(pairs) + + +def _simulate_exposure_dgp( + config: InterferenceBenchmarkConfig, + *, + assignment_seed: int, + outcome_seed: int, +) -> pd.DataFrame: + units = pd.MultiIndex.from_product( + [range(config.n_periods), range(config.n_zones)], + names=["period_id", "zone_id"], + ).to_frame(index=False) + assignment = two_stage_saturation_assignment( + units, + TwoStageSaturationConfig( + n_clusters=config.n_clusters, + individuals_per_cell=config.individuals_per_cell, + saturation_levels=config.saturation_levels, + seed=assignment_seed, + ), + ) + frame = add_mapped_exposures( + assignment, + _ring_edges(config.n_zones), + history_lags=config.history_lags, + ) + + zone_angle = 2.0 * np.pi * frame["zone_id"].to_numpy(dtype=float) / config.n_zones + period_angle = ( + 2.0 * np.pi * frame["period_id"].to_numpy(dtype=float) / config.n_periods + ) + frame["baseline_state"] = np.sin(zone_angle) + 0.25 * np.cos(2.0 * zone_angle) + frame["period_sin"] = np.sin(period_angle) + frame["period_cos"] = np.cos(period_angle) + + rng = np.random.default_rng(outcome_seed) + cluster_shocks = rng.normal(0.0, config.cluster_noise_sd, config.n_clusters) + history_for_outcome = frame["history_exposure"].fillna(0.0).to_numpy(dtype=float) + frame["outcome"] = ( + 8.0 + + 0.35 * frame["baseline_state"].to_numpy(dtype=float) + + 0.20 * frame["period_sin"].to_numpy(dtype=float) + - 0.15 * frame["period_cos"].to_numpy(dtype=float) + + cluster_shocks[frame["cluster_id"].to_numpy(dtype=int)] + + config.own_effect * frame["treatment"].to_numpy(dtype=float) + + config.neighbor_effect * frame["neighbor_exposure"].to_numpy(dtype=float) + + config.history_effect * history_for_outcome + + rng.normal(0.0, config.outcome_noise_sd, len(frame)) + ) + frame["dgp_evidence_type"] = "semi_synthetic_exposure_mapped_known_truth" + frame["assignment_seed"] = int(assignment_seed) + frame["outcome_seed"] = int(outcome_seed) + return frame + + +def _mapped_records( + frame: pd.DataFrame, + config: InterferenceBenchmarkConfig, + truths: InterferenceEstimands, + *, + replication: int, + assignment_seed: int, + outcome_seed: int, +) -> list[dict[str, Any]]: + estimates = estimate_exposure_response( + frame, + ExposureMappingConfig( + outcome="outcome", + own_exposure="treatment", + neighbor_exposure="neighbor_exposure", + history_exposure="history_exposure", + cluster="randomization_cluster", + covariates=("baseline_state", "period_sin", "period_cos"), + alpha=1.0 - config.confidence_level, + minimum_inference_clusters=config.minimum_inference_clusters, + ), + ) + truth_values = truths.to_dict() + records: list[dict[str, Any]] = [] + for estimate in estimates.to_dict("records"): + target = str(estimate["target_estimand"]) + truth = truth_values[target] + records.append( + { + **estimate, + "design": "two_stage_saturation", + "estimator": "exposure_mapped_cluster_regression", + "replication": replication, + "seed": assignment_seed, + "assignment_seed": assignment_seed, + "outcome_seed": outcome_seed, + "std_error": float(estimate["standard_error"]), + "truth": truth, + "market_total_truth": truths.market_total_effect, + "estimation_error": float(estimate["estimate"]) - truth, + "diagnostic_gap_to_market_total": np.nan, + "identified": True, + "comparison_status": "identified_controlled_exposure_response", + "coefficient_inference_cluster_aware": True, + "inference_valid_for_target": bool(estimate["inference_valid"]), + "controlled_exposure_not_market_total": True, + "fit_status": "ok", + "design_cost": float(config.n_zones * config.n_periods), + "evidence_type": "semi_synthetic_exposure_mapped_known_truth", + "estimand_definition": ESTIMAND_DEFINITIONS[target], + } + ) + return records + + +def _naive_record( + frame: pd.DataFrame, + config: InterferenceBenchmarkConfig, + truths: InterferenceEstimands, + *, + replication: int, + assignment_seed: int, + outcome_seed: int, +) -> dict[str, Any]: + estimate = cluster_robust( + frame, + EstimatorConfig( + method="cluster_robust", + outcome="outcome", + treatment="cluster_saturation", + covariates=("baseline_state", "period_sin", "period_cos"), + cluster="randomization_cluster", + target_estimand="market_total_effect", + alpha=1.0 - config.confidence_level, + ), + ) + return { + "method": "cluster_robust", + "exposure_term": "cluster_saturation", + "target_estimand": "market_total_effect", + "coefficient_estimand": "stage_one_saturation_assignment_slope", + "design": "two_stage_saturation", + "estimator": "naive_assignment_cluster_regression", + "replication": replication, + "seed": assignment_seed, + "assignment_seed": assignment_seed, + "outcome_seed": outcome_seed, + "estimate": estimate.estimate, + "standard_error": estimate.standard_error, + "std_error": estimate.standard_error, + "ci_low": estimate.ci_low, + "ci_high": estimate.ci_high, + "p_value": estimate.p_value, + "n_obs": estimate.n_obs, + "n_clusters": int(estimate.diagnostics["n_clusters"]), + "truth": truths.market_total_effect, + "market_total_truth": truths.market_total_effect, + "estimation_error": np.nan, + "diagnostic_gap_to_market_total": estimate.estimate - truths.market_total_effect, + "identified": False, + "comparison_status": "target_mismatch", + "coefficient_inference_cluster_aware": True, + "inference_valid": int(estimate.diagnostics["n_clusters"]) + >= config.minimum_inference_clusters, + "inference_valid_for_target": False, + "controlled_exposure_not_market_total": False, + "fit_status": "ok", + "design_cost": float(config.n_zones * config.n_periods), + "effect_scale": "stage-one saturation coefficient; not full-policy market total", + "identification_scope": ( + "Randomization identifies an assignment-saturation contrast. Omitted mapped " + "neighbor and history exposures prevent relabeling it as market_total_effect." + ), + "evidence_type": "semi_synthetic_assignment_diagnostic_target_mismatch", + "estimand_definition": ESTIMAND_DEFINITIONS["market_total_effect"], + } + + +def _fit_ledger( + records: pd.DataFrame, + failures: pd.DataFrame, + config: InterferenceBenchmarkConfig, +) -> pd.DataFrame: + plans = [ + { + "estimator": "exposure_mapped_cluster_regression", + "target_estimand": target, + "identified": True, + "comparison_status": "identified_controlled_exposure_response", + } + for target in MAPPED_TARGETS.values() + ] + plans.append( + { + "estimator": "naive_assignment_cluster_regression", + "target_estimand": "market_total_effect", + "identified": False, + "comparison_status": "target_mismatch", + } + ) + ledger = pd.DataFrame(plans) + keys = ["estimator", "target_estimand"] + successful = ( + records.loc[records["fit_status"].eq("ok")] + .groupby(keys) + .size() + .rename("successful_fits") + .reset_index() + ) + ledger = ledger.merge(successful, on=keys, how="left", validate="one_to_one") + ledger["attempted_fits"] = int(config.replications) + ledger["successful_fits"] = ledger["successful_fits"].fillna(0).astype(int) + ledger["failed_fits"] = ledger["attempted_fits"] - ledger["successful_fits"] + ledger["fit_complete"] = ledger["failed_fits"].eq(0) + ledger["fit_success_rate"] = ledger["successful_fits"] / ledger["attempted_fits"] + + inference = ( + records.groupby(keys)["inference_valid_for_target"] + .mean() + .rename("target_inference_valid_rate") + .reset_index() + ) + ledger = ledger.merge(inference, on=keys, how="left", validate="one_to_one") + ledger["target_inference_valid_rate"] = ( + ledger["target_inference_valid_rate"].fillna(0.0) + ) + ledger["decision_eligible"] = ( + ledger["identified"] + & ledger["fit_complete"] + & ledger["target_inference_valid_rate"].eq(1.0) + ) + ledger["recorded_failure_rows"] = int(len(failures)) + ledger["evidence_type"] = "semi_synthetic_benchmark_fit_ledger" + return ledger.sort_values(keys).reset_index(drop=True) + + +def _benchmark_summary( + records: pd.DataFrame, + fit_ledger: pd.DataFrame, + config: InterferenceBenchmarkConfig, + truths: InterferenceEstimands, +) -> pd.DataFrame: + mapped = records.loc[records["identified"] & records["fit_status"].eq("ok")].copy() + if mapped.empty: + mapped_summary = pd.DataFrame() + else: + mapped_summary = summarize_monte_carlo( + mapped, + confidence_level=config.confidence_level, + group_columns=["design", "estimator", "target_estimand"], + ) + mapped_summary["identified"] = True + mapped_summary["comparison_status"] = "identified_controlled_exposure_response" + mapped_summary["market_total_truth"] = truths.market_total_effect + mapped_summary["controlled_exposure_not_market_total"] = True + mapped_summary["diagnostic_mean_gap_to_market_total"] = np.nan + mapped_summary["diagnostic_gap_mcse"] = np.nan + mapped_summary["evidence_type"] = ( + "semi_synthetic_exposure_mapped_known_truth_monte_carlo" + ) + + inference = ( + mapped.groupby(["design", "estimator", "target_estimand"])[ + "inference_valid_for_target" + ] + .all() + .rename("inference_valid_for_target") + .reset_index() + ) + mapped_summary = mapped_summary.merge( + inference, + on=["design", "estimator", "target_estimand"], + how="left", + validate="one_to_one", + ) + invalid = ~mapped_summary["inference_valid_for_target"].astype(bool) + mapped_summary.loc[ + invalid, + ["coverage", "coverage_mcse", "power", "power_mcse"], + ] = np.nan + mapped_summary["withheld_reason"] = np.where( + invalid, + "cluster count is below the predeclared inference minimum", + None, + ) + + naive = records.loc[ + records["estimator"].eq("naive_assignment_cluster_regression") + & records["fit_status"].eq("ok") + ].copy() + if naive.empty: + naive_summary = pd.DataFrame() + else: + diagnostic = naive["diagnostic_gap_to_market_total"].astype(float) + naive_row: dict[str, Any] = { + "design": "two_stage_saturation", + "estimator": "naive_assignment_cluster_regression", + "target_estimand": "market_total_effect", + "truth": truths.market_total_effect, + "mean_estimate": float(naive["estimate"].mean()), + "bias": np.nan, + "bias_mcse": np.nan, + "variance": float(naive["estimate"].var(ddof=1)), + "rmse": np.nan, + "rmse_mcse": np.nan, + "coverage": np.nan, + "coverage_mcse": np.nan, + "power": np.nan, + "power_mcse": np.nan, + "mean_std_error": float(naive["std_error"].mean()), + "replications": int(len(naive)), + "mean_design_cost": float(naive["design_cost"].mean()), + "information_cost": np.nan, + "confidence_level": config.confidence_level, + "identified": False, + "comparison_status": "target_mismatch", + "market_total_truth": truths.market_total_effect, + "controlled_exposure_not_market_total": False, + "diagnostic_mean_gap_to_market_total": float(diagnostic.mean()), + "diagnostic_gap_mcse": float( + diagnostic.std(ddof=1) / np.sqrt(len(diagnostic)) + ), + "inference_valid_for_target": False, + "withheld_reason": ( + "The stage-one saturation coefficient omits mapped neighbor and history " + "exposures; bias, RMSE, coverage, and power for market_total_effect are withheld." + ), + "evidence_type": "semi_synthetic_assignment_diagnostic_target_mismatch", + } + naive_summary = pd.DataFrame([naive_row]) + + summary = pd.concat([mapped_summary, naive_summary], ignore_index=True, sort=False) + fit_columns = [ + "estimator", + "target_estimand", + "fit_complete", + "successful_fits", + "failed_fits", + "decision_eligible", + ] + summary = summary.merge( + fit_ledger[fit_columns], + on=["estimator", "target_estimand"], + how="left", + validate="one_to_one", + ) + return summary.sort_values(["identified", "target_estimand"], ascending=[False, True]).reset_index( + drop=True + ) + + +def run_interference_benchmark( + config: InterferenceBenchmarkConfig | None = None, +) -> InterferenceBenchmarkResult: + """Run deterministic known-truth exposure and naive-assignment comparisons.""" + + cfg = config or InterferenceBenchmarkConfig() + truths = known_interference_estimands(cfg) + records: list[dict[str, Any]] = [] + failures: list[dict[str, Any]] = [] + + for replication, (assignment_seed, outcome_seed) in enumerate( + _replication_seeds(cfg.seed, cfg.replications) + ): + frame = _simulate_exposure_dgp( + cfg, + assignment_seed=assignment_seed, + outcome_seed=outcome_seed, + ) + try: + records.extend( + _mapped_records( + frame, + cfg, + truths, + replication=replication, + assignment_seed=assignment_seed, + outcome_seed=outcome_seed, + ) + ) + except (ValueError, np.linalg.LinAlgError) as exc: + for target in MAPPED_TARGETS.values(): + failures.append( + { + "replication": replication, + "assignment_seed": assignment_seed, + "outcome_seed": outcome_seed, + "estimator": "exposure_mapped_cluster_regression", + "target_estimand": target, + "stage": "estimation", + "error": str(exc), + } + ) + try: + records.append( + _naive_record( + frame, + cfg, + truths, + replication=replication, + assignment_seed=assignment_seed, + outcome_seed=outcome_seed, + ) + ) + except (ValueError, np.linalg.LinAlgError) as exc: + failures.append( + { + "replication": replication, + "assignment_seed": assignment_seed, + "outcome_seed": outcome_seed, + "estimator": "naive_assignment_cluster_regression", + "target_estimand": "market_total_effect", + "stage": "estimation", + "error": str(exc), + } + ) + + record_frame = pd.DataFrame(records) + if record_frame.empty: + raise RuntimeError("interference benchmark produced no successful fits") + failure_frame = pd.DataFrame( + failures, + columns=[ + "replication", + "assignment_seed", + "outcome_seed", + "estimator", + "target_estimand", + "stage", + "error", + ], + ) + fit_ledger = _fit_ledger(record_frame, failure_frame, cfg) + summary = _benchmark_summary(record_frame, fit_ledger, cfg, truths) + metadata: dict[str, Any] = { + "evidence_type": "semi_synthetic_exposure_mapped_known_truth_benchmark", + "config": asdict(cfg), + "known_estimands": truths.to_dict(), + "estimand_definitions": dict(ESTIMAND_DEFINITIONS), + "assignment_design": ( + "balanced geographic cluster saturation arms followed by independent " + "within-zone-period opportunity assignment" + ), + "exposure_mapping": "two equal-weight ring neighbors declared before outcomes", + "history_mapping": f"mean of {cfg.history_lags} exact own-treatment lag(s)", + "market_total_bridge": ( + "Known only because this benchmark declares an additive exposure-response DGP; " + "controlled coefficients are not individually relabeled as market_total_effect." + ), + "naive_assignment_status": ( + "target mismatch; coefficient uncertainty is cluster-aware, but market-total " + "bias, RMSE, coverage, and power are withheld" + ), + } + return InterferenceBenchmarkResult( + records=record_frame.sort_values( + ["replication", "estimator", "target_estimand"] + ).reset_index(drop=True), + summary=summary, + fit_ledger=fit_ledger, + failures=failure_frame, + metadata=metadata, + ) + + +__all__ = [ + "InterferenceBenchmarkConfig", + "InterferenceBenchmarkResult", + "InterferenceEstimands", + "known_interference_estimands", + "run_interference_benchmark", +] diff --git a/CasualLab/src/casuallab/marketplace_benchmark.py b/CasualLab/src/casuallab/marketplace_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..9f985417444cd7e4dcb1a6585d77c084a3a34c80 --- /dev/null +++ b/CasualLab/src/casuallab/marketplace_benchmark.py @@ -0,0 +1,1106 @@ +"""End-to-end simulator, design, and estimator Monte Carlo orchestration.""" + +from __future__ import annotations + +import json +from dataclasses import dataclass, replace +from math import isfinite +from numbers import Integral, Real + +import numpy as np +import pandas as pd + +from casuallab.benchmark import BenchmarkConfig, summarize_monte_carlo +from casuallab.config import ( + DesignConfig, + DesignName, + EstimatorConfig, + SimulationConfig, + TreatmentVersion, +) +from casuallab.estimands import EstimandName, get_estimand, identification_assessment +from casuallab.estimators import estimate_effect +from casuallab.simulator import simulate_market + + +@dataclass(frozen=True) +class SensitivityScenario: + name: str + spillover_strength: float + persistence: float + treatment_duration: int | None = None + n_clusters: int | None = None + treatment_saturation: float | None = None + washout_periods: int | None = None + budget: float | None = None + treatment_version: TreatmentVersion | str | None = None + varied_dimension: str = "custom" + + @property + def scenario_role(self) -> str: + """Return the scenario's role in the predeclared benchmark plan.""" + + if self.budget is not None: + return "target_mismatch_diagnostic" + if self.varied_dimension == "reference": + return "reference" + if self.varied_dimension == "treatment_version": + return "intervention_sensitivity" + if self.varied_dimension in { + "spillover_strength", + "persistence", + "spillover_x_persistence", + }: + return "mechanism_sensitivity" + return "operational_sensitivity" + + def __post_init__(self) -> None: + if not self.name.strip(): + raise ValueError("scenario name must not be empty") + if not self.varied_dimension.strip(): + raise ValueError("varied_dimension must not be empty") + for field_name, value in { + "spillover_strength": self.spillover_strength, + "persistence": self.persistence, + }.items(): + if not isinstance(value, Real) or not isfinite(float(value)): + raise ValueError(f"{field_name} must be a finite number") + if self.spillover_strength < 0: + raise ValueError("spillover_strength must be non-negative") + if not 0 <= self.persistence < 1: + raise ValueError("persistence must lie in [0, 1)") + for field_name, value in { + "treatment_duration": self.treatment_duration, + "n_clusters": self.n_clusters, + "washout_periods": self.washout_periods, + }.items(): + if value is not None and (isinstance(value, bool) or not isinstance(value, Integral)): + raise ValueError(f"{field_name} must be an integer when supplied") + if self.treatment_duration is not None and self.treatment_duration < 1: + raise ValueError("treatment_duration must be positive when supplied") + if self.n_clusters is not None and self.n_clusters < 1: + raise ValueError("n_clusters must be positive when supplied") + if self.washout_periods is not None and self.washout_periods < 0: + raise ValueError("washout_periods cannot be negative") + if self.treatment_saturation is not None: + if not isinstance(self.treatment_saturation, Real) or not isfinite( + float(self.treatment_saturation) + ): + raise ValueError("treatment_saturation must be a finite number") + if not 0 < self.treatment_saturation <= 1: + raise ValueError("treatment_saturation must lie in (0, 1]") + if self.budget is not None: + if not isinstance(self.budget, Real) or not isfinite(float(self.budget)): + raise ValueError("budget must be a finite number when supplied") + if self.budget < 0: + raise ValueError("budget cannot be negative") + if self.treatment_version is not None: + object.__setattr__( + self, + "treatment_version", + TreatmentVersion.parse(self.treatment_version), + ) + if ( + self.treatment_duration is not None + and self.washout_periods is not None + and self.washout_periods >= self.treatment_duration + ): + raise ValueError("washout_periods must be shorter than treatment_duration") + + +@dataclass(frozen=True) +class MarketplaceBenchmarkResult: + records: pd.DataFrame + summary: pd.DataFrame + failures: pd.DataFrame + fit_ledger: pd.DataFrame + + +def default_sensitivity_scenarios( + simulation: SimulationConfig, +) -> tuple[SensitivityScenario, ...]: + """Return a compact, predeclared mechanism and operating-parameter grid. + + The first four cells retain the paired spillover-by-persistence factorial. The + remaining cells vary one assignment, intervention, or constraint dimension from the + no-interference reference. A low shared-budget cell is included as an explicit + *target-mismatch diagnostic*: assignment-specific budget dilution is not treated + as identification of the feasible all-zone policy effect. + """ + + active_spillover = max(0.15, simulation.spillover_strength) + active_persistence = max(0.25, simulation.persistence) + n_zones = max(8, simulation.n_zones) + base_duration = simulation.design.treatment_duration + duration_variant = ( + base_duration * 2 + if base_duration * 2 <= simulation.n_periods + else max(1, base_duration // 2) + ) + if duration_variant == base_duration: + duration_variant = base_duration + 1 + + base_clusters = min(simulation.design.n_clusters or 4, n_zones) + cluster_variant = n_zones if base_clusters < n_zones else max(1, base_clusters // 2) + if cluster_variant == base_clusters: + cluster_variant = max(1, base_clusters - 1) + + base_saturation = simulation.design.treatment_saturation + saturation_variant = 0.5 if not np.isclose(base_saturation, 0.5) else 0.75 + + washout_duration = max(2, base_duration) + base_washout = simulation.design.washout_periods + washout_variant = max(1, washout_duration // 2) if base_washout == 0 else 0 + washout_variant = min(washout_variant, washout_duration - 1) + + # This is intentionally conservative and laptop-safe. For the default calibrated + # configuration it is below unconstrained spend by a wide margin; every run also + # records the empirical binding rate rather than assuming the constraint bound. + nominal_cost_per_cell = 0.0 + if simulation.treatment_version in { + TreatmentVersion.RIDER_DISCOUNT, + TreatmentVersion.BUNDLED, + }: + nominal_cost_per_cell += ( + simulation.base_demand * simulation.base_fare * simulation.discount_rate + ) + if simulation.treatment_version in { + TreatmentVersion.DRIVER_INCENTIVE, + TreatmentVersion.BUNDLED, + }: + nominal_cost_per_cell += simulation.base_supply * simulation.incentive_per_driver + low_budget = max( + 1.0, + 0.02 * n_zones * simulation.n_periods * nominal_cost_per_cell, + ) + configured_budget = simulation.effective_budget + if configured_budget is not None and configured_budget > 0: + low_budget = min(float(configured_budget), low_budget) + + return ( + SensitivityScenario("no_interference", 0.0, 0.0, varied_dimension="reference"), + SensitivityScenario( + "spillover_only", + active_spillover, + 0.0, + varied_dimension="spillover_strength", + ), + SensitivityScenario( + "persistence_only", + 0.0, + active_persistence, + varied_dimension="persistence", + ), + SensitivityScenario( + "spillover_and_persistence", + active_spillover, + active_persistence, + varied_dimension="spillover_x_persistence", + ), + SensitivityScenario( + "treatment_duration_variant", + 0.0, + 0.0, + treatment_duration=duration_variant, + varied_dimension="treatment_duration", + ), + SensitivityScenario( + "cluster_count_variant", + 0.0, + 0.0, + n_clusters=cluster_variant, + varied_dimension="cluster_count", + ), + SensitivityScenario( + "partial_saturation", + 0.0, + 0.0, + treatment_saturation=saturation_variant, + varied_dimension="treatment_saturation", + ), + SensitivityScenario( + "washout_variant", + 0.0, + active_persistence, + treatment_duration=washout_duration, + washout_periods=washout_variant, + varied_dimension="washout_periods", + ), + SensitivityScenario( + "shared_budget_low", + 0.0, + 0.0, + budget=low_budget, + varied_dimension="budget", + ), + SensitivityScenario( + "rider_discount_only", + 0.0, + 0.0, + treatment_version=TreatmentVersion.RIDER_DISCOUNT, + varied_dimension="treatment_version", + ), + SensitivityScenario( + "driver_incentive_only", + 0.0, + 0.0, + treatment_version=TreatmentVersion.DRIVER_INCENTIVE, + varied_dimension="treatment_version", + ), + ) + + +def _scenario_simulation_config( + simulation: SimulationConfig, + scenario: SensitivityScenario, + *, + n_zones: int, + seed: int, +) -> SimulationConfig: + """Apply a scenario's declared overrides without inheriting the base budget.""" + + duration = scenario.treatment_duration or simulation.design.treatment_duration + washout = ( + simulation.design.washout_periods + if scenario.washout_periods is None + else scenario.washout_periods + ) + if washout >= duration: + raise ValueError(f"scenario {scenario.name!r} has washout_periods >= treatment_duration") + design = replace( + simulation.design, + treatment_duration=duration, + washout_periods=washout, + n_clusters=( + simulation.design.n_clusters if scenario.n_clusters is None else scenario.n_clusters + ), + treatment_saturation=( + simulation.design.treatment_saturation + if scenario.treatment_saturation is None + else scenario.treatment_saturation + ), + # The simulation-level scenario budget is the sole shared constraint. + budget=None, + ) + return replace( + simulation, + n_zones=n_zones, + budget=scenario.budget, + seed=seed, + spillover_strength=scenario.spillover_strength, + persistence=scenario.persistence, + rider_substitution=( + 0.0 if scenario.spillover_strength == 0 else simulation.rider_substitution + ), + driver_mobility=(0.0 if scenario.spillover_strength == 0 else simulation.driver_mobility), + treatment_version=( + simulation.treatment_version + if scenario.treatment_version is None + else scenario.treatment_version + ), + design=design, + ) + + +def _budget_scope(budget: float | None) -> str: + if budget is None: + return "unconstrained estimator-recovery simulation" + return ( + f"shared market budget={float(budget):.12g}; assignment-vs-full-policy " + "comparison is a target-mismatch diagnostic" + ) + + +def _scenario_n_zones( + simulation: SimulationConfig, + scenario: SensitivityScenario, +) -> int: + """Use two zones per requested geographic cluster, matching dashboard geometry.""" + + requested_clusters = scenario.n_clusters or simulation.design.n_clusters or 4 + return max(4, 2 * int(requested_clusters)) + + +_METHOD_ALIASES = { + "regression_adjusted": "regression_adjustment", + "regression": "regression_adjustment", + "cluster_adjusted": "cluster_robust", + "clustered": "cluster_robust", + "two_way_cluster": "two_way_cluster_robust", + "two_way_clustered": "two_way_cluster_robust", + "did": "difference_in_differences", + "aipw": "doubly_robust", + "dr": "doubly_robust", +} + +MIN_INFERENCE_CLUSTERS = 8 + + +def _canonical_method(method: str) -> str: + normalized = method.strip().lower().replace("-", "_").replace(" ", "_") + return _METHOD_ALIASES.get(normalized, normalized) + + +def _applicable_methods(design: DesignName, requested: tuple[str, ...]) -> tuple[str, ...]: + canonical = tuple(dict.fromkeys(_canonical_method(method) for method in requested)) + if design is DesignName.INDIVIDUAL: + allowed = {"regression_adjustment", "cluster_robust"} + elif design is DesignName.GEO_CLUSTER: + allowed = { + "difference_in_means", + "regression_adjustment", + "cluster_robust", + "doubly_robust", + } + elif design is DesignName.GEO_TIME: + allowed = { + "difference_in_means", + "regression_adjustment", + "cluster_robust", + "difference_in_differences", + "doubly_robust", + "two_way_cluster_robust", + } + else: + # Pure temporal assignments have no stable treated group for conventional + # DiD; common time fixed effects absorb marketplace-wide treatment. + allowed = { + "difference_in_means", + "regression_adjustment", + "cluster_robust", + "doubly_robust", + } + return tuple(method for method in canonical if method in allowed) + + +def _scenario_method_applicability( + method: str, + design: DesignName, + planned_randomization_clusters: int, + treatment_probability: float, +) -> tuple[bool, str]: + """Screen estimator requirements known before any Monte Carlo draw.""" + + homogeneous_assignment_groups = { + DesignName.GEO_CLUSTER, + DesignName.TIME_BLOCK, + DesignName.GEO_TIME, + } + if method == "doubly_robust" and design in homogeneous_assignment_groups: + treated_clusters = int( + np.clip( + round(treatment_probability * planned_randomization_clusters), + 1, + planned_randomization_clusters - 1, + ) + ) + control_clusters = planned_randomization_clusters - treated_clusters + if min(treated_clusters, control_clusters) < 2: + return ( + False, + "group-cross-fitted doubly robust estimation requires at least two " + "planned randomization clusters in each arm", + ) + return True, "implemented for this assignment geometry" + + +def _design_config( + design: DesignName, + simulation: SimulationConfig, + *, + seed: int, +) -> DesignConfig: + requested_clusters = simulation.design.n_clusters or 4 + n_clusters = min(requested_clusters, simulation.n_zones) + cluster_size = max(1, int(np.ceil(simulation.n_zones / n_clusters))) + temporal = design in {DesignName.TIME_BLOCK, DesignName.SWITCHBACK, DesignName.GEO_TIME} + duration = simulation.design.treatment_duration + washout = simulation.design.washout_periods if temporal else 0 + return DesignConfig( + name=design, + treatment_probability=simulation.design.treatment_probability, + treatment_saturation=simulation.design.treatment_saturation, + n_clusters=n_clusters if design in {DesignName.GEO_CLUSTER, DesignName.GEO_TIME} else None, + cluster_size=cluster_size, + treatment_duration=duration, + washout_periods=min(washout, duration - 1), + budget=None, + seed=seed + 1, + ) + + +def _estimator_config( + method: str, + design: DesignName, + target_estimand: str, + seed: int, +) -> EstimatorConfig: + treatment = "treatment" if design is DesignName.INDIVIDUAL else "assigned_treatment" + cluster: str | None = None + if method == "cluster_robust": + cluster = "zone_id" if design is DesignName.INDIVIDUAL else "randomization_cluster" + elif method == "two_way_cluster_robust": + cluster = "cluster_id" + elif method == "doubly_robust": + cluster = "randomization_cluster" + return EstimatorConfig( + method=method, + outcome="outcome", + treatment=treatment, + covariates=("baseline_demand", "baseline_supply", "hour_sin", "hour_cos"), + cluster=cluster, + propensity="treatment_probability" if method == "doubly_robust" else None, + unit="zone_id" if method == "difference_in_differences" else None, + time=( + "period_id" + if method == "difference_in_differences" + else ("time_block" if method == "two_way_cluster_robust" else None) + ), + target_estimand=target_estimand, + alpha=0.05, + # Canonical simulator truths use the fixed configured horizon. Washout- + # restricted truths remain separately named analysis_population_* values. + filter_eligible=False, + crossfit_folds=3, + seed=seed, + ) + + +def _design_identification_flag( + design: DesignName, + target_estimand: str, + scenario: SensitivityScenario, +) -> bool: + # A shared cap scales the realized mixed assignment and the feasible all-zone + # policy by different factors. Without a budget-aware exposure mapping, their + # assignment coefficient is not the declared full-policy estimand. + if scenario.budget is not None: + return False + compatible = design.value in set(get_estimand(target_estimand).compatible_designs) + screen, _ = identification_assessment( + target_estimand, + design=design.value, + interference_present=scenario.spillover_strength > 0, + exposure_mapped=False, + histories_observed=True, + ) + if not compatible or not screen: + return False + if design is DesignName.GEO_CLUSTER and scenario.spillover_strength > 0: + return False + if design in {DesignName.TIME_BLOCK, DesignName.SWITCHBACK} and scenario.persistence > 0: + return False + if design is DesignName.GEO_TIME and ( + scenario.spillover_strength > 0 or scenario.persistence > 0 + ): + return False + return True + + +def _identification_reason( + design: DesignName, + target_estimand: str, + scenario: SensitivityScenario, +) -> str: + if _design_identification_flag(design, target_estimand, scenario): + return "assignment contrast matches the fixed full-horizon target" + if scenario.budget is not None: + return ( + "shared-budget scaling couples realized intensity to aggregate assignment, " + "so the assignment contrast does not identify the feasible all-zone policy" + ) + if design.value not in set(get_estimand(target_estimand).compatible_designs): + return "assignment family targets a different causal contrast" + if design is DesignName.GEO_CLUSTER and scenario.spillover_strength > 0: + return "cross-cluster spillover prevents isolation of the all-zone policy" + if design in {DesignName.TIME_BLOCK, DesignName.SWITCHBACK} and scenario.persistence > 0: + return "carryover makes current assignment differ from full-policy history" + if design is DesignName.GEO_TIME: + return "unmodeled spatial or temporal exposure changes the assignment contrast" + return "conservative identification screen failed" + + +def _planned_cluster_counts( + design: DesignName, + *, + n_zones: int, + n_periods: int, + config: DesignConfig, +) -> tuple[int, int]: + """Return randomized-unit and estimator-inference cluster counts.""" + + time_blocks = int(np.ceil(n_periods / config.treatment_duration)) + geo_clusters = config.n_clusters or int(np.ceil(n_zones / config.cluster_size)) + if design is DesignName.INDIVIDUAL: + return n_zones * n_periods, n_zones + if design is DesignName.GEO_CLUSTER: + return geo_clusters, geo_clusters + if design is DesignName.TIME_BLOCK: + return time_blocks, time_blocks + if design is DesignName.SWITCHBACK: + pairs = int(np.ceil(time_blocks / 2)) + return pairs, pairs + return geo_clusters * time_blocks, geo_clusters * time_blocks + + +def _inference_assessment( + method: str, + design: DesignName, + n_inference_clusters: int, + *, + n_geographic_clusters: int | None = None, + n_time_clusters: int | None = None, +) -> tuple[bool, str]: + """Assess whether reported uncertainty follows the randomized assignment unit.""" + + if method == "two_way_cluster_robust": + if design is not DesignName.GEO_TIME: + return False, "two-way geographic-time inference requires geo_time assignment" + if n_geographic_clusters is None or n_time_clusters is None: + return False, "two-way inference dimensions were not recorded" + limiting_clusters = min(n_geographic_clusters, n_time_clusters) + if limiting_clusters < MIN_INFERENCE_CLUSTERS: + return ( + False, + f"few-cluster diagnostic: min({n_geographic_clusters} geographic, " + f"{n_time_clusters} time) groups is below {MIN_INFERENCE_CLUSTERS}", + ) + return True, "two-way geographic and time-block cluster-aware uncertainty" + + if design is DesignName.GEO_TIME and method in { + "cluster_robust", + "doubly_robust", + "difference_in_differences", + }: + return ( + False, + "point estimate diagnostic; one-way uncertainty does not cover shared " + "geographic and time-block dependence", + ) + if method in {"cluster_robust", "doubly_robust"}: + if n_inference_clusters < MIN_INFERENCE_CLUSTERS: + return ( + False, + f"few-cluster diagnostic: {n_inference_clusters} independent inference " + f"clusters is below the declared minimum of {MIN_INFERENCE_CLUSTERS}", + ) + return True, "assignment-cluster-aware uncertainty" + return False, "point estimate diagnostic; iid uncertainty ignores clustered assignment" + + +def _cluster_semantics(design: DesignName) -> str: + descriptions = { + DesignName.INDIVIDUAL: "zone-period saturation assignments", + DesignName.GEO_CLUSTER: "geographic assignment clusters", + DesignName.TIME_BLOCK: "market-wide time-block assignments", + DesignName.SWITCHBACK: "randomized switchback block pairs", + DesignName.GEO_TIME: "geographic-cluster-by-time-block assignment cells", + } + return descriptions[design] + + +def run_marketplace_benchmark( + benchmark: BenchmarkConfig, + simulation: SimulationConfig, + *, + scenarios: tuple[SensitivityScenario, ...] | None = None, +) -> MarketplaceBenchmarkResult: + """Compare assignment/estimator pairs against matched structural truth. + + The reference recovery cells disable the configured experiment budget. A single + low-budget sensitivity cell is retained but is explicitly marked as a target + mismatch because the shared cap dilutes a mixed assignment differently from the + feasible all-market policy. Operational policy evaluation remains separate in + ``marketplace_policy``. + """ + + selected_scenarios = ( + default_sensitivity_scenarios(simulation) if scenarios is None else scenarios + ) + if not selected_scenarios: + raise ValueError("at least one sensitivity scenario is required") + scenario_names = [scenario.name for scenario in selected_scenarios] + if len(scenario_names) != len(set(scenario_names)): + raise ValueError("sensitivity scenario names must be unique") + declared_scenario_set = json.dumps(sorted(scenario_names), separators=(",", ":")) + target = EstimandName.parse(benchmark.target_estimand).value + if target != EstimandName.MARKET_TOTAL.value: + raise ValueError( + "marketplace estimator recovery currently supports only " + "market_total_effect; cumulative, mechanism, and efficiency targets " + "require estimand-specific transformations" + ) + records: list[dict[str, object]] = [] + failures: list[dict[str, object]] = [] + fit_plans: list[dict[str, object]] = [] + master = np.random.SeedSequence(benchmark.seed) + replication_seeds = [ + int(sequence.generate_state(1)[0]) for sequence in master.spawn(benchmark.replications) + ] + + for scenario in selected_scenarios: + # Reuse each replication seed across designs and scenarios. This gives exact + # common-random-number pairing when panel geometry is equal; the cluster-count + # cell intentionally changes geometry and is common-seed rather than draw-paired. + for design_name in benchmark.designs: + design = DesignName.parse(design_name) + candidate_methods = _applicable_methods(design, benchmark.estimators) + n_zones = _scenario_n_zones(simulation, scenario) + plan_base = _scenario_simulation_config( + simulation, + scenario, + n_zones=n_zones, + seed=benchmark.seed, + ) + plan_design = _design_config( + design, + plan_base, + seed=benchmark.seed, + ) + identified = _design_identification_flag(design, target, scenario) + identification_scope = _identification_reason(design, target, scenario) + planned_randomization_clusters, planned_inference_clusters = _planned_cluster_counts( + design, + n_zones=n_zones, + n_periods=simulation.n_periods, + config=plan_design, + ) + planned_geo_clusters = ( + int(plan_design.n_clusters or np.ceil(n_zones / plan_design.cluster_size)) + if design is DesignName.GEO_TIME + else None + ) + planned_time_clusters = ( + int(np.ceil(simulation.n_periods / plan_design.treatment_duration)) + if design is DesignName.GEO_TIME + else None + ) + method_applicability = { + method: _scenario_method_applicability( + method, + design, + planned_randomization_clusters, + plan_design.treatment_probability, + ) + for method in candidate_methods + } + methods = tuple( + method for method, (applicable, _) in method_applicability.items() if applicable + ) + for method in candidate_methods: + applicable, applicability_reason = method_applicability[method] + inference_valid, inference_scope = _inference_assessment( + method, + design, + planned_inference_clusters, + n_geographic_clusters=planned_geo_clusters, + n_time_clusters=planned_time_clusters, + ) + fit_plans.append( + { + "scenario": scenario.name, + "declared_scenario_set": declared_scenario_set, + "declared_scenario_count": len(selected_scenarios), + "design": design.value, + "estimator": method, + "target_estimand": target, + "varied_dimension": scenario.varied_dimension, + "scenario_role": scenario.scenario_role, + "spillover_strength": scenario.spillover_strength, + "persistence": scenario.persistence, + "treatment_duration": plan_design.treatment_duration, + "washout_periods": plan_design.washout_periods, + "treatment_saturation": plan_design.treatment_saturation, + "treatment_probability": plan_design.treatment_probability, + "configured_geo_clusters": plan_design.n_clusters, + "cluster_size": plan_design.cluster_size, + "cluster_semantics": _cluster_semantics(design), + "planned_randomization_clusters": planned_randomization_clusters, + "inference_clusters": planned_inference_clusters, + "inference_geographic_clusters": planned_geo_clusters, + "inference_time_clusters": planned_time_clusters, + "minimum_inference_clusters": MIN_INFERENCE_CLUSTERS, + "applicable": applicable, + "applicability_reason": applicability_reason, + "planned_fits": benchmark.replications if applicable else 0, + "n_zones": n_zones, + "n_periods": simulation.n_periods, + "identified": identified, + "identification_scope": identification_scope, + "comparison_status": ( + "identified_target" if identified else "target_mismatch" + ), + "inference_valid": inference_valid, + "inference_scope": inference_scope, + "target_population_id": ( + f"all_{n_zones}_zones_x_{simulation.n_periods}_periods_" + "equal_cell_weight" + ), + "estimator_population_id": "full_horizon", + "budget": scenario.budget, + "budget_scope": _budget_scope(scenario.budget), + "shared_budget_coupling": scenario.budget is not None, + "incentive_per_driver": plan_base.incentive_per_driver, + "treatment_version": plan_base.treatment_version.value, + "normalized_measurement_cost": ( + n_zones * simulation.n_periods * benchmark.cost_per_market_period + ), + "measurement_cost_basis": ( + "normalized zone-period measurement units; excludes treatment " + "and operational spend" + ), + "operational_cost_included": False, + "evidence_type": "semi_synthetic_causal_monte_carlo", + } + ) + if not candidate_methods: + failures.append( + { + "scenario": scenario.name, + "design": design.value, + "estimator": None, + "stage": "applicability", + "error": "no requested estimator is applicable to this assignment", + } + ) + continue + if not methods: + continue + for replication, seed in enumerate(replication_seeds): + # Two zones per requested geographic cluster matches the dashboard's + # scenario geometry. The G=8 cluster-count cell therefore uses 16 + # zones and supplies a declared adequate-cluster inference diagnostic. + scenario_base = _scenario_simulation_config( + simulation, + n_zones=n_zones, + seed=seed, + scenario=scenario, + ) + design_config = _design_config( + design, + scenario_base, + seed=seed, + ) + scenario_config = replace(scenario_base, design=design_config) + try: + result = simulate_market(scenario_config) + except (ValueError, RuntimeError, np.linalg.LinAlgError) as exc: + for method in methods: + failures.append( + { + "scenario": scenario.name, + "design": design.value, + "estimator": method, + "replication": replication, + "seed": seed, + "stage": "simulation", + "error": str(exc), + } + ) + continue + truth = result.ground_truth.get(target) + if truth is None or not np.isfinite(truth): + for method in methods: + failures.append( + { + "scenario": scenario.name, + "design": design.value, + "estimator": method, + "replication": replication, + "seed": seed, + "stage": "ground_truth", + "error": f"ground truth {target!r} is unavailable", + } + ) + continue + for method in methods: + estimator_config = _estimator_config(method, design, target, seed) + try: + estimate = estimate_effect(result.panel, estimator_config) + except (ValueError, np.linalg.LinAlgError) as exc: + failures.append( + { + "scenario": scenario.name, + "design": design.value, + "estimator": method, + "replication": replication, + "seed": seed, + "stage": "estimation", + "error": str(exc), + } + ) + continue + inference_cluster_column = estimator_config.cluster + if inference_cluster_column is not None: + inference_clusters = int(result.panel[inference_cluster_column].nunique()) + elif method == "difference_in_differences": + inference_clusters = int(result.panel["zone_id"].nunique()) + else: + inference_clusters = planned_inference_clusters + inference_geographic_clusters = ( + int(result.panel["cluster_id"].nunique()) + if design is DesignName.GEO_TIME + else None + ) + inference_time_clusters = ( + int(result.panel["time_block"].nunique()) + if design is DesignName.GEO_TIME + else None + ) + valid_inference, inference_scope = _inference_assessment( + method, + design, + inference_clusters, + n_geographic_clusters=inference_geographic_clusters, + n_time_clusters=inference_time_clusters, + ) + raw_gap = float(estimate.estimate - truth) + records.append( + { + "scenario": scenario.name, + "declared_scenario_set": declared_scenario_set, + "declared_scenario_count": len(selected_scenarios), + "design": design.value, + "estimator": estimate.method, + "replication": replication, + "seed": seed, + "target_estimand": target, + "varied_dimension": scenario.varied_dimension, + "scenario_role": scenario.scenario_role, + "estimate": estimate.estimate, + "std_error": estimate.standard_error, + "ci_low": estimate.ci_low, + "ci_high": estimate.ci_high, + "p_value": estimate.p_value, + "truth": float(truth), + "spillover_strength": scenario.spillover_strength, + "persistence": scenario.persistence, + "treatment_duration": design_config.treatment_duration, + "washout_periods": design_config.washout_periods, + "treatment_saturation": design_config.treatment_saturation, + "treatment_probability": design_config.treatment_probability, + "mean_assignment_propensity": float( + result.panel["treatment_probability"].mean() + ), + "configured_geo_clusters": design_config.n_clusters, + "effective_randomization_clusters": ( + int(result.panel["randomization_cluster"].nunique()) + ), + "cluster_semantics": _cluster_semantics(design), + "inference_clusters": inference_clusters, + "inference_geographic_clusters": inference_geographic_clusters, + "inference_time_clusters": inference_time_clusters, + "minimum_inference_clusters": MIN_INFERENCE_CLUSTERS, + "cluster_size": design_config.cluster_size, + "n_zones": scenario_config.n_zones, + "n_periods": scenario_config.n_periods, + "identified": identified, + "identification_scope": identification_scope, + "comparison_status": ( + "identified_target" if identified else "target_mismatch" + ), + "inference_valid": valid_inference, + "inference_scope": inference_scope, + "estimation_error": raw_gap if identified else np.nan, + "diagnostic_gap": raw_gap if not identified else np.nan, + "target_population_id": result.metadata["target_population_id"], + "estimator_population_id": "full_horizon", + "budget": scenario_config.effective_budget, + "budget_scope": _budget_scope(scenario_config.effective_budget), + "shared_budget_coupling": ( + scenario_config.effective_budget is not None + ), + "budget_binding": bool( + scenario_config.effective_budget is not None + and ( + float(result.metadata["budget_scale"]) < 1.0 - 1e-9 + or float(result.metadata["all_treated_budget_scale"]) + < 1.0 - 1e-9 + ) + ), + "assignment_budget_scale": result.metadata["budget_scale"], + "full_policy_budget_scale": result.metadata["all_treated_budget_scale"], + "incentive_per_driver": scenario_config.incentive_per_driver, + "treatment_version": scenario_config.treatment_version.value, + "normalized_measurement_cost": ( + scenario_config.n_zones + * scenario_config.n_periods + * benchmark.cost_per_market_period + ), + # The generic Monte Carlo engine consumes this internal + # column; it is renamed before the public result is returned. + "design_cost": ( + scenario_config.n_zones + * scenario_config.n_periods + * benchmark.cost_per_market_period + ), + "measurement_cost_basis": ( + "normalized zone-period measurement units; excludes " + "treatment and operational spend" + ), + "operational_cost_included": False, + "full_policy_spend": result.ground_truth.get("full_policy_spend"), + "realized_schedule_spend": result.metadata.get("realized_spend"), + "target_rows": len(result.panel), + "washout_eligible_rows": result.ground_truth.get("analysis_rows"), + "evidence_type": "semi_synthetic_causal_monte_carlo", + } + ) + + record_frame = pd.DataFrame(records) + if record_frame.empty: + nonbinding_budget_threshold = float("nan") + else: + # Only uncapped runs can certify the spend level above which a dashboard + # budget is nonbinding. A capped path must never prove its own invariance. + unconstrained = record_frame.loc[record_frame["budget"].isna()] + spend_values = unconstrained[["full_policy_spend", "realized_schedule_spend"]].to_numpy( + dtype=float + ) + if spend_values.size == 0 or not np.isfinite(spend_values).any(): + nonbinding_budget_threshold = float("nan") + else: + nonbinding_budget_threshold = float(np.nanmax(spend_values)) + record_frame["nonbinding_budget_threshold"] = nonbinding_budget_threshold + record_frame["nonbinding_budget_threshold_scope"] = ( + "maximum full-policy or realized-schedule treatment spend across successful " + "unconstrained benchmark simulations, designs, replications, and scenarios" + ) + ledger_keys = ["scenario", "design", "estimator"] + fit_ledger = pd.DataFrame(fit_plans) + if fit_ledger.empty: + raise ValueError("no requested estimator is applicable to any selected design") + if record_frame.empty: + success_counts = pd.DataFrame(columns=[*ledger_keys, "successful_fits"]) + else: + success_counts = ( + record_frame.groupby(ledger_keys, dropna=False) + .size() + .rename("successful_fits") + .reset_index() + ) + fit_ledger = fit_ledger.merge( + success_counts, + on=ledger_keys, + how="left", + validate="one_to_one", + ) + fit_ledger["attempted_fits"] = fit_ledger.pop("planned_fits").astype(int) + fit_ledger["successful_fits"] = fit_ledger["successful_fits"].fillna(0).astype(int) + fit_ledger["failed_fits"] = fit_ledger["attempted_fits"] - fit_ledger["successful_fits"] + fit_ledger["fit_success_rate"] = fit_ledger["successful_fits"] / fit_ledger["attempted_fits"] + fit_ledger["fit_complete"] = fit_ledger["failed_fits"].eq(0) + fit_ledger["nonbinding_budget_threshold"] = nonbinding_budget_threshold + fit_ledger["nonbinding_budget_threshold_scope"] = ( + "maximum full-policy or realized-schedule treatment spend across successful " + "unconstrained benchmark simulations, designs, replications, and scenarios" + ) + + if record_frame.empty: + summary = fit_ledger.copy() + for column in ( + "truth", + "mean_estimate", + "bias", + "bias_mcse", + "variance", + "rmse", + "rmse_mcse", + "coverage", + "coverage_mcse", + "power", + "power_mcse", + "mean_std_error", + "normalized_precision_cost", + "mean_full_policy_spend", + "max_full_policy_spend", + "mean_realized_schedule_spend", + "max_realized_schedule_spend", + "budget_binding_rate", + "mean_assignment_budget_scale", + "mean_full_policy_budget_scale", + "mean_target_rows", + "mean_washout_eligible_rows", + "effective_randomization_clusters", + "mean_assignment_propensity", + ): + summary[column] = np.nan + summary["replications"] = 0 + summary["mean_normalized_measurement_cost"] = summary["normalized_measurement_cost"] + summary["confidence_level"] = benchmark.confidence_level + else: + metric_summary = summarize_monte_carlo( + record_frame, + confidence_level=benchmark.confidence_level, + group_columns=ledger_keys, + ).rename( + columns={ + "mean_design_cost": "mean_normalized_measurement_cost", + "information_cost": "normalized_precision_cost", + } + ) + metric_summary = metric_summary.drop(columns=["evidence_type"]) + summary = fit_ledger.merge( + metric_summary, + on=ledger_keys, + how="left", + validate="one_to_one", + ) + supplemental = ( + record_frame.groupby(ledger_keys, dropna=False) + .agg( + mean_full_policy_spend=("full_policy_spend", "mean"), + max_full_policy_spend=("full_policy_spend", "max"), + mean_realized_schedule_spend=("realized_schedule_spend", "mean"), + max_realized_schedule_spend=("realized_schedule_spend", "max"), + budget_binding_rate=("budget_binding", "mean"), + mean_assignment_budget_scale=("assignment_budget_scale", "mean"), + mean_full_policy_budget_scale=("full_policy_budget_scale", "mean"), + mean_target_rows=("target_rows", "mean"), + mean_washout_eligible_rows=("washout_eligible_rows", "mean"), + effective_randomization_clusters=( + "effective_randomization_clusters", + "mean", + ), + mean_assignment_propensity=("mean_assignment_propensity", "mean"), + ) + .reset_index() + ) + summary = summary.merge( + supplemental, + on=ledger_keys, + how="left", + validate="one_to_one", + ) + summary["normalized_precision_cost_definition"] = ( + "mean normalized zone-period measurement units multiplied by MSE; lower is better" + ) + summary["diagnostic_mean_gap"] = np.where( + ~summary["identified"].astype(bool), summary["bias"], np.nan + ) + summary["diagnostic_gap_mcse"] = np.where( + ~summary["identified"].astype(bool), summary["bias_mcse"], np.nan + ) + target_mismatch = ~summary["identified"].astype(bool) + summary.loc[ + target_mismatch, + [ + "bias", + "bias_mcse", + "rmse", + "rmse_mcse", + "coverage", + "coverage_mcse", + "power", + "power_mcse", + "normalized_precision_cost", + ], + ] = np.nan + invalid_inference = ~summary["inference_valid"].astype(bool) + summary.loc[ + invalid_inference, + ["coverage", "coverage_mcse", "power", "power_mcse"], + ] = np.nan + failure_frame = pd.DataFrame(failures) + public_records = record_frame.drop(columns=["design_cost"], errors="ignore") + return MarketplaceBenchmarkResult(public_records, summary, failure_frame, fit_ledger) diff --git a/CasualLab/src/casuallab/marketplace_policy.py b/CasualLab/src/casuallab/marketplace_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..ecb6e64c5420d4d1070d3683f8156759ac196870 --- /dev/null +++ b/CasualLab/src/casuallab/marketplace_policy.py @@ -0,0 +1,638 @@ +"""Honest-holdout policy learning evaluated through the marketplace simulator. + +The learner sees randomized assignments, pre-treatment features, and observed +outcomes from training markets. Structural effect columns are never passed to a +model. After scores are frozen, every baseline allocation is evaluated by running +the complete simulator again on disjoint market seeds, so congestion, spatial +spillovers, persistence, matching, and the shared budget are recomputed jointly. +""" + +from __future__ import annotations + +import json +from collections.abc import Mapping, Sequence +from dataclasses import asdict, dataclass, fields, replace + +import numpy as np +import pandas as pd +from sklearn.ensemble import RandomForestRegressor + +from casuallab.config import ( + DesignConfig, + DesignName, + SimulationConfig, + TreatmentVersion, +) +from casuallab.simulator import SimulationResult, simulate_market + +POLICY_FEATURES = ( + "baseline_demand", + "baseline_supply", + "market_tightness", + "hour_sin", + "hour_cos", + "zone_demand_factor", + "zone_supply_factor", +) +POLICY_NAMES = ( + "no_treatment", + "random", + "uniform", + "rule_based", + "model_based", +) + + +@dataclass(frozen=True, slots=True) +class MarketplacePolicyConfig: + """Configuration for a fixed-budget honest-holdout policy comparison.""" + + budget: float = 2_000.0 + instability_penalty: float = 0.25 + model_trees: int = 120 + model_replicates: int = 4 + seed: int = 202503 + training_treatment_probability: float = 0.5 + training_treatment_duration: int = 4 + + def __post_init__(self) -> None: + if self.budget <= 0: + raise ValueError("budget must be positive") + if self.instability_penalty < 0: + raise ValueError("instability_penalty must be non-negative") + if self.model_trees < 10: + raise ValueError("model_trees must be at least 10") + if self.model_replicates < 2: + raise ValueError("model_replicates must be at least 2") + if not 0 < self.training_treatment_probability < 1: + raise ValueError("training_treatment_probability must lie in (0, 1)") + if self.training_treatment_duration < 1: + raise ValueError("training_treatment_duration must be positive") + + @classmethod + def from_mapping(cls, values: Mapping[str, object]) -> MarketplacePolicyConfig: + if not isinstance(values, Mapping): + raise TypeError("policy configuration must be a mapping") + allowed = {item.name for item in fields(cls)} + unknown = set(values).difference(allowed) + if unknown: + raise ValueError(f"unknown marketplace policy keys: {sorted(unknown)}") + return cls(**dict(values)) + + +@dataclass(frozen=True) +class MarketplacePolicyResult: + """Aggregate policy table plus the paired holdout-market evaluation ledger.""" + + summary: pd.DataFrame + market_results: pd.DataFrame + + +@dataclass(frozen=True) +class TreatmentVersionPolicyResult: + """Policy summaries and paired ledgers across declared intervention versions.""" + + summary: pd.DataFrame + market_results: pd.DataFrame + + +def _seed_draws(seed: int, count: int) -> tuple[int, ...]: + sequence = np.random.SeedSequence(seed) + return tuple( + int(child.generate_state(1, dtype=np.uint32)[0]) + for child in sequence.spawn(count) + ) + + +def _training_design( + simulation: SimulationConfig, + config: MarketplacePolicyConfig, + seed: int, +) -> DesignConfig: + n_clusters = min(4, simulation.n_zones) + return DesignConfig( + name=DesignName.GEO_TIME, + treatment_probability=config.training_treatment_probability, + treatment_saturation=1.0, + n_clusters=n_clusters, + cluster_size=max(1, int(np.ceil(simulation.n_zones / n_clusters))), + treatment_duration=config.training_treatment_duration, + washout_periods=0, + budget=None, + seed=seed + 1, + ) + + +def _randomized_training_frame( + simulation: SimulationConfig, + config: MarketplacePolicyConfig, + seeds: Sequence[int], +) -> pd.DataFrame: + frames: list[pd.DataFrame] = [] + allowed = { + *POLICY_FEATURES, + "outcome", + "assigned_treatment", + "treatment_probability", + } + for market_index, seed in enumerate(seeds): + design = _training_design(simulation, config, seed) + market_config = replace(simulation, seed=seed, budget=None, design=design) + generated = simulate_market(market_config) + frame = generated.panel[list(allowed)].copy() + frame["training_market_index"] = market_index + frame["training_market_seed"] = seed + frames.append(frame) + training = pd.concat(frames, ignore_index=True) + treatment = training["assigned_treatment"].to_numpy(dtype=float) + if not set(np.unique(treatment)).issubset({0.0, 1.0}) or np.ptp(treatment) == 0: + raise ValueError("policy training requires randomized binary assignment variation") + numeric = training[[*POLICY_FEATURES, "outcome"]].to_numpy(dtype=float) + if not np.isfinite(numeric).all(): + raise ValueError("policy training features and outcomes must be finite") + # Deliberately reject accidental leakage of structural validation columns. + if any(column.startswith("true_") or column == "y0" for column in training): + raise AssertionError("structural truth leaked into the policy training frame") + return training + + +def _fit_t_learner_ensemble( + training: pd.DataFrame, + config: MarketplacePolicyConfig, +) -> tuple[tuple[RandomForestRegressor, RandomForestRegressor], ...]: + models: list[tuple[RandomForestRegressor, RandomForestRegressor]] = [] + treated = training["assigned_treatment"] == 1 + for replicate in range(config.model_replicates): + pair: list[RandomForestRegressor] = [] + for arm, mask in ((0, ~treated), (1, treated)): + model = RandomForestRegressor( + n_estimators=config.model_trees, + min_samples_leaf=max(5, int(mask.sum()) // 100), + max_depth=8, + max_features="sqrt", + bootstrap=True, + random_state=config.seed + replicate * 2 + arm, + n_jobs=1, + ) + model.fit(training.loc[mask, list(POLICY_FEATURES)], training.loc[mask, "outcome"]) + pair.append(model) + models.append((pair[0], pair[1])) + return tuple(models) + + +def _zero_assignment(simulation: SimulationConfig) -> pd.DataFrame: + grid = pd.MultiIndex.from_product( + [range(simulation.n_periods), range(simulation.n_zones)], + names=["period_id", "zone_id"], + ).to_frame(index=False) + grid["treatment"] = 0.0 + grid["assigned_treatment"] = 0.0 + return grid + + +def _assignment_from_intensity( + base: pd.DataFrame, + intensity: np.ndarray, +) -> pd.DataFrame: + schedule = base[["zone_id", "period_id"]].copy() + schedule["treatment"] = np.asarray(intensity, dtype=float) + schedule["assigned_treatment"] = schedule["treatment"] + return schedule + + +def _ranked_full_budget_plan( + score: np.ndarray, + planning_cost: np.ndarray, + budget: float, +) -> np.ndarray: + if score.shape != planning_cost.shape: + raise ValueError("score and planning cost must align") + if not np.isfinite(score).all() or not np.isfinite(planning_cost).all(): + raise ValueError("policy scores and planning costs must be finite") + if (planning_cost <= 0).any(): + raise ValueError("policy planning costs must be positive") + order = np.lexsort((np.arange(len(score)), -(score / planning_cost))) + selected = np.zeros(len(score), dtype=float) + cumulative = 0.0 + # Slightly over-plan so the simulator's nonlinear cost path can scale the + # selected schedule to the same shared cap rather than systematically underspend. + target = 1.10 * budget + for index in order: + # A targeting policy is allowed to leave budget unused when its estimated + # incremental value is nonpositive. Forcing those cells into the plan + # would turn a maximum budget into a deployment quota. + if score[index] <= 0.0: + break + selected[index] = 1.0 + cumulative += planning_cost[index] + if cumulative >= target: + break + return selected + + +def _random_full_budget_plan( + planning_cost: np.ndarray, + budget: float, + *, + random_seed: int, +) -> np.ndarray: + """Select cells in an independent random order up to the planning cap.""" + + if not np.isfinite(planning_cost).all(): + raise ValueError("policy planning costs must be finite") + if (planning_cost <= 0).any(): + raise ValueError("policy planning costs must be positive") + selected = np.zeros(len(planning_cost), dtype=float) + cumulative = 0.0 + target = 1.10 * budget + order = np.random.default_rng(random_seed).permutation(len(planning_cost)) + for index in order: + selected[index] = 1.0 + cumulative += planning_cost[index] + if cumulative >= target: + break + return selected + + +def _ensemble_scores( + models: Sequence[tuple[RandomForestRegressor, RandomForestRegressor]], + features: pd.DataFrame, + config: MarketplacePolicyConfig, +) -> tuple[np.ndarray, np.ndarray, np.ndarray, float]: + predictions = np.vstack( + [ + treated.predict(features[list(POLICY_FEATURES)]) + - control.predict(features[list(POLICY_FEATURES)]) + for control, treated in models + ] + ) + mean = predictions.mean(axis=0) + instability = predictions.std(axis=0, ddof=1) + conservative = mean - config.instability_penalty * instability + return conservative, mean, instability, float(np.mean(instability)) + + +def _policy_allocations( + control: SimulationResult, + planning_cost: np.ndarray, + models: Sequence[tuple[RandomForestRegressor, RandomForestRegressor]], + config: MarketplacePolicyConfig, + *, + random_seed: int, +) -> tuple[dict[str, np.ndarray], dict[str, float]]: + base = control.panel + conservative, _, instability, mean_instability = _ensemble_scores( + models, + base, + config, + ) + rule_scores = ( + base["baseline_demand"].to_numpy(dtype=float) + * base["market_tightness"].to_numpy(dtype=float) + ) + allocations = { + "no_treatment": np.zeros(len(base), dtype=float), + "random": _random_full_budget_plan( + planning_cost, + config.budget, + random_seed=random_seed, + ), + "uniform": np.ones(len(base), dtype=float), + "rule_based": _ranked_full_budget_plan(rule_scores, planning_cost, config.budget), + "model_based": _ranked_full_budget_plan(conservative, planning_cost, config.budget), + } + model_selected = allocations["model_based"] > 0 + selected_instability = ( + float(instability[model_selected].mean()) if model_selected.any() else mean_instability + ) + + replicate_allocations = np.vstack( + [ + _ranked_full_budget_plan( + treated.predict(base[list(POLICY_FEATURES)]) + - control_model.predict(base[list(POLICY_FEATURES)]), + planning_cost, + config.budget, + ) + for control_model, treated in models + ] + ) + decision_instability = float( + replicate_allocations.std(axis=0, ddof=1).mean() + ) + diagnostics = { + "mean_model_instability": selected_instability, + "decision_instability": decision_instability, + } + return allocations, diagnostics + + +def _score_policy_market( + policy: str, + evaluated: SimulationResult, + control: SimulationResult, + *, + budget: float, + market_seed: int, + diagnostics: Mapping[str, float], +) -> dict[str, object]: + panel = evaluated.panel + baseline = control.panel + spend = float(panel["treatment_cost"].sum()) + incremental_trips = float(panel["trips"].sum() - baseline["trips"].sum()) + incremental_welfare = float(panel["welfare"].sum() - baseline["welfare"].sum()) + incremental_revenue = float( + panel["platform_net_revenue"].sum() + - baseline["platform_net_revenue"].sum() + ) + return { + "policy": policy, + "holdout_market_seed": market_seed, + "incremental_trips": incremental_trips, + "incremental_welfare": incremental_welfare, + "incremental_platform_net_revenue": incremental_revenue, + "budget_spent": spend, + "budget": budget, + "budget_feasible": spend <= budget + 1e-6, + "mean_treatment_intensity": float(panel["treatment"].mean()), + "treated_cell_share": float((panel["planned_treatment"] > 0).mean()), + "mean_wait_minutes_change": float( + panel["wait_minutes"].mean() - baseline["wait_minutes"].mean() + ), + "mean_model_instability": ( + diagnostics["mean_model_instability"] if policy == "model_based" else 0.0 + ), + "decision_instability": ( + diagnostics["decision_instability"] if policy == "model_based" else 0.0 + ), + "target_estimand": "full_horizon_incremental_trips", + "target_population_id": control.metadata["target_population_id"], + "n_zones": control.metadata["n_zones"], + "n_periods": control.metadata["n_periods"], + "weighting": "total across every configured zone-period", + "evidence_type": "semi_synthetic_policy_holdout_market", + } + + +def _pretreatment_planning_cost( + control: SimulationResult, + simulation: SimulationConfig, +) -> np.ndarray: + """Construct a positive cost proxy from pre-treatment state only.""" + + panel = control.panel + proxy = np.zeros(len(panel), dtype=float) + if simulation.treatment_version in { + TreatmentVersion.RIDER_DISCOUNT, + TreatmentVersion.BUNDLED, + }: + proxy += ( + panel["baseline_demand"].to_numpy(dtype=float) + * simulation.base_fare + * simulation.discount_rate + ) + if simulation.treatment_version in { + TreatmentVersion.DRIVER_INCENTIVE, + TreatmentVersion.BUNDLED, + }: + proxy += ( + panel["baseline_supply"].to_numpy(dtype=float) + * simulation.incentive_per_driver + ) + if not np.isfinite(proxy).all() or (proxy <= 0).any(): + raise ValueError("pre-treatment planning costs must be finite and positive") + return proxy + + +def run_marketplace_policy_evaluation( + simulation: SimulationConfig, + config: MarketplacePolicyConfig, + *, + n_train_markets: int = 12, + n_holdout_markets: int = 8, +) -> MarketplacePolicyResult: + """Return aggregate results and the paired holdout-market ledger.""" + + if n_train_markets < 2 or n_holdout_markets < 2: + raise ValueError("policy evaluation requires at least two train and holdout markets") + seeds = _seed_draws(config.seed, n_train_markets + n_holdout_markets) + train_seeds = seeds[:n_train_markets] + holdout_seeds = seeds[n_train_markets:] + if set(train_seeds).intersection(holdout_seeds): + raise AssertionError("training and holdout market seeds must be disjoint") + + training = _randomized_training_frame(simulation, config, train_seeds) + models = _fit_t_learner_ensemble(training, config) + market_rows: list[dict[str, object]] = [] + for holdout_index, seed in enumerate(holdout_seeds): + evaluation_config = replace(simulation, seed=seed, budget=config.budget) + control = simulate_market( + evaluation_config, + assignments=_zero_assignment(evaluation_config), + ) + planning_cost = _pretreatment_planning_cost(control, evaluation_config) + allocations, diagnostics = _policy_allocations( + control, + planning_cost, + models, + config, + random_seed=config.seed + 100_000 + holdout_index, + ) + for policy, intensity in allocations.items(): + evaluated = simulate_market( + evaluation_config, + assignments=_assignment_from_intensity(control.panel, intensity), + ) + market_rows.append( + _score_policy_market( + policy, + evaluated, + control, + budget=config.budget, + market_seed=seed, + diagnostics=diagnostics, + ) + ) + + market_results = pd.DataFrame(market_rows) + if set(market_results["policy"]) != set(POLICY_NAMES): + raise AssertionError("every declared baseline policy must be evaluated") + if not market_results["budget_feasible"].all(): + raise AssertionError("simulator policy evaluation exceeded the fixed budget") + + random_reference = market_results.loc[ + market_results["policy"] == "random", + ["holdout_market_seed", "incremental_trips"], + ].rename(columns={"incremental_trips": "random_incremental_trips"}) + market_results = market_results.merge( + random_reference, + on="holdout_market_seed", + how="left", + validate="many_to_one", + ) + market_results["paired_incremental_outcome_vs_random"] = ( + market_results["incremental_trips"] + - market_results["random_incremental_trips"] + ) + + rows: list[dict[str, object]] = [] + for policy, group in market_results.groupby("policy", sort=True): + total_spend = float(group["budget_spent"].sum()) + total_increment = float(group["incremental_trips"].sum()) + expected = float(group["incremental_trips"].mean()) + paired = group["paired_incremental_outcome_vs_random"] + rows.append( + { + "policy": policy, + "expected_incremental_outcome": expected, + "incremental_outcome_sd": float(group["incremental_trips"].std(ddof=1)), + "incremental_outcome_se": float( + group["incremental_trips"].std(ddof=1) / np.sqrt(len(group)) + ), + "incremental_outcome_p10": float(group["incremental_trips"].quantile(0.10)), + "incremental_welfare": float(group["incremental_welfare"].mean()), + "incremental_platform_net_revenue": float( + group["incremental_platform_net_revenue"].mean() + ), + "budget_spent": float(group["budget_spent"].mean()), + "budget": config.budget, + "budget_efficiency": ( + total_increment / total_spend if total_spend else np.nan + ), + "budget_feasible": bool(group["budget_feasible"].all()), + "mean_treatment_intensity": float(group["mean_treatment_intensity"].mean()), + "treated_cell_share": float(group["treated_cell_share"].mean()), + "mean_wait_minutes_change": float(group["mean_wait_minutes_change"].mean()), + "mean_model_instability": float(group["mean_model_instability"].mean()), + "decision_instability": float(group["decision_instability"].mean()), + "training_markets": n_train_markets, + "training_rows": len(training), + "holdout_markets": n_holdout_markets, + "evaluation_complete": len(group) == n_holdout_markets, + "incremental_outcome_vs_random": float(paired.mean()), + "paired_difference_se_vs_random": float( + paired.std(ddof=1) / np.sqrt(len(paired)) + ), + "paired_difference_p10_vs_random": float(paired.quantile(0.10)), + "training_market_seeds": json.dumps(list(train_seeds)), + "holdout_market_seeds": json.dumps(list(holdout_seeds)), + "training_signal": "randomized observed outcomes; no structural truth columns", + "evaluation_engine": "full marketplace simulator rerun per policy and seed", + "planning_cost_basis": ( + "pre-treatment baseline demand/supply and configured treatment prices; " + "no treated holdout counterfactual" + ), + "model": "random_forest_t_learner_ensemble", + "target_estimand": "full_horizon_incremental_trips", + "target_population_id": group["target_population_id"].iloc[0], + "n_zones": simulation.n_zones, + "n_periods": simulation.n_periods, + "weighting": "mean of paired full-horizon market totals across holdout seeds", + "simulation_config": json.dumps(simulation.to_dict(), sort_keys=True), + "policy_config": json.dumps(asdict(config), sort_keys=True), + "evidence_type": "semi_synthetic_policy_holdout", + } + ) + result = pd.DataFrame(rows).sort_values("policy").reset_index(drop=True) + result["policy_eligible"] = ( + result["budget_feasible"] + & result["evaluation_complete"] + & np.isfinite(result["expected_incremental_outcome"]) + ) + return MarketplacePolicyResult(result, market_results) + + +def run_marketplace_policy_benchmark( + simulation: SimulationConfig, + config: MarketplacePolicyConfig, + *, + n_train_markets: int = 12, + n_holdout_markets: int = 8, +) -> pd.DataFrame: + """Fit on randomized markets and return the aggregate honest-holdout table.""" + + return run_marketplace_policy_evaluation( + simulation, + config, + n_train_markets=n_train_markets, + n_holdout_markets=n_holdout_markets, + ).summary + + +def run_treatment_version_policy_evaluation( + simulation: SimulationConfig, + config: MarketplacePolicyConfig, + *, + treatment_versions: Sequence[TreatmentVersion | str] = ( + TreatmentVersion.RIDER_DISCOUNT, + TreatmentVersion.DRIVER_INCENTIVE, + TreatmentVersion.BUNDLED, + ), + n_train_markets: int = 12, + n_holdout_markets: int = 8, +) -> TreatmentVersionPolicyResult: + """Evaluate every policy under rider, driver, and bundled interventions. + + The same training and holdout seed schedule is reused across versions. This makes + latent-market draws paired when geometry is unchanged while fitting a separate + learner for each treatment version. Version comparisons remain conditional on the + simulator's declared response functions; they are not empirical dose-response + estimates. + """ + + versions = tuple(TreatmentVersion.parse(value) for value in treatment_versions) + if not versions: + raise ValueError("at least one treatment version is required") + if len(set(versions)) != len(versions): + raise ValueError("treatment versions must be unique") + summaries: list[pd.DataFrame] = [] + ledgers: list[pd.DataFrame] = [] + expected_training_seeds: str | None = None + expected_holdout_seeds: str | None = None + for version in versions: + version_config = replace(simulation, treatment_version=version) + evaluated = run_marketplace_policy_evaluation( + version_config, + config, + n_train_markets=n_train_markets, + n_holdout_markets=n_holdout_markets, + ) + summary = evaluated.summary.copy() + summary["treatment_version"] = version.value + summary["version_pairing"] = ( + "common training/holdout market seeds across intervention versions" + ) + summary["version_evidence_scope"] = ( + "semi-synthetic response-function sensitivity; not an empirical dose response" + ) + ledger = evaluated.market_results.copy() + ledger["treatment_version"] = version.value + ledger["version_pairing"] = ( + "common training/holdout market seeds across intervention versions" + ) + current_training_seeds = str(summary["training_market_seeds"].iloc[0]) + current_holdout_seeds = str(summary["holdout_market_seeds"].iloc[0]) + if expected_training_seeds is None: + expected_training_seeds = current_training_seeds + expected_holdout_seeds = current_holdout_seeds + elif ( + current_training_seeds != expected_training_seeds + or current_holdout_seeds != expected_holdout_seeds + ): + raise AssertionError("treatment-version evaluation lost common market seeds") + summaries.append(summary) + ledgers.append(ledger) + return TreatmentVersionPolicyResult( + summary=pd.concat(summaries, ignore_index=True), + market_results=pd.concat(ledgers, ignore_index=True), + ) + + +__all__ = [ + "MarketplacePolicyConfig", + "MarketplacePolicyResult", + "TreatmentVersionPolicyResult", + "run_marketplace_policy_benchmark", + "run_marketplace_policy_evaluation", + "run_treatment_version_policy_evaluation", +] diff --git a/CasualLab/src/casuallab/nyc_benchmark.py b/CasualLab/src/casuallab/nyc_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..bd096bcbb4e28fd0637d53f47ab75671c126f57d --- /dev/null +++ b/CasualLab/src/casuallab/nyc_benchmark.py @@ -0,0 +1,1100 @@ +"""Fail-closed NYC-informed known-truth marketplace benchmarks. + +The NYC simulation anchor contributes descriptive scale and heterogeneity +initializers. Causal effects in this benchmark remain structural simulator truths +under explicit assumptions; they are never described as effects estimated from NYC +trip records. This module is independent of the default marketplace benchmark entry +points so it cannot silently change the Chicago/sample workflow. +""" + +from __future__ import annotations + +import json +import math +import re +import shutil +import tempfile +from collections.abc import Mapping +from dataclasses import dataclass, replace +from numbers import Integral, Real +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd + +from casuallab.benchmark import BenchmarkConfig +from casuallab.config import DesignName, SimulationConfig, load_simulation_config +from casuallab.data import sha256_file +from casuallab.marketplace_benchmark import ( + MarketplaceBenchmarkResult, + SensitivityScenario, + run_marketplace_benchmark, +) +from casuallab.nyc_simulation import ( + ANCHOR_EVIDENCE_LABEL, + ANCHOR_SCHEMA_VERSION, + CAUSAL_ASSUMPTION_FIELDS, + NYCSimulationAnchorSettings, + build_nyc_simulation_anchor, +) + +NYC_BENCHMARK_EVIDENCE_TYPE = ( + "semi_synthetic_nyc_informed_known_truth_monte_carlo" +) +NYC_BENCHMARK_SCHEMA_VERSION = "1.0.0" +_VALIDATED_ANCHOR_STATUS = ( + "descriptive_control_path_anchor_validated_not_fitted_structural_model" +) +_HASH_PATTERN = re.compile(r"[0-9a-f]{64}") + + +@dataclass(frozen=True, slots=True) +class NYCBenchmarkConfig: + """Laptop-safe orchestration settings for an NYC-informed benchmark. + + Geometry is an explicit simulation-size override and cannot exceed the anchor + geometry. The default 16 x 48 panel supplies eight geographic clusters and + twelve four-hour blocks for the repository's standard anchor while remaining + inexpensive enough for focused local runs. + """ + + replications: int = 6 + seed: int = 870221 + confidence_level: float = 0.95 + designs: tuple[str, ...] = ("geo_cluster", "geo_time") + estimators: tuple[str, ...] = ( + "cluster_robust", + "two_way_cluster_robust", + ) + n_zones: int | None = 16 + n_periods: int | None = 48 + cost_per_market_period: float = 1.0 + max_replications: int = 32 + max_panel_cells: int = 4096 + max_planned_fits: int = 256 + + def __post_init__(self) -> None: + integer_fields = ( + "replications", + "seed", + "max_replications", + "max_panel_cells", + "max_planned_fits", + ) + for name in integer_fields: + value = getattr(self, name) + if isinstance(value, bool) or not isinstance(value, Integral): + raise ValueError(f"{name} must be an integer") + for name in ("n_zones", "n_periods"): + value = getattr(self, name) + if value is not None and ( + isinstance(value, bool) or not isinstance(value, Integral) + ): + raise ValueError(f"{name} must be an integer when supplied") + if self.replications < 2: + raise ValueError("replications must be at least two") + if self.max_replications < 2 or self.replications > self.max_replications: + raise ValueError("replications exceed the declared laptop-safe maximum") + if self.max_panel_cells < 1 or self.max_planned_fits < 1: + raise ValueError("laptop-safety limits must be positive") + if self.n_zones is not None and self.n_zones < 4: + raise ValueError("n_zones must be at least four when supplied") + if self.n_zones is not None and self.n_zones % 2: + raise ValueError("n_zones must be even for two-zones-per-cluster geometry") + if self.n_periods is not None and self.n_periods < 2: + raise ValueError("n_periods must be at least two when supplied") + if not isinstance(self.confidence_level, Real) or not math.isfinite( + float(self.confidence_level) + ): + raise ValueError("confidence_level must be finite") + if not 0.5 < self.confidence_level < 1.0: + raise ValueError("confidence_level must lie in (0.5, 1)") + if not isinstance(self.cost_per_market_period, Real) or not math.isfinite( + float(self.cost_per_market_period) + ): + raise ValueError("cost_per_market_period must be finite") + if self.cost_per_market_period <= 0: + raise ValueError("cost_per_market_period must be positive") + if not self.designs or not self.estimators: + raise ValueError("at least one design and estimator are required") + canonical_designs = tuple(DesignName.parse(value).value for value in self.designs) + if len(canonical_designs) != len(set(canonical_designs)): + raise ValueError("designs must not contain aliases of the same design") + canonical_estimators = tuple( + str(value).strip().lower().replace("-", "_").replace(" ", "_") + for value in self.estimators + ) + if any(not value for value in canonical_estimators): + raise ValueError("estimator names must not be empty") + if len(canonical_estimators) != len(set(canonical_estimators)): + raise ValueError("estimators must not contain duplicates") + object.__setattr__(self, "designs", canonical_designs) + object.__setattr__(self, "estimators", canonical_estimators) + + def to_dict(self) -> dict[str, Any]: + return { + "replications": int(self.replications), + "seed": int(self.seed), + "confidence_level": float(self.confidence_level), + "designs": list(self.designs), + "estimators": list(self.estimators), + "n_zones": None if self.n_zones is None else int(self.n_zones), + "n_periods": None if self.n_periods is None else int(self.n_periods), + "cost_per_market_period": float(self.cost_per_market_period), + "max_replications": int(self.max_replications), + "max_panel_cells": int(self.max_panel_cells), + "max_planned_fits": int(self.max_planned_fits), + } + + +@dataclass(frozen=True, slots=True) +class NYCBenchmarkResult: + """NYC-labeled benchmark tables and serializable provenance metadata.""" + + records: pd.DataFrame + summary: pd.DataFrame + failures: pd.DataFrame + fit_ledger: pd.DataFrame + metadata: Mapping[str, Any] + + +@dataclass(frozen=True, slots=True) +class _VerifiedAnchor: + payload: Mapping[str, Any] + simulation: SimulationConfig + template: SimulationConfig + hashes: Mapping[str, str] + project_root: Path + + +def _load_json(path: Path, label: str) -> dict[str, Any]: + if not path.is_file(): + raise FileNotFoundError(f"{label} is required: {path}") + try: + value = json.loads(path.read_text(encoding="utf-8")) + except (json.JSONDecodeError, OSError) as exc: + raise ValueError(f"{label} is not readable valid JSON") from exc + if not isinstance(value, dict): + raise ValueError(f"{label} must be a JSON object") + return value + + +def _hash(value: Any, label: str) -> str: + if not isinstance(value, str) or _HASH_PATTERN.fullmatch(value) is None: + raise ValueError(f"{label} must be a lowercase SHA-256 digest") + return value + + +def _portable_path(value: Any, label: str) -> Path: + if not isinstance(value, str) or not value: + raise ValueError(f"{label} must be a nonempty path string") + path = Path(value) + if path.is_absolute() or ".." in path.parts: + raise ValueError(f"{label} must be project-relative and portable") + return path + + +def _project_relative_path(path: Path, root: Path, label: str) -> str: + """Render one resolved input path relative to its verified project root.""" + + resolved = path.resolve() + try: + relative = resolved.relative_to(root.resolve()) + except ValueError as exc: + raise ValueError(f"{label} must be contained by the verified project root") from exc + if not relative.parts or relative == Path("."): + raise ValueError(f"{label} must identify a file below the project root") + return relative.as_posix() + + +def _manifest_root( + manifest: Mapping[str, Any], + anchor_path: Path, + project_root: str | Path | None, +) -> Path: + entries = manifest.get("files") + if not isinstance(entries, list) or not entries: + raise ValueError("NYC anchor manifest has no file entries") + target = anchor_path.resolve() + candidate_roots = ( + (Path(project_root).resolve(),) + if project_root is not None + else tuple(target.parents) + ) + matches: list[Path] = [] + for root in candidate_roots: + for index, raw in enumerate(entries): + if not isinstance(raw, Mapping): + raise ValueError("NYC anchor manifest contains a non-object entry") + relative = _portable_path( + raw.get("path"), f"NYC anchor manifest.files[{index}].path" + ) + resolved = (root / relative).resolve() + try: + resolved.relative_to(root) + except ValueError as exc: + raise ValueError("NYC anchor manifest entry escapes its root") from exc + if resolved == target: + matches.append(root) + unique = tuple(dict.fromkeys(matches)) + if len(unique) != 1: + raise ValueError("could not resolve one unambiguous NYC anchor manifest root") + return unique[0] + + +def _verify_manifest_files( + manifest: Mapping[str, Any], root: Path +) -> dict[Path, dict[str, Any]]: + raw_entries = manifest.get("files") + if not isinstance(raw_entries, list) or not raw_entries: + raise ValueError("NYC anchor manifest.files must be a nonempty list") + verified: dict[Path, dict[str, Any]] = {} + for index, raw in enumerate(raw_entries): + if not isinstance(raw, Mapping): + raise ValueError("NYC anchor manifest contains a non-object entry") + entry = dict(raw) + relative = _portable_path( + entry.get("path"), f"NYC anchor manifest.files[{index}].path" + ) + resolved = (root / relative).resolve() + try: + resolved.relative_to(root) + except ValueError as exc: + raise ValueError("NYC anchor manifest entry escapes its project root") from exc + if resolved in verified: + raise ValueError("NYC anchor manifest contains duplicate paths") + byte_count = entry.get("bytes") + if isinstance(byte_count, bool) or not isinstance(byte_count, int) or byte_count < 0: + raise ValueError("NYC anchor manifest contains an invalid byte count") + expected_sha = _hash(entry.get("sha256"), "NYC anchor manifest file hash") + if not resolved.is_file(): + raise FileNotFoundError(f"NYC anchor manifest file is missing: {resolved}") + if resolved.stat().st_size != byte_count: + raise ValueError(f"NYC anchor manifest byte mismatch: {relative}") + if sha256_file(resolved) != expected_sha: + raise ValueError(f"NYC anchor manifest SHA-256 mismatch: {relative}") + verified[resolved] = entry + return verified + + +def _unique_file_by_hash( + files: Mapping[Path, Mapping[str, Any]], digest: str, label: str +) -> Path: + matches = [path for path, entry in files.items() if entry.get("sha256") == digest] + if len(matches) != 1: + raise ValueError(f"NYC anchor manifest must identify exactly one {label}") + return matches[0] + + +def _verify_anchor( + anchor_path: str | Path, + anchor_manifest_path: str | Path, + *, + project_root: str | Path | None, + expected_anchor_sha256: str | None, + expected_anchor_manifest_sha256: str | None, +) -> _VerifiedAnchor: + anchor_file = Path(anchor_path).resolve() + manifest_file = Path(anchor_manifest_path).resolve() + anchor_sha = sha256_file(anchor_file) + manifest_sha = sha256_file(manifest_file) + if expected_anchor_sha256 is not None and anchor_sha != _hash( + expected_anchor_sha256, "expected_anchor_sha256" + ): + raise ValueError("NYC anchor SHA-256 disagrees with the external pin") + if expected_anchor_manifest_sha256 is not None and manifest_sha != _hash( + expected_anchor_manifest_sha256, "expected_anchor_manifest_sha256" + ): + raise ValueError("NYC anchor manifest SHA-256 disagrees with the external pin") + + anchor = _load_json(anchor_file, "NYC simulation anchor") + manifest = _load_json(manifest_file, "NYC simulation anchor manifest") + metadata = manifest.get("metadata") + if not isinstance(metadata, Mapping): + raise ValueError("NYC anchor manifest metadata is missing") + if ( + anchor.get("schema_version") != ANCHOR_SCHEMA_VERSION + or anchor.get("evidence_label") != ANCHOR_EVIDENCE_LABEL + or anchor.get("causal_claim") is not False + or anchor.get("status") != _VALIDATED_ANCHOR_STATUS + or metadata.get("evidence_label") != ANCHOR_EVIDENCE_LABEL + or metadata.get("causal_claim") is not False + or metadata.get("status") != _VALIDATED_ANCHOR_STATUS + ): + raise ValueError("NYC anchor evidence contract is incompatible") + + root = _manifest_root(manifest, anchor_file, project_root) + files = _verify_manifest_files(manifest, root) + if anchor_file not in files or files[anchor_file].get("sha256") != anchor_sha: + raise ValueError("NYC anchor is not covered by its manifest") + calibration_sha = _hash( + metadata.get("calibration_sha256"), "NYC anchor calibration_sha256" + ) + calibration_manifest_sha = _hash( + metadata.get("calibration_manifest_sha256"), + "NYC anchor calibration_manifest_sha256", + ) + template_sha = _hash( + metadata.get("simulation_config_sha256"), + "NYC anchor simulation_config_sha256", + ) + source_manifest_sha = _hash( + metadata.get("source_data_manifest_sha256"), + "NYC anchor source_data_manifest_sha256", + ) + calibration_file = _unique_file_by_hash(files, calibration_sha, "calibration file") + calibration_manifest_file = _unique_file_by_hash( + files, calibration_manifest_sha, "calibration manifest" + ) + template_file = _unique_file_by_hash(files, template_sha, "simulation template") + template = load_simulation_config(template_file) + + target_panel = anchor.get("target_panel") + if not isinstance(target_panel, Mapping) or not isinstance( + target_panel.get("simulation"), Mapping + ): + raise ValueError("NYC anchor target simulation geometry is missing") + target = target_panel["simulation"] + integer_values: dict[str, int] = {} + for key in ("n_zones", "n_periods", "seed"): + value = target.get(key) + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError(f"NYC anchor target_panel.simulation.{key} must be an integer") + integer_values[key] = value + integrity = anchor.get("integrity") + if not isinstance(integrity, Mapping): + raise ValueError("NYC anchor integrity section is missing") + root_mode = integrity.get("project_root_resolution") + if root_mode not in {"explicit", "inferred_from_portable_source_manifest_path"}: + raise ValueError("NYC anchor project-root provenance is invalid") + rebuilt = build_nyc_simulation_anchor( + calibration_file, + project_root=(root if root_mode == "explicit" else None), + manifest_path=calibration_manifest_file, + settings=NYCSimulationAnchorSettings( + target_n_zones=integer_values["n_zones"], + target_n_periods=integer_values["n_periods"], + seed=integer_values["seed"], + ), + assumption_template=template, + ) + if rebuilt != anchor: + raise ValueError( + "NYC anchor does not exactly reconstruct from its calibration and template lineage" + ) + if rebuilt["integrity"]["source_data_manifest_sha256"] != source_manifest_sha: + raise ValueError("NYC anchor source-data manifest hash disagrees with metadata") + simulation = SimulationConfig.from_dict(rebuilt["simulation_config"]) + return _VerifiedAnchor( + payload=rebuilt, + simulation=simulation, + template=template, + hashes={ + "anchor_sha256": anchor_sha, + "anchor_manifest_sha256": manifest_sha, + "calibration_sha256": calibration_sha, + "calibration_manifest_sha256": calibration_manifest_sha, + "simulation_template_sha256": template_sha, + "source_data_manifest_sha256": source_manifest_sha, + }, + project_root=root, + ) + + +def validate_nyc_benchmark_anchor( + anchor_path: str | Path, + anchor_manifest_path: str | Path, + *, + project_root: str | Path | None = None, + expected_anchor_sha256: str | None = None, + expected_anchor_manifest_sha256: str | None = None, +) -> dict[str, Any]: + """Validate and exactly reconstruct an NYC anchor for benchmark use.""" + + verified = _verify_anchor( + anchor_path, + anchor_manifest_path, + project_root=project_root, + expected_anchor_sha256=expected_anchor_sha256, + expected_anchor_manifest_sha256=expected_anchor_manifest_sha256, + ) + return { + "schema_version": NYC_BENCHMARK_SCHEMA_VERSION, + "evidence_label": ANCHOR_EVIDENCE_LABEL, + "causal_claim": False, + "exact_reconstruction_passed": True, + "hashes": dict(verified.hashes), + "simulation_config": verified.simulation.to_dict(), + } + + +def default_nyc_benchmark_scenarios( + anchor_simulation: SimulationConfig, +) -> tuple[SensitivityScenario, ...]: + """Return one anchor-assumption scenario and one identification reference.""" + + return ( + SensitivityScenario( + "anchor_explicit_assumptions", + spillover_strength=anchor_simulation.spillover_strength, + persistence=anchor_simulation.persistence, + varied_dimension="anchor_explicit_causal_assumptions", + ), + SensitivityScenario( + "no_interference_no_carryover", + spillover_strength=0.0, + persistence=0.0, + varied_dimension="reference", + ), + ) + + +def _effective_base( + anchor: SimulationConfig, + config: NYCBenchmarkConfig, +) -> tuple[SimulationConfig, dict[str, Any]]: + n_zones = min(16, anchor.n_zones) if config.n_zones is None else int(config.n_zones) + n_periods = ( + min(48, anchor.n_periods) if config.n_periods is None else int(config.n_periods) + ) + if n_zones > anchor.n_zones or n_periods > anchor.n_periods: + raise ValueError("NYC benchmark geometry cannot exceed the validated anchor geometry") + if n_zones < 4 or n_zones % 2: + raise ValueError("effective NYC benchmark n_zones must be even and at least four") + if n_zones * n_periods > config.max_panel_cells: + raise ValueError("NYC benchmark panel exceeds max_panel_cells") + geographic_clusters = n_zones // 2 + design = replace( + anchor.design, + n_clusters=geographic_clusters, + cluster_size=2, + budget=None, + seed=config.seed + 1, + ) + effective = replace( + anchor, + n_zones=n_zones, + n_periods=n_periods, + budget=None, + seed=config.seed, + design=design, + ) + for field in CAUSAL_ASSUMPTION_FIELDS: + if getattr(effective, field) != getattr(anchor, field): + raise RuntimeError(f"NYC benchmark changed causal anchor field {field!r}") + overrides = { + "n_zones": { + "anchor": anchor.n_zones, + "effective": n_zones, + "scope": "laptop_safe_geometry_override", + }, + "n_periods": { + "anchor": anchor.n_periods, + "effective": n_periods, + "scope": "laptop_safe_geometry_override", + }, + "seed": { + "anchor": anchor.seed, + "effective": config.seed, + "scope": "benchmark_monte_carlo_seed", + }, + "budget": { + "anchor": anchor.effective_budget, + "effective": None, + "scope": "unconstrained_estimator_recovery", + }, + "design.n_clusters": { + "anchor": anchor.design.n_clusters, + "effective": geographic_clusters, + "scope": "two_zones_per_geographic_cluster", + }, + "design.cluster_size": { + "anchor": anchor.design.cluster_size, + "effective": 2, + "scope": "two_zones_per_geographic_cluster", + }, + "design.seed": { + "anchor": anchor.design.seed, + "effective": config.seed + 1, + "scope": "benchmark_assignment_seed", + }, + } + return effective, overrides + + +def _scenario_causal_values( + base: SimulationConfig, scenario: SensitivityScenario +) -> dict[str, Any]: + values = {field: getattr(base, field) for field in CAUSAL_ASSUMPTION_FIELDS} + values["spillover_strength"] = scenario.spillover_strength + values["persistence"] = scenario.persistence + if scenario.spillover_strength == 0: + values["rider_substitution"] = 0.0 + values["driver_mobility"] = 0.0 + if scenario.treatment_version is not None: + values["treatment_version"] = scenario.treatment_version + return { + key: (value.value if hasattr(value, "value") else value) + for key, value in values.items() + } + + +def _scenario_provenance( + anchor: SimulationConfig, + scenarios: tuple[SensitivityScenario, ...], +) -> dict[str, dict[str, Any]]: + anchor_values = { + field: ( + getattr(anchor, field).value + if hasattr(getattr(anchor, field), "value") + else getattr(anchor, field) + ) + for field in CAUSAL_ASSUMPTION_FIELDS + } + result: dict[str, dict[str, Any]] = {} + for scenario in scenarios: + effective = _scenario_causal_values(anchor, scenario) + overrides = { + field: {"anchor": anchor_values[field], "effective": effective[field]} + for field in CAUSAL_ASSUMPTION_FIELDS + if effective[field] != anchor_values[field] + } + result[scenario.name] = { + "anchor_causal_assumptions_preserved": not overrides, + "causal_overrides": overrides, + "interpretation": ( + "All causal quantities are explicit simulator assumptions, including " + "declared sensitivity overrides; none is an NYC causal estimate." + ), + } + return result + + +def _validate_scenario_geometry( + base: SimulationConfig, + anchor: SimulationConfig, + config: NYCBenchmarkConfig, + scenarios: tuple[SensitivityScenario, ...], +) -> None: + planned_fits = ( + config.replications + * len(scenarios) + * len(config.designs) + * len(config.estimators) + ) + if planned_fits > config.max_planned_fits: + raise ValueError("NYC benchmark plan exceeds max_planned_fits") + for scenario in scenarios: + clusters = scenario.n_clusters or base.design.n_clusters or 4 + n_zones = max(4, 2 * int(clusters)) + if n_zones > anchor.n_zones: + raise ValueError( + f"scenario {scenario.name!r} exceeds the validated anchor zone geometry" + ) + if n_zones * base.n_periods > config.max_panel_cells: + raise ValueError(f"scenario {scenario.name!r} exceeds max_panel_cells") + + +def _target_gates( + result: MarketplaceBenchmarkResult, + config: NYCBenchmarkConfig, + anchor: SimulationConfig, +) -> dict[str, bool]: + records = result.records + summary = result.summary + ledger = result.fit_ledger + no_runtime_failures = bool(result.failures.empty) + records_present = bool(not records.empty and not summary.empty) + target_consistent = bool( + records_present + and records["target_estimand"].eq("market_total_effect").all() + and summary["target_estimand"].eq("market_total_effect").all() + ) + known_truth_finite = bool( + records_present + and np.isfinite(records["truth"].to_numpy(dtype=float)).all() + ) + applicable = ledger.loc[ledger["applicable"].astype(bool)] + complete_fits = bool( + not applicable.empty + and applicable["fit_complete"].astype(bool).all() + and applicable["attempted_fits"].eq(config.replications).all() + and applicable["successful_fits"].eq(config.replications).all() + ) + identified = summary["identified"].astype(bool) if records_present else pd.Series(dtype=bool) + inference_valid = ( + summary["inference_valid"].astype(bool) + if records_present + else pd.Series(dtype=bool) + ) + at_least_one_valid_target = bool((identified & inference_valid).any()) + identified_metrics_finite = bool( + identified.any() + and np.isfinite( + summary.loc[identified, ["bias", "rmse", "truth"]].to_numpy(dtype=float) + ).all() + ) + mismatch = ~identified + mismatch_metrics_masked = bool( + not mismatch.any() + or summary.loc[mismatch, ["bias", "rmse", "coverage", "power"]] + .isna() + .all() + .all() + ) + geometry_bounded = bool( + records_present + and records["n_zones"].le(anchor.n_zones).all() + and records["n_periods"].le(anchor.n_periods).all() + and ( + records["n_zones"].astype(int) * records["n_periods"].astype(int) + ).le(config.max_panel_cells).all() + ) + gates = { + "no_runtime_failures": no_runtime_failures, + "records_present": records_present, + "target_estimand_is_market_total_effect": target_consistent, + "known_truth_finite": known_truth_finite, + "applicable_fit_plan_complete": complete_fits, + "at_least_one_identified_inference_valid_cell": at_least_one_valid_target, + "identified_target_metrics_finite": identified_metrics_finite, + "target_mismatch_metrics_masked": mismatch_metrics_masked, + "effective_geometry_within_anchor_and_laptop_limit": geometry_bounded, + } + gates["all_passed"] = all(gates.values()) + return gates + + +def _label_frame( + frame: pd.DataFrame, + *, + hashes: Mapping[str, str], + anchor: SimulationConfig, + base: SimulationConfig, + overrides: Mapping[str, Any], + scenario_provenance: Mapping[str, Mapping[str, Any]], +) -> pd.DataFrame: + labeled = frame.copy() + labeled["evidence_type"] = NYC_BENCHMARK_EVIDENCE_TYPE + labeled["anchor_evidence_label"] = ANCHOR_EVIDENCE_LABEL + labeled["nyc_empirical_causal_effect"] = False + labeled["simulator_known_truth"] = True + labeled["known_truth_scope"] = ( + "structural simulator counterfactual under explicit assumptions; not an NYC causal estimate" + ) + for key, value in hashes.items(): + labeled[f"nyc_{key}"] = value + labeled["anchor_config_n_zones"] = anchor.n_zones + labeled["anchor_config_n_periods"] = anchor.n_periods + labeled["benchmark_base_n_zones"] = base.n_zones + labeled["benchmark_base_n_periods"] = base.n_periods + labeled["benchmark_base_overrides"] = json.dumps( + overrides, sort_keys=True, separators=(",", ":") + ) + if "scenario" in labeled: + labeled["scenario_causal_provenance"] = labeled["scenario"].map( + { + name: json.dumps(value, sort_keys=True, separators=(",", ":")) + for name, value in scenario_provenance.items() + } + ) + if labeled["scenario_causal_provenance"].isna().any(): + raise RuntimeError("NYC benchmark result contains an undeclared scenario") + labeled["target_gate_all_passed"] = True + return labeled + + +def run_nyc_informed_marketplace_benchmark( + anchor_path: str | Path, + anchor_manifest_path: str | Path, + *, + config: NYCBenchmarkConfig | None = None, + scenarios: tuple[SensitivityScenario, ...] | None = None, + project_root: str | Path | None = None, + expected_anchor_sha256: str | None = None, + expected_anchor_manifest_sha256: str | None = None, +) -> NYCBenchmarkResult: + """Run a deterministic NYC-informed benchmark after exact anchor reconstruction.""" + + runtime = config or NYCBenchmarkConfig() + verified = _verify_anchor( + anchor_path, + anchor_manifest_path, + project_root=project_root, + expected_anchor_sha256=expected_anchor_sha256, + expected_anchor_manifest_sha256=expected_anchor_manifest_sha256, + ) + base, overrides = _effective_base(verified.simulation, runtime) + selected = ( + default_nyc_benchmark_scenarios(verified.simulation) + if scenarios is None + else tuple(scenarios) + ) + if not selected: + raise ValueError("at least one NYC benchmark scenario is required") + names = [scenario.name for scenario in selected] + if len(names) != len(set(names)): + raise ValueError("NYC benchmark scenario names must be unique") + _validate_scenario_geometry(base, verified.simulation, runtime, selected) + scenario_provenance = _scenario_provenance(verified.simulation, selected) + benchmark = BenchmarkConfig( + replications=runtime.replications, + seed=runtime.seed, + confidence_level=runtime.confidence_level, + designs=runtime.designs, + estimators=runtime.estimators, + target_estimand="market_total_effect", + cost_per_market_period=runtime.cost_per_market_period, + ) + raw = run_marketplace_benchmark(benchmark, base, scenarios=selected) + gates = _target_gates(raw, runtime, verified.simulation) + if not gates["all_passed"]: + failed = sorted(key for key, passed in gates.items() if not passed) + details = ( + raw.failures.to_dict(orient="records")[:3] + if not raw.failures.empty + else [] + ) + raise RuntimeError( + f"NYC benchmark target gates failed: {failed}; failures={details}" + ) + + label_kwargs = { + "hashes": verified.hashes, + "anchor": verified.simulation, + "base": base, + "overrides": overrides, + "scenario_provenance": scenario_provenance, + } + records = _label_frame(raw.records, **label_kwargs) + summary = _label_frame(raw.summary, **label_kwargs) + failures = _label_frame(raw.failures, **label_kwargs) + fit_ledger = _label_frame(raw.fit_ledger, **label_kwargs) + metadata = { + "schema_version": NYC_BENCHMARK_SCHEMA_VERSION, + "evidence_type": NYC_BENCHMARK_EVIDENCE_TYPE, + "nyc_empirical_causal_effect": False, + "simulator_known_truth": True, + "known_truth_estimand": "market_total_effect", + "known_truth_scope": ( + "structural simulator counterfactual under explicit assumptions; " + "not an NYC causal estimate" + ), + "anchor": { + "evidence_label": ANCHOR_EVIDENCE_LABEL, + "exact_reconstruction_passed": True, + "anchor_path": _project_relative_path( + Path(anchor_path), verified.project_root, "anchor_path" + ), + "anchor_manifest_path": _project_relative_path( + Path(anchor_manifest_path), + verified.project_root, + "anchor_manifest_path", + ), + "hashes": dict(verified.hashes), + "simulation_config": verified.simulation.to_dict(), + }, + "benchmark_config": runtime.to_dict(), + "benchmark_base_simulation_config": base.to_dict(), + "effective_overrides": overrides, + "scenario_causal_provenance": scenario_provenance, + "target_gates": gates, + "limitations": [ + "NYC records supply descriptive initialization moments, not causal effects.", + "Known truth exists only inside the declared structural simulator.", + "Geometry reduction is a computational design choice, not an empirical sample.", + "Sensitivity overrides are explicit assumptions and are not learned from NYC data.", + ], + } + return NYCBenchmarkResult(records, summary, failures, fit_ledger, metadata) + + +def _artifact_json_safe(value: Any) -> Any: + if isinstance(value, Path): + return str(value) + if isinstance(value, Mapping): + return {str(key): _artifact_json_safe(item) for key, item in value.items()} + if isinstance(value, (list, tuple, set, frozenset)): + return [_artifact_json_safe(item) for item in value] + if isinstance(value, (np.integer, np.floating, np.bool_)): + return value.item() + if hasattr(value, "value"): + return _artifact_json_safe(value.value) + return value + + +def _artifact_output_path( + output_dir: str | Path, + project_root: str | Path | None, +) -> tuple[Path, str]: + root = ( + Path(project_root).resolve() + if project_root is not None + else Path.cwd().resolve() + ) + raw = Path(output_dir) + output = ((root / raw) if not raw.is_absolute() else raw).resolve() + if output.parent == output: + raise ValueError("artifact output_dir must not be a filesystem root") + if output == Path.cwd().resolve(): + raise ValueError("artifact output_dir must not overwrite the current workspace") + if output == root: + raise ValueError("artifact output_dir must not overwrite project_root") + try: + portable = output.relative_to(root).as_posix() + except ValueError as exc: + raise ValueError("artifact output_dir must be contained by project_root") from exc + if output.exists() and not output.is_dir(): + raise ValueError("artifact output_dir exists and is not a directory") + return output, portable + + +def _artifact_project_root(project_root: str | Path | None) -> Path: + return ( + Path(project_root).resolve() + if project_root is not None + else Path.cwd().resolve() + ) + + +def _artifact_input_entry( + path: Path, + *, + project_root: Path, + expected_sha256: Any, + role: str, + evidence_type: str, +) -> dict[str, Any]: + expected = _hash(expected_sha256, f"{role} declared SHA-256") + portable = _project_relative_path(path, project_root, role) + resolved = (project_root / portable).resolve() + if not resolved.is_file(): + raise FileNotFoundError(f"{role} is required: {resolved}") + actual = sha256_file(resolved) + if actual != expected: + raise ValueError(f"{role} SHA-256 disagrees with result metadata") + return { + "path": portable, + "role": role, + "media_type": "application/json", + "bytes": resolved.stat().st_size, + "sha256": actual, + "evidence_types": [evidence_type], + } + + +def _artifact_anchor_inputs( + metadata: Mapping[str, Any], project_root: Path +) -> list[dict[str, Any]]: + anchor = metadata.get("anchor") + if not isinstance(anchor, Mapping): + raise ValueError("result metadata lacks anchor provenance") + hashes = anchor.get("hashes") + if not isinstance(hashes, Mapping): + raise ValueError("result metadata lacks anchor hashes") + anchor_relative = _portable_path( + anchor.get("anchor_path"), "result metadata anchor.anchor_path" + ) + manifest_relative = _portable_path( + anchor.get("anchor_manifest_path"), + "result metadata anchor.anchor_manifest_path", + ) + anchor_file = (project_root / anchor_relative).resolve() + manifest_file = (project_root / manifest_relative).resolve() + reverified = _verify_anchor( + anchor_file, + manifest_file, + project_root=project_root, + expected_anchor_sha256=_hash( + hashes.get("anchor_sha256"), "result metadata anchor_sha256" + ), + expected_anchor_manifest_sha256=_hash( + hashes.get("anchor_manifest_sha256"), + "result metadata anchor_manifest_sha256", + ), + ) + if dict(reverified.hashes) != dict(hashes): + raise ValueError("revalidated anchor lineage disagrees with result metadata") + return [ + _artifact_input_entry( + anchor_file, + project_root=project_root, + expected_sha256=hashes.get("anchor_sha256"), + role="anchor", + evidence_type=ANCHOR_EVIDENCE_LABEL, + ), + _artifact_input_entry( + manifest_file, + project_root=project_root, + expected_sha256=hashes.get("anchor_manifest_sha256"), + role="anchor_manifest", + evidence_type=ANCHOR_EVIDENCE_LABEL, + ), + ] + + +def _artifact_write_table(frame: pd.DataFrame, destination: Path) -> Path: + if not isinstance(frame, pd.DataFrame): + raise TypeError("benchmark artifact tables must be pandas DataFrames") + frame.to_csv(destination, index=False, lineterminator="\n") + return destination + + +def _artifact_write_json(payload: Mapping[str, Any], destination: Path) -> Path: + destination.write_text( + json.dumps( + _artifact_json_safe(payload), + indent=2, + sort_keys=True, + allow_nan=False, + ) + + "\n", + encoding="utf-8", + ) + return destination + + +def _artifact_evidence_types(frame: pd.DataFrame, default: str) -> list[str]: + if "evidence_type" not in frame or frame.empty: + return [default] + values = sorted(frame["evidence_type"].dropna().astype(str).unique().tolist()) + return values or [default] + + +def _artifact_publish_directory(stage: Path, output: Path, temporary_root: Path) -> None: + backup = temporary_root / "previous_bundle" + if output.exists(): + output.replace(backup) + try: + stage.replace(output) + except BaseException: + if backup.exists() and not output.exists(): + backup.replace(output) + raise + if backup.exists(): + shutil.rmtree(backup) + + +def write_nyc_benchmark_artifacts( + result: NYCBenchmarkResult, + output_dir: str | Path, + *, + project_root: str | Path | None = None, +) -> dict[str, Path]: + """Atomically publish a self-contained NYC-informed benchmark bundle. + + The manifest hashes the four result tables and metadata payload. All serialized + paths are portable, and no wall-clock timestamp is added, so equal results produce + byte-identical bundles. + """ + + if not isinstance(result, NYCBenchmarkResult): + raise TypeError("result must be an NYCBenchmarkResult") + if not isinstance(result.metadata, Mapping): + raise TypeError("result.metadata must be a mapping") + artifact_root = _artifact_project_root(project_root) + inputs = _artifact_anchor_inputs(result.metadata, artifact_root) + output, portable_output = _artifact_output_path(output_dir, project_root) + output.parent.mkdir(parents=True, exist_ok=True) + temporary_root = Path( + tempfile.mkdtemp(prefix=f".{output.name}-stage-", dir=output.parent) + ) + stage = temporary_root / "bundle" + stage.mkdir() + tables = { + "records": result.records, + "summary": result.summary, + "fit_ledger": result.fit_ledger, + "failures": result.failures, + } + filenames = {name: f"{name}.csv" for name in tables} + try: + for name, frame in tables.items(): + _artifact_write_table(frame, stage / filenames[name]) + + metadata = dict(result.metadata) + if "artifact_bundle" in metadata: + raise ValueError("result metadata already contains reserved artifact_bundle") + metadata["artifact_bundle"] = { + "schema_version": NYC_BENCHMARK_SCHEMA_VERSION, + "artifact_type": "nyc_informed_marketplace_benchmark", + "portable_output_directory": portable_output, + "portable_paths": True, + "bundle_valid": True, + "evidence_type": NYC_BENCHMARK_EVIDENCE_TYPE, + "causal_claim": False, + "nyc_empirical_causal_effect": False, + "simulator_known_truth": True, + "inputs": inputs, + "tables": { + name: {"path": filenames[name], "rows": int(len(frame))} + for name, frame in tables.items() + }, + } + metadata_path = _artifact_write_json(metadata, stage / "metadata.json") + + files: list[dict[str, Any]] = [] + for name, frame in tables.items(): + path = stage / filenames[name] + files.append( + { + "path": path.name, + "role": name, + "media_type": "text/csv", + "rows": int(len(frame)), + "bytes": path.stat().st_size, + "sha256": sha256_file(path), + "evidence_types": _artifact_evidence_types( + frame, NYC_BENCHMARK_EVIDENCE_TYPE + ), + } + ) + files.append( + { + "path": metadata_path.name, + "role": "metadata", + "media_type": "application/json", + "bytes": metadata_path.stat().st_size, + "sha256": sha256_file(metadata_path), + "evidence_types": [NYC_BENCHMARK_EVIDENCE_TYPE], + } + ) + manifest = { + "schema_version": NYC_BENCHMARK_SCHEMA_VERSION, + "artifact_type": "nyc_informed_marketplace_benchmark", + "evidence_type": NYC_BENCHMARK_EVIDENCE_TYPE, + "causal_claim": False, + "causal_claim_from_nyc_data": False, + "simulator_known_truth": True, + "portable_paths": True, + "bundle_valid": True, + "artifact_directory": portable_output, + "metadata_file": metadata_path.name, + "files": files, + "inputs": inputs, + } + _artifact_write_json(manifest, stage / "manifest.json") + _artifact_publish_directory(stage, output, temporary_root) + finally: + if temporary_root.exists(): + shutil.rmtree(temporary_root) + + return { + "output_directory": output, + **{name: output / filename for name, filename in filenames.items()}, + "metadata": output / "metadata.json", + "manifest": output / "manifest.json", + } + + +__all__ = [ + "NYC_BENCHMARK_EVIDENCE_TYPE", + "NYC_BENCHMARK_SCHEMA_VERSION", + "NYCBenchmarkConfig", + "NYCBenchmarkResult", + "default_nyc_benchmark_scenarios", + "run_nyc_informed_marketplace_benchmark", + "validate_nyc_benchmark_anchor", + "write_nyc_benchmark_artifacts", +] diff --git a/CasualLab/src/casuallab/nyc_calibration.py b/CasualLab/src/casuallab/nyc_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..9436c8d3f3fb7a7670ee1972fe5275e74d5f9da6 --- /dev/null +++ b/CasualLab/src/casuallab/nyc_calibration.py @@ -0,0 +1,1248 @@ +"""Laptop-safe descriptive calibration and network inputs for NYC HVFHV data. + +The public API in this module deliberately separates observed completed-trip +moments from causal or structural assumptions. Trip-level Parquet is scanned by +DuckDB; only scalar results and compact aggregate CSVs cross into Python. +""" + +from __future__ import annotations + +import hashlib +import json +import shutil +import tempfile +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from datetime import UTC, date, datetime +from pathlib import Path +from typing import Any + +import duckdb +import numpy as np + +from casuallab.config import SimulationConfig +from casuallab.data import DataConfig, load_data_config, sha256_file + +EVIDENCE_LABEL = "descriptive_real_data" +CAUSAL_WARNING = ( + "Published completed-trip associations are descriptive and do not identify " + "treatment response, spillovers, persistence, substitution, or welfare." +) + + +@dataclass(frozen=True, slots=True) +class NYCCalibrationSettings: + """Runtime and design choices for a calibration bundle. + + ``target_cluster_count`` is a proposed experiment-design input. It is not + estimated by the observed OD graph. + """ + + memory_limit: str = "1GB" + threads: int = 1 + exact_lag_hours: tuple[int, ...] = (1, 24, 168) + target_cluster_count: int = 16 + verify_source_hashes: bool = True + + def __post_init__(self) -> None: + if not self.memory_limit.strip(): + raise ValueError("memory_limit must not be empty") + if self.threads < 1: + raise ValueError("threads must be positive") + if not self.exact_lag_hours or any(lag < 1 for lag in self.exact_lag_hours): + raise ValueError("exact_lag_hours must contain positive integers") + if len(set(self.exact_lag_hours)) != len(self.exact_lag_hours): + raise ValueError("exact_lag_hours must not contain duplicates") + if self.target_cluster_count < 2: + raise ValueError("target_cluster_count must be at least two") + + def to_dict(self) -> dict[str, Any]: + return { + "memory_limit": self.memory_limit, + "threads": self.threads, + "exact_lag_hours": list(self.exact_lag_hours), + "target_cluster_count": self.target_cluster_count, + "verify_source_hashes": self.verify_source_hashes, + } + + +@dataclass(frozen=True, slots=True) +class NYCCalibrationArtifacts: + """Paths in one successfully published calibration/network bundle.""" + + output_directory: Path + calibration_path: Path + hour_profile_path: Path + zone_profile_path: Path + edge_path: Path + exposure_mapping_path: Path + node_path: Path + autocorrelation_path: Path + manifest_path: Path + + def paths(self) -> tuple[Path, ...]: + return ( + self.calibration_path, + self.hour_profile_path, + self.zone_profile_path, + self.edge_path, + self.exposure_mapping_path, + self.node_path, + self.autocorrelation_path, + self.manifest_path, + ) + + +def _json_safe(value: Any) -> Any: + if isinstance(value, Path): + return str(value) + if isinstance(value, (date, datetime)): + return value.isoformat() + if isinstance(value, Mapping): + return {str(key): _json_safe(item) for key, item in value.items()} + if isinstance(value, (list, tuple, set, frozenset)): + return [_json_safe(item) for item in value] + if isinstance(value, (np.integer, np.floating)): + value = value.item() + if isinstance(value, float) and not np.isfinite(value): + return None + return value + + +def _atomic_json(payload: Mapping[str, Any], destination: Path) -> Path: + destination.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + prefix=f".{destination.stem}-", + suffix=destination.suffix, + dir=destination.parent, + delete=False, + ) as handle: + temporary = Path(handle.name) + json.dump(_json_safe(payload), handle, indent=2, sort_keys=True, allow_nan=False) + handle.write("\n") + temporary.replace(destination) + return destination + + +def _sql_string(value: str) -> str: + return "'" + value.replace("'", "''") + "'" + + +def _scan_sql(paths: Sequence[Path]) -> str: + if not paths: + raise FileNotFoundError("expected at least one Parquet input") + rendered = ", ".join(_sql_string(str(path.resolve())) for path in paths) + return ( + f"read_parquet([{rendered}], union_by_name=true, " + "hive_partitioning=false)" + ) + + +def _parquet_files(directory: Path) -> tuple[Path, ...]: + files = tuple(sorted(directory.rglob("*.parquet"))) + if not files: + raise FileNotFoundError(f"no Parquet files found under {directory}") + return files + + +def _portable_path(path: Path, project_root: Path) -> str: + try: + return str(path.resolve().relative_to(project_root.resolve())) + except ValueError: + # Never serialize a machine-specific absolute path. External inputs remain + # recognizable by filename and are explicitly flagged in provenance. + return path.name + + +def _row(connection: duckdb.DuckDBPyConnection, query: str) -> dict[str, Any]: + result = connection.execute(query) + values = result.fetchone() + if values is None: + raise RuntimeError("calibration query returned no row") + return { + description[0]: value + for description, value in zip(result.description, values, strict=True) + } + + +def _copy_csv( + connection: duckdb.DuckDBPyConnection, + query: str, + destination: Path, +) -> Path: + temporary = destination.with_name(f".{destination.name}.tmp") + temporary.unlink(missing_ok=True) + try: + connection.execute( + f"COPY ({query}) TO {_sql_string(str(temporary.resolve()))} " + "(FORMAT CSV, HEADER true)" + ) + temporary.replace(destination) + except BaseException: + temporary.unlink(missing_ok=True) + raise + return destination + + +def _manifest_declared_digest(entries: Sequence[Mapping[str, Any]]) -> str: + canonical = json.dumps( + [ + { + "path": str(entry.get("path")), + "bytes": int(entry.get("bytes", -1)), + "sha256": str(entry.get("sha256")), + } + for entry in entries + ], + sort_keys=True, + separators=(",", ":"), + ).encode() + return hashlib.sha256(canonical).hexdigest() + + +def _verify_source_manifest( + manifest_path: Path, + project_root: Path, + queried_files: Sequence[Path], + *, + verify_hashes: bool, +) -> tuple[dict[str, Any], dict[str, Any]]: + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + entries = manifest.get("files", []) + if not isinstance(entries, list): + raise ValueError("source data manifest files must be a list") + + resolved_entries: dict[Path, Mapping[str, Any]] = {} + mismatches: list[str] = [] + for entry in entries: + if not isinstance(entry, Mapping) or "path" not in entry: + mismatches.append("malformed_manifest_entry") + continue + entry_path = Path(str(entry["path"])) + resolved = ( + entry_path.resolve() + if entry_path.is_absolute() + else (project_root / entry_path).resolve() + ) + resolved_entries[resolved] = entry + portable = _portable_path(resolved, project_root) + if not resolved.is_file(): + mismatches.append(f"missing:{portable}") + continue + if resolved.stat().st_size != int(entry.get("bytes", -1)): + mismatches.append(f"bytes:{portable}") + continue + if verify_hashes and sha256_file(resolved) != entry.get("sha256"): + mismatches.append(f"sha256:{portable}") + + missing_queried = sorted( + _portable_path(path, project_root) + for path in queried_files + if path.resolve() not in resolved_entries + ) + mismatches.extend(f"not_in_manifest:{path}" for path in missing_queried) + metadata = manifest.get("metadata", {}) + config = manifest.get("config", {}) + scope_valid = ( + isinstance(config, Mapping) + and config.get("source") == "nyc_hvfhv" + and config.get("mode") == "full" + and isinstance(metadata, Mapping) + and metadata.get("causal_claim") is False + ) + validation = { + "path": _portable_path(manifest_path, project_root), + "sha256": sha256_file(manifest_path), + "entries": len(entries), + "declared_file_set_sha256": _manifest_declared_digest(entries), + "hashes_recomputed": verify_hashes, + "queried_files_listed": not missing_queried, + "scope_is_full_nyc_descriptive": scope_valid, + "mismatches": mismatches, + "all_valid": not mismatches and scope_valid, + } + return manifest, validation + + +def _trip_moments(connection: duckdb.DuckDBPyConnection) -> dict[str, Any]: + values = _row( + connection, + """ + WITH trip_values AS ( + SELECT + date_diff('second', request_datetime, pickup_datetime) / 60.0 + AS wait_minutes, + fare, + driver_pay + FROM clean + ) + SELECT + count(*)::BIGINT AS trip_rows, + count(wait_minutes)::BIGINT AS wait_published_rows, + count(*) FILTER (WHERE wait_minutes >= 0)::BIGINT AS wait_valid_rows, + count(*) FILTER (WHERE wait_minutes < 0)::BIGINT AS wait_negative_rows, + count(*) FILTER (WHERE wait_minutes = 0)::BIGINT AS wait_zero_rows, + avg(wait_minutes) FILTER (WHERE wait_minutes >= 0) AS wait_mean, + stddev_pop(wait_minutes) FILTER (WHERE wait_minutes >= 0) AS wait_stddev, + min(wait_minutes) FILTER (WHERE wait_minutes >= 0) AS wait_min, + approx_quantile(wait_minutes, 0.10) FILTER (WHERE wait_minutes >= 0) + AS wait_p10, + approx_quantile(wait_minutes, 0.25) FILTER (WHERE wait_minutes >= 0) + AS wait_p25, + approx_quantile(wait_minutes, 0.50) FILTER (WHERE wait_minutes >= 0) + AS wait_p50, + approx_quantile(wait_minutes, 0.75) FILTER (WHERE wait_minutes >= 0) + AS wait_p75, + approx_quantile(wait_minutes, 0.90) FILTER (WHERE wait_minutes >= 0) + AS wait_p90, + approx_quantile(wait_minutes, 0.95) FILTER (WHERE wait_minutes >= 0) + AS wait_p95, + approx_quantile(wait_minutes, 0.99) FILTER (WHERE wait_minutes >= 0) + AS wait_p99, + max(wait_minutes) FILTER (WHERE wait_minutes >= 0) AS wait_max, + count(fare)::BIGINT AS fare_known_rows, + count(*) FILTER (WHERE fare < 0)::BIGINT AS fare_negative_rows, + count(*) FILTER (WHERE fare = 0)::BIGINT AS fare_zero_rows, + sum(fare) AS fare_sum, + avg(fare) AS fare_mean, + stddev_pop(fare) AS fare_stddev, + min(fare) AS fare_min, + approx_quantile(fare, 0.10) AS fare_p10, + approx_quantile(fare, 0.50) AS fare_p50, + approx_quantile(fare, 0.90) AS fare_p90, + approx_quantile(fare, 0.99) AS fare_p99, + max(fare) AS fare_max, + count(driver_pay)::BIGINT AS driver_pay_known_rows, + count(*) FILTER (WHERE driver_pay < 0)::BIGINT + AS driver_pay_negative_rows, + count(*) FILTER (WHERE driver_pay = 0)::BIGINT AS driver_pay_zero_rows, + sum(driver_pay) AS driver_pay_sum, + avg(driver_pay) AS driver_pay_mean, + stddev_pop(driver_pay) AS driver_pay_stddev, + min(driver_pay) AS driver_pay_min, + approx_quantile(driver_pay, 0.10) AS driver_pay_p10, + approx_quantile(driver_pay, 0.50) AS driver_pay_p50, + approx_quantile(driver_pay, 0.90) AS driver_pay_p90, + approx_quantile(driver_pay, 0.99) AS driver_pay_p99, + max(driver_pay) AS driver_pay_max, + corr(fare, driver_pay) AS fare_driver_pay_correlation, + sum(driver_pay) / nullif(sum(fare), 0) AS driver_pay_to_base_fare_ratio + FROM trip_values + """, + ) + wait_keys = ( + "published_rows", + "valid_rows", + "negative_rows", + "zero_rows", + "mean", + "stddev", + "min", + "p10", + "p25", + "p50", + "p75", + "p90", + "p95", + "p99", + "max", + ) + money_keys = ( + "known_rows", + "negative_rows", + "zero_rows", + "sum", + "mean", + "stddev", + "min", + "p10", + "p50", + "p90", + "p99", + "max", + ) + return { + "trip_rows": values["trip_rows"], + "request_to_pickup_wait_minutes": { + "available": int(values["wait_published_rows"]) > 0, + **{key: values[f"wait_{key}"] for key in wait_keys}, + "source_fields": ["request_datetime", "pickup_datetime"], + "unit": "minutes", + "validity_rule": "request_datetime and pickup_datetime published; nonnegative difference", + "quantile_method": "duckdb_approx_quantile_tdigest", + "interpretation": ( + "Request-to-pickup elapsed time is available only where both published " + "timestamps are non-null. It is a service-process proxy, not latent " + "rider utility or an intervention effect." + ), + "evidence_label": EVIDENCE_LABEL, + }, + "fare": { + **{key: values[f"fare_{key}"] for key in money_keys}, + "source_field": "base_passenger_fare normalized as fare", + "unit": "nominal_usd_per_published_trip", + "quantile_method": "duckdb_approx_quantile_tdigest", + "evidence_label": EVIDENCE_LABEL, + }, + "driver_pay": { + **{key: values[f"driver_pay_{key}"] for key in money_keys}, + "source_field": "driver_pay", + "unit": "nominal_usd_per_published_trip", + "quantile_method": "duckdb_approx_quantile_tdigest", + "interpretation": ( + "Published trip-level driver pay is not driver availability, opportunity " + "cost, platform margin, or the causal effect of an incentive." + ), + "evidence_label": EVIDENCE_LABEL, + }, + "fare_driver_pay_associations": { + "pearson_correlation": values["fare_driver_pay_correlation"], + "aggregate_driver_pay_to_base_fare_ratio": values[ + "driver_pay_to_base_fare_ratio" + ], + "interpretation": ( + "Both quantities are descriptive accounting associations. Base passenger " + "fare is not total rider payment or platform revenue." + ), + "evidence_label": EVIDENCE_LABEL, + }, + } + + +def _variance_decomposition(connection: duckdb.DuckDBPyConnection) -> dict[str, Any]: + values = _row( + connection, + """ + WITH cells AS ( + SELECT zone_id, time_bin, hour(time_bin)::INTEGER AS hour, trip_count::DOUBLE AS y + FROM zone + ), + grand AS ( + SELECT count(*)::BIGINT AS n, avg(y) AS mean_y, var_pop(y) AS total_variance + FROM cells + ), + zone_means AS ( + SELECT zone_id, count(*)::BIGINT AS n, avg(y) AS mean_y + FROM cells GROUP BY zone_id + ), + hour_means AS ( + SELECT hour, count(*)::BIGINT AS n, avg(y) AS mean_y + FROM cells GROUP BY hour + ), + zone_between AS ( + SELECT + sum(z.n * power(z.mean_y - g.mean_y, 2)) / g.n + AS between_component + FROM zone_means z + CROSS JOIN grand g + GROUP BY g.n + ), + zone_within AS ( + SELECT sum(power(c.y - z.mean_y, 2)) / g.n AS within_component + FROM cells c + JOIN zone_means z USING (zone_id) + CROSS JOIN grand g + GROUP BY g.n + ), + hour_between AS ( + SELECT + sum(h.n * power(h.mean_y - g.mean_y, 2)) / g.n + AS between_component + FROM hour_means h + CROSS JOIN grand g + GROUP BY g.n + ), + hour_within AS ( + SELECT sum(power(c.y - h.mean_y, 2)) / g.n AS within_component + FROM cells c + JOIN hour_means h USING (hour) + CROSS JOIN grand g + GROUP BY g.n + ) + SELECT + g.n AS panel_cells, + (SELECT count(*) FROM zone_means)::INTEGER AS zones, + count(DISTINCT c.time_bin)::INTEGER AS periods, + g.mean_y AS mean_completed_trips_per_zone_hour, + g.total_variance AS total_cell_variance, + zb.between_component AS between_zone_component, + zw.within_component AS within_zone_temporal_component, + zb.between_component / nullif(g.total_variance, 0) + AS icc_like_between_zone_share, + zb.between_component + zw.within_component - g.total_variance + AS zone_decomposition_residual, + hb.between_component AS between_hour_of_day_component, + hw.within_component AS within_hour_of_day_component, + hb.between_component / nullif(g.total_variance, 0) + AS between_hour_of_day_share, + hb.between_component + hw.within_component - g.total_variance + AS hour_decomposition_residual, + count(*) FILTER (WHERE c.y > 0)::BIGINT AS occupied_cells, + sum(c.y)::BIGINT AS total_completed_trips + FROM cells c + CROSS JOIN grand g + CROSS JOIN zone_between zb + CROSS JOIN zone_within zw + CROSS JOIN hour_between hb + CROSS JOIN hour_within hw + GROUP BY ALL + """, + ) + return { + **values, + "variance_definition": "population variance across complete pickup-zone x hour cells", + "icc_like_definition": ( + "weighted between-zone variance component divided by total cell variance" + ), + "interpretation": ( + "The ICC-like share is a descriptive variance decomposition, not a fitted " + "random-effects ICC, a design effect, or evidence of causal interference." + ), + "evidence_label": EVIDENCE_LABEL, + } + + +def _conservation(connection: duckdb.DuckDBPyConnection) -> dict[str, Any]: + clean = _row( + connection, + """ + SELECT + count(*)::BIGINT AS clean_rows, + count(*) FILTER (WHERE pickup_datetime IS NULL)::BIGINT + AS pickup_datetime_null_rows, + count(DISTINCT pickup_zone_id)::INTEGER AS pickup_zones, + min(pickup_datetime) AS pickup_min, + max(pickup_datetime) AS pickup_max + FROM clean + """, + ) + zone = _row( + connection, + """ + SELECT + count(*)::BIGINT AS zone_rows, + sum(trip_count)::BIGINT AS zone_trip_sum, + count(*) - count(DISTINCT (zone_id, time_bin)) AS zone_key_duplicates, + count(DISTINCT zone_id)::INTEGER AS zones, + count(DISTINCT time_bin)::INTEGER AS periods, + count(*) FILTER (WHERE trip_count = 0)::BIGINT AS zero_trip_cells + FROM zone + """, + ) + od = _row( + connection, + """ + SELECT + count(*)::BIGINT AS od_hour_rows, + sum(trip_count)::BIGINT AS od_trip_sum, + count(*) - count(DISTINCT (origin_zone_id, destination_zone_id, time_bin)) + AS od_key_duplicates, + count(*) FILTER (WHERE trip_count <= 0)::BIGINT AS nonpositive_od_rows + FROM od + """, + ) + return {**clean, **zone, **od} + + +def _create_graph_tables(connection: duckdb.DuckDBPyConnection) -> dict[str, Any]: + connection.execute( + """ + CREATE TEMP TABLE od_month AS + SELECT + origin_zone_id, + destination_zone_id, + sum(trip_count)::BIGINT AS trip_count + FROM od + GROUP BY origin_zone_id, destination_zone_id + """ + ) + connection.execute( + """ + CREATE TEMP TABLE od_edges AS + SELECT + least(origin_zone_id, destination_zone_id) AS zone_a, + greatest(origin_zone_id, destination_zone_id) AS zone_b, + sum(trip_count)::BIGINT AS edge_weight, + sum(CASE + WHEN origin_zone_id = least(origin_zone_id, destination_zone_id) + THEN trip_count ELSE 0 END)::BIGINT AS trips_a_to_b, + sum(CASE + WHEN origin_zone_id = greatest(origin_zone_id, destination_zone_id) + THEN trip_count ELSE 0 END)::BIGINT AS trips_b_to_a + FROM od_month + WHERE origin_zone_id <> destination_zone_id + GROUP BY zone_a, zone_b + """ + ) + return _row( + connection, + """ + WITH totals AS ( + SELECT + count(*)::BIGINT AS directed_pairs, + sum(trip_count)::BIGINT AS total_trips, + sum(trip_count) FILTER ( + WHERE origin_zone_id = destination_zone_id + )::BIGINT AS intra_zone_trips, + count(DISTINCT origin_zone_id)::INTEGER AS origin_nodes, + count(DISTINCT destination_zone_id)::INTEGER AS destination_nodes + FROM od_month + ), + edge_stats AS ( + SELECT + count(*)::BIGINT AS undirected_cross_zone_edges, + sum(edge_weight)::BIGINT AS cross_zone_trips, + sum(power(edge_weight::DOUBLE, 2)) / + nullif(power(sum(edge_weight)::DOUBLE, 2), 0) AS edge_weight_hhi + FROM od_edges + ), + ranked AS ( + SELECT edge_weight, row_number() OVER ( + ORDER BY edge_weight DESC, zone_a, zone_b + ) AS rank + FROM od_edges + ) + SELECT + t.directed_pairs, + e.undirected_cross_zone_edges, + greatest(t.origin_nodes, t.destination_nodes)::INTEGER AS nodes, + t.total_trips, + coalesce(t.intra_zone_trips, 0)::BIGINT AS intra_zone_trips, + e.cross_zone_trips, + e.cross_zone_trips::DOUBLE / nullif(t.total_trips, 0) AS cross_zone_share, + e.undirected_cross_zone_edges::DOUBLE / + nullif(greatest(t.origin_nodes, t.destination_nodes) * + (greatest(t.origin_nodes, t.destination_nodes) - 1) / 2, 0) + AS undirected_density, + e.edge_weight_hhi, + (SELECT sum(edge_weight) FROM ranked WHERE rank <= 10)::DOUBLE / + nullif(e.cross_zone_trips, 0) AS top_10_edge_weight_share + FROM totals t CROSS JOIN edge_stats e + """, + ) + + +def _edge_query() -> str: + return f""" + SELECT + zone_a, + zone_b, + edge_weight, + trips_a_to_b, + trips_b_to_a, + edge_weight::DOUBLE / sum(edge_weight) OVER () AS cross_zone_weight_share, + '{EVIDENCE_LABEL}' AS evidence_label, + 'Undirected completed-trip flow weight; not a spillover estimate.' + AS interpretation_warning + FROM od_edges + ORDER BY edge_weight DESC, zone_a, zone_b + """ + + +def _exposure_mapping_query() -> str: + """Return the edge schema consumed by ``add_mapped_exposures``. + + Each monthly undirected flow edge is represented in both focal directions. + Downstream exposure code row-normalizes the nonnegative raw weights. + """ + + return f""" + WITH directed_mapping AS ( + SELECT + zone_a AS focal_zone_id, + zone_b AS neighbor_zone_id, + edge_weight::DOUBLE AS weight + FROM od_edges + UNION ALL + SELECT + zone_b AS focal_zone_id, + zone_a AS neighbor_zone_id, + edge_weight::DOUBLE AS weight + FROM od_edges + ) + SELECT + focal_zone_id, + neighbor_zone_id, + weight, + '{EVIDENCE_LABEL}' AS evidence_label, + 'Symmetric monthly completed-trip flow; downstream row-normalizes weight.' + AS weight_definition, + 'Pre-treatment exposure-map input; not an estimated spillover effect.' + AS interpretation_warning + FROM directed_mapping + ORDER BY focal_zone_id, weight DESC, neighbor_zone_id + """ + + +def _node_query() -> str: + return f""" + WITH nodes AS ( + SELECT origin_zone_id AS zone_id FROM od_month + UNION + SELECT destination_zone_id AS zone_id FROM od_month + ), + out_shares AS ( + SELECT + origin_zone_id AS zone_id, + destination_zone_id, + trip_count, + trip_count::DOUBLE / sum(trip_count) OVER (PARTITION BY origin_zone_id) + AS destination_share + FROM od_month + ), + outgoing AS ( + SELECT + zone_id, + sum(trip_count)::BIGINT AS outbound_trips, + count(*)::INTEGER AS outbound_destinations_including_self, + count(*) FILTER (WHERE destination_zone_id <> zone_id)::INTEGER + AS cross_zone_out_degree, + sum(power(destination_share, 2)) AS outbound_destination_hhi, + sum(trip_count) FILTER (WHERE destination_zone_id = zone_id)::BIGINT + AS self_loop_trips + FROM out_shares + GROUP BY zone_id + ), + incoming AS ( + SELECT + destination_zone_id AS zone_id, + sum(trip_count)::BIGINT AS inbound_trips, + count(*) FILTER (WHERE origin_zone_id <> destination_zone_id)::INTEGER + AS cross_zone_in_degree + FROM od_month + GROUP BY destination_zone_id + ), + strength_rows AS ( + SELECT zone_a AS zone_id, edge_weight FROM od_edges + UNION ALL + SELECT zone_b AS zone_id, edge_weight FROM od_edges + ), + strength AS ( + SELECT + zone_id, + count(*)::INTEGER AS undirected_degree, + sum(edge_weight)::BIGINT AS undirected_strength + FROM strength_rows GROUP BY zone_id + ) + SELECT + n.zone_id, + coalesce(o.outbound_trips, 0)::BIGINT AS outbound_trips, + coalesce(i.inbound_trips, 0)::BIGINT AS inbound_trips, + coalesce(o.self_loop_trips, 0)::BIGINT AS self_loop_trips, + coalesce(o.cross_zone_out_degree, 0)::INTEGER AS cross_zone_out_degree, + coalesce(i.cross_zone_in_degree, 0)::INTEGER AS cross_zone_in_degree, + coalesce(s.undirected_degree, 0)::INTEGER AS undirected_degree, + coalesce(s.undirected_strength, 0)::BIGINT AS undirected_strength, + coalesce(s.undirected_strength, 0)::DOUBLE / + nullif(2 * sum(coalesce(s.undirected_strength, 0)) OVER () / 2, 0) + AS undirected_strength_share, + o.outbound_destination_hhi, + coalesce(o.self_loop_trips, 0)::DOUBLE / nullif(o.outbound_trips, 0) + AS outbound_self_loop_share, + '{EVIDENCE_LABEL}' AS evidence_label, + 'Node weights are clustering inputs from observed flows, not causal exposure.' + AS interpretation_warning + FROM nodes n + LEFT JOIN outgoing o USING (zone_id) + LEFT JOIN incoming i USING (zone_id) + LEFT JOIN strength s USING (zone_id) + ORDER BY outbound_trips DESC, n.zone_id + """ + + +def _autocorrelation_query(lags: Sequence[int]) -> str: + pieces: list[str] = [] + for lag in lags: + pieces.append( + f"""( + WITH zone_means AS ( + SELECT zone_id, avg(trip_count::DOUBLE) AS zone_mean + FROM zone GROUP BY zone_id + ), + spans AS ( + SELECT + zone_id, + greatest( + date_diff('hour', min(time_bin), max(time_bin)) + 1 - {lag}, + 0 + )::BIGINT AS possible_pairs + FROM zone GROUP BY zone_id + ), + pairs AS ( + SELECT + current.trip_count::DOUBLE AS current_y, + previous.trip_count::DOUBLE AS previous_y, + means.zone_mean + FROM zone current + JOIN zone previous + ON current.zone_id = previous.zone_id + AND current.time_bin = previous.time_bin + INTERVAL '{lag} hours' + JOIN zone_means means ON current.zone_id = means.zone_id + ) + SELECT + {lag}::INTEGER AS lag_hours, + count(*)::BIGINT AS exact_lag_support_pairs, + (SELECT sum(possible_pairs) FROM spans)::BIGINT + AS possible_pairs_on_hourly_span, + count(*)::DOUBLE / nullif((SELECT sum(possible_pairs) FROM spans), 0) + AS support_share, + corr(current_y, previous_y) AS pooled_trip_count_correlation, + corr(current_y - zone_mean, previous_y - zone_mean) + AS within_zone_centered_correlation, + avg(current_y) AS current_mean, + avg(previous_y) AS lagged_mean, + '{EVIDENCE_LABEL}' AS evidence_label, + 'Exact timestamp lag association; not a causal persistence parameter.' + AS interpretation_warning + FROM pairs + )""" + ) + return " UNION ALL ".join(pieces) + " ORDER BY lag_hours" + + +def _hour_profile_query() -> str: + return f""" + SELECT + hour(time_bin)::INTEGER AS hour_of_day, + count(*)::BIGINT AS zone_hour_cells, + count(DISTINCT zone_id)::INTEGER AS zones, + count(DISTINCT time_bin::DATE)::INTEGER AS dates, + sum(trip_count)::BIGINT AS completed_trips, + avg(trip_count::DOUBLE) AS mean_trips_per_zone_hour, + var_pop(trip_count::DOUBLE) AS cell_variance, + stddev_pop(trip_count::DOUBLE) AS cell_stddev, + approx_quantile(trip_count, 0.50) AS cell_p50, + approx_quantile(trip_count, 0.90) AS cell_p90, + '{EVIDENCE_LABEL}' AS evidence_label + FROM zone + GROUP BY hour_of_day + ORDER BY hour_of_day + """ + + +def _zone_profile_query() -> str: + return f""" + SELECT + zone_id, + count(*)::BIGINT AS hourly_cells, + count(*) FILTER (WHERE trip_count > 0)::BIGINT AS occupied_cells, + sum(trip_count)::BIGINT AS completed_trips, + sum(trip_count)::DOUBLE / sum(sum(trip_count)) OVER () AS month_trip_share, + avg(trip_count::DOUBLE) AS mean_trips_per_hour, + var_pop(trip_count::DOUBLE) AS temporal_variance, + stddev_pop(trip_count::DOUBLE) AS temporal_stddev, + approx_quantile(trip_count, 0.50) AS hourly_p50, + approx_quantile(trip_count, 0.90) AS hourly_p90, + max(trip_count)::BIGINT AS hourly_max, + '{EVIDENCE_LABEL}' AS evidence_label + FROM zone + GROUP BY zone_id + ORDER BY completed_trips DESC, zone_id + """ + + +def _raw_rows_declared(source_manifest: Mapping[str, Any]) -> int | None: + metadata = source_manifest.get("metadata", {}) + if isinstance(metadata, Mapping): + full = metadata.get("full_month_processing", {}) + if isinstance(full, Mapping) and full.get("raw_rows") is not None: + return int(full["raw_rows"]) + config = source_manifest.get("config", {}) + if isinstance(config, Mapping) and config.get("nyc_expected_rows") is not None: + return int(config["nyc_expected_rows"]) + return None + + +def _calibration_proposal( + trip_moments: Mapping[str, Any], + variance: Mapping[str, Any], + template: SimulationConfig, +) -> dict[str, Any]: + mean_completed = float(variance["mean_completed_trips_per_zone_hour"]) + assumed_ratio = template.base_supply / template.base_demand + wait = trip_moments["request_to_pickup_wait_minutes"] + fare = trip_moments["fare"] + wait_anchor = wait.get("p50") if wait.get("available") else None + patch = { + "n_zones": int(variance["zones"]), + "n_periods": int(variance["periods"]), + "periods_per_day": 24, + "base_demand": mean_completed, + "base_supply": mean_completed * assumed_ratio, + "base_fare": fare.get("mean"), + "base_wait_minutes": wait_anchor, + } + return { + "status": "transparent_initialization_proposal_not_fitted_structural_model", + "suggested_simulation_config_patch": patch, + "observed_control_target": { + "quantity": "mean published completed trips per pickup-zone hour", + "value": mean_completed, + "evidence_label": EVIDENCE_LABEL, + }, + "initialization_rules": [ + "Use the observed zone and hourly panel dimensions for simulation shape.", + "Initialize fare scale from mean published base passenger fare.", + "Use median nonnegative request-to-pickup elapsed time only as a wait proxy.", + "Initialize latent demand at completed-trip scale, then jointly rescale demand and supply until the simulated control path matches the completed-trip target.", + "Preserve the template supply-to-demand ratio during scale rescaling because available drivers are not published.", + "Validate the simulated hourly and zone distributions against held-out descriptive cells before using it for design analysis.", + ], + "assumption_carried_from_template": { + "baseline_supply_to_demand_ratio": assumed_ratio, + "capacity_per_driver": template.capacity_per_driver, + "matching_efficiency": template.matching_efficiency, + "individuals_per_cell": template.individuals_per_cell, + "treatment_version": template.treatment_version.value, + "discount_rate": template.discount_rate, + "incentive_per_driver": template.incentive_per_driver, + "direct_demand_effect": template.direct_demand_effect, + "direct_supply_effect": template.direct_supply_effect, + "spillover_strength": template.spillover_strength, + "persistence": template.persistence, + "rider_substitution": template.rider_substitution, + "driver_mobility": template.driver_mobility, + "rider_value": template.rider_value, + "operating_cost_per_trip": template.operating_cost_per_trip, + "wait_disutility_per_minute": template.wait_disutility_per_minute, + }, + "not_estimated_from_trip_records": [ + "latent_requests", + "available_drivers", + "baseline_supply_to_demand_ratio", + "capacity_per_driver", + "matching_efficiency", + "direct_demand_effect", + "direct_supply_effect", + "spillover_strength", + "persistence", + "rider_substitution", + "driver_mobility", + "rider_value", + "operating_cost_per_trip", + "wait_disutility_per_minute", + "platform_margin", + "welfare_function_or_welfare_effect", + ], + "critical_warning": ( + "The proposed base_demand and base_supply values are initialization scales, " + "not estimates of latent demand or driver supply. Autocorrelation is not " + "mapped to persistence, and OD weights are not mapped to spillover effects." + ), + } + + +def _bundle_manifest( + stage: Path, + source_manifest_validation: Mapping[str, Any], + config: DataConfig, + settings: NYCCalibrationSettings, +) -> Path: + paths = tuple(sorted(path for path in stage.iterdir() if path.is_file())) + entries = [ + { + "path": path.name, + "bytes": path.stat().st_size, + "sha256": sha256_file(path), + } + for path in paths + if path.name != "manifest.json" + ] + return _atomic_json( + { + "schema_version": "1.0.0", + "evidence_label": EVIDENCE_LABEL, + "causal_claim": False, + "portable_paths": True, + "files": entries, + "source_data_manifest": source_manifest_validation, + "config": { + "data": config.as_serializable_dict(), + "calibration": settings.to_dict(), + }, + "interpretation_warning": CAUSAL_WARNING, + }, + stage / "manifest.json", + ) + + +def _publish_directory(stage: Path, destination: Path) -> None: + backup = destination.with_name(f".{destination.name}.previous") + if backup.exists(): + shutil.rmtree(backup) + if destination.exists(): + destination.replace(backup) + try: + stage.replace(destination) + except BaseException: + if backup.exists() and not destination.exists(): + backup.replace(destination) + raise + if backup.exists(): + shutil.rmtree(backup) + + +def write_nyc_calibration_bundle( + config: DataConfig | str | Path, + output_directory: str | Path, + *, + settings: NYCCalibrationSettings | None = None, + simulator_template: SimulationConfig | None = None, +) -> NYCCalibrationArtifacts: + """Write a fail-closed descriptive NYC calibration and OD-network bundle. + + The function requires an already completed NYC full-mode data build. It never + converts the trip table to pandas or Polars; DuckDB performs every trip-level + scan under the configured memory limit. + """ + + cfg = load_data_config(config) if not isinstance(config, DataConfig) else config + if cfg.source != "nyc_hvfhv" or cfg.mode != "full": + raise ValueError("NYC calibration requires source=nyc_hvfhv and mode=full") + runtime = settings or NYCCalibrationSettings() + template = simulator_template or SimulationConfig() + output = Path(output_directory).resolve() + output.parent.mkdir(parents=True, exist_ok=True) + marker = output.parent / f"{output.name}_INCOMPLETE.json" + _atomic_json( + { + "status": "incomplete", + "started_at_utc": datetime.now(UTC).isoformat(), + "intended_output": output.name, + "interpretation": ( + "Do not treat this calibration bundle as current while this marker exists." + ), + }, + marker, + ) + + pipeline_marker = cfg.manifest_path.with_name("NYC_FULL_INCOMPLETE.json") + if pipeline_marker.exists(): + raise RuntimeError("NYC full data pipeline is marked incomplete") + if not cfg.manifest_path.is_file(): + raise FileNotFoundError(cfg.manifest_path) + clean_files = _parquet_files(cfg.clean_dir / "trips") + zone_files = _parquet_files(cfg.panel_dir / "zone_time") + od_files = _parquet_files(cfg.panel_dir / "od_flow") + queried_files = (*clean_files, *zone_files, *od_files) + source_manifest, manifest_validation = _verify_source_manifest( + cfg.manifest_path, + cfg.project_root, + queried_files, + verify_hashes=runtime.verify_source_hashes, + ) + if not manifest_validation["all_valid"]: + raise ValueError("source data manifest validation failed") + + temporary_root = Path( + tempfile.mkdtemp(prefix=f".{output.name}-stage-", dir=output.parent) + ) + stage = temporary_root / output.name + stage.mkdir() + duckdb_temp = temporary_root / "duckdb_temp" + duckdb_temp.mkdir() + try: + connection = duckdb.connect() + connection.execute(f"SET threads = {runtime.threads}") + connection.execute(f"SET memory_limit = {_sql_string(runtime.memory_limit)}") + connection.execute( + f"SET temp_directory = {_sql_string(str(duckdb_temp.resolve()))}" + ) + connection.execute( + f"CREATE TEMP VIEW clean AS SELECT * FROM {_scan_sql(clean_files)}" + ) + connection.execute( + f"CREATE TEMP VIEW zone AS SELECT * FROM {_scan_sql(zone_files)}" + ) + connection.execute( + f"CREATE TEMP VIEW od AS SELECT * FROM {_scan_sql(od_files)}" + ) + try: + trip_moments = _trip_moments(connection) + variance = _variance_decomposition(connection) + conservation = _conservation(connection) + graph_summary = _create_graph_tables(connection) + hour_path = _copy_csv( + connection, _hour_profile_query(), stage / "hour_of_day_profile.csv" + ) + zone_path = _copy_csv( + connection, _zone_profile_query(), stage / "zone_temporal_profile.csv" + ) + edge_path = _copy_csv( + connection, _edge_query(), stage / "od_weighted_edges.csv" + ) + exposure_mapping_path = _copy_csv( + connection, + _exposure_mapping_query(), + stage / "exposure_mapping_edges.csv", + ) + node_path = _copy_csv( + connection, _node_query(), stage / "zone_graph_nodes.csv" + ) + autocorrelation_path = _copy_csv( + connection, + _autocorrelation_query(runtime.exact_lag_hours), + stage / "temporal_autocorrelation.csv", + ) + finally: + connection.close() + + raw_rows = _raw_rows_declared(source_manifest) + checks = { + "source_manifest_valid": bool(manifest_validation["all_valid"]), + "raw_rows_declared": raw_rows is not None, + "raw_equals_clean": raw_rows == int(conservation["clean_rows"]), + "zone_conserves_clean": int(conservation["zone_trip_sum"]) + == int(conservation["clean_rows"]) + - int(conservation["pickup_datetime_null_rows"]), + "od_conserves_clean": int(conservation["od_trip_sum"]) + == int(conservation["clean_rows"]) + - int(conservation["pickup_datetime_null_rows"]), + "graph_conserves_od": int(graph_summary["total_trips"]) + == int(conservation["od_trip_sum"]), + "zone_keys_unique": int(conservation["zone_key_duplicates"]) == 0, + "od_keys_unique": int(conservation["od_key_duplicates"]) == 0, + "od_counts_positive": int(conservation["nonpositive_od_rows"]) == 0, + "variance_trip_sum_conserves": int(variance["total_completed_trips"]) + == int(conservation["zone_trip_sum"]), + } + if not all(checks.values()): + failed = ", ".join(name for name, passed in checks.items() if not passed) + raise ValueError(f"NYC calibration conservation checks failed: {failed}") + + diagnostic_provenance: dict[str, Any] | None = None + if cfg.diagnostics_path.is_file(): + diagnostic_provenance = { + "path": _portable_path(cfg.diagnostics_path, cfg.project_root), + "sha256": sha256_file(cfg.diagnostics_path), + } + calibration = { + "schema_version": "1.0.0", + "evidence_label": EVIDENCE_LABEL, + "causal_claim": False, + "bundle_valid": True, + "scope": { + "source": "nyc_hvfhv", + "unit": "published_completed_trip_record_and_pickup_zone_hour", + "population_claim": False, + "pickup_min": conservation["pickup_min"], + "pickup_max": conservation["pickup_max"], + }, + "trip_level_descriptive_moments": trip_moments, + "zone_hour_variance_decomposition": variance, + "od_flow_graph": { + **graph_summary, + "representation": "undirected_monthly_completed_trip_flow_graph", + "edge_file": edge_path.name, + "exposure_mapping_file": exposure_mapping_path.name, + "exposure_mapping_schema": [ + "focal_zone_id", + "neighbor_zone_id", + "weight", + ], + "zone_id_semantics": ( + "NYC TLC LocationID; align CSV loader dtype with assignment zone_id" + ), + "exposure_mapping_direction": ( + "each undirected monthly edge is emitted in both focal directions" + ), + "node_file": node_path.name, + "self_loops": "excluded from edges; retained as node attribute", + "edge_weight": "sum of published completed trips in both directions", + "cluster_input_proposal": { + "target_cluster_count": runtime.target_cluster_count, + "status": "experiment_design_assumption_not_estimate", + "suggested_objective": ( + "minimize between-cluster completed-trip flow subject to balanced " + "pre-period volume and enough randomized clusters" + ), + "required_before_use": [ + "pre-treatment-only graph construction", + "cluster-size and volume balance checks", + "between-cluster exposure diagnostics", + "randomization-inference power analysis", + ], + }, + "interpretation": ( + "Observed OD weights define a candidate exposure graph but do not " + "estimate interference, rider substitution, or driver movement." + ), + "evidence_label": EVIDENCE_LABEL, + }, + "temporal_associations": { + "file": autocorrelation_path.name, + "lags_hours": list(runtime.exact_lag_hours), + "support_definition": ( + "same-zone pairs whose timestamps differ by exactly the declared lag" + ), + "interpretation": ( + "Exact-lag autocorrelation summarizes observed completed trips; it is " + "not assigned to the simulator persistence parameter." + ), + "evidence_label": EVIDENCE_LABEL, + }, + "simulator_scale_calibration_proposal": _calibration_proposal( + trip_moments, variance, template + ), + "conservation": {"raw_rows_declared": raw_rows, **conservation}, + "checks": checks, + "provenance": { + "source_data_manifest": manifest_validation, + "diagnostics": diagnostic_provenance, + "queried_inputs": { + "clean_parts": len(clean_files), + "zone_parts": len(zone_files), + "od_parts": len(od_files), + "paths": [ + _portable_path(path, cfg.project_root) for path in queried_files + ], + }, + "config": { + "data": cfg.as_serializable_dict(), + "calibration": runtime.to_dict(), + }, + }, + "limitations": [ + "Published completed trips exclude latent requests, unserved demand, and available drivers.", + "Request-to-pickup elapsed time is a published timestamp difference, not a randomized wait outcome or a complete rider-experience measure.", + "Base passenger fare and driver pay do not identify platform revenue, driver opportunity cost, price elasticity, or incentive response.", + "The ICC-like between-zone share is descriptive and is not a fitted random-effects ICC or experiment design effect.", + "OD edges are observed completed-trip connections, not causal spatial spillovers or equilibrium substitution parameters.", + "Temporal autocorrelation is not a causal persistence estimate.", + "Treatment response, spillover, persistence, substitution, compliance, and welfare remain explicit simulator assumptions.", + "One month does not establish seasonality or transportability to other months, products, or cities.", + ], + "critical_warning": CAUSAL_WARNING, + } + calibration_path = _atomic_json(calibration, stage / "calibration.json") + manifest_path = _bundle_manifest( + stage, manifest_validation, cfg, runtime + ) + _publish_directory(stage, output) + marker.unlink(missing_ok=True) + except BaseException: + raise + finally: + if temporary_root.exists(): + shutil.rmtree(temporary_root) + + return NYCCalibrationArtifacts( + output_directory=output, + calibration_path=output / calibration_path.name, + hour_profile_path=output / hour_path.name, + zone_profile_path=output / zone_path.name, + edge_path=output / edge_path.name, + exposure_mapping_path=output / exposure_mapping_path.name, + node_path=output / node_path.name, + autocorrelation_path=output / autocorrelation_path.name, + manifest_path=output / manifest_path.name, + ) + + +__all__ = [ + "NYCCalibrationArtifacts", + "NYCCalibrationSettings", + "write_nyc_calibration_bundle", +] diff --git a/CasualLab/src/casuallab/nyc_events.py b/CasualLab/src/casuallab/nyc_events.py new file mode 100644 index 0000000000000000000000000000000000000000..321e003758adcea272718749dc867a8939ce6742 --- /dev/null +++ b/CasualLab/src/casuallab/nyc_events.py @@ -0,0 +1,1052 @@ +"""Verified calendar and permitted-event enrichment for the NYC full-month panel. + +The external records are used only for descriptive associations. Permit windows +can include setup and breakdown, a permit is not attendance, and the source does +not enumerate every private-venue event. Nothing in this module identifies a +causal holiday or event effect. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import shutil +import tempfile +import urllib.request +from collections.abc import Sequence +from dataclasses import dataclass +from datetime import date +from pathlib import Path +from typing import Any + +import duckdb +import numpy as np +import pandas as pd + +from casuallab.data import sha256_file + +OPM_2024_HOLIDAY_URL = ( + "https://www.opm.gov/policy-data-oversight/pay-leave/federal-holidays/#url=2024" +) +NYC_2024_HOLIDAY_URL = ( + "https://www.nyc.gov/assets/opa/downloads/pdf/2024-list-of-holidays.pdf" +) +NYC_PERMITTED_EVENTS_DATASET_URL = ( + "https://data.cityofnewyork.us/City-Government/" + "NYC-Permitted-Event-Information-Historical/bkfu-528j" +) +NYC_PERMITTED_EVENTS_QUERY_URL = ( + "https://data.cityofnewyork.us/resource/bkfu-528j.csv?" + "%24select=event_id%2Cevent_name%2Cstart_date_time%2Cend_date_time%2C" + "event_agency%2Cevent_type%2Cevent_borough%2Cevent_location%2C" + "community_board%2Cpolice_precinct&" + "%24where=start_date_time%20%3C%20%272024-02-01T00%3A00%3A00.000%27%20" + "and%20end_date_time%20%3E%3D%20%272024-01-01T00%3A00%3A00.000%27&" + "%24order=start_date_time%2Cend_date_time%2Cevent_id%2Cevent_location&" + "%24limit=10000" +) + +HOLIDAY_SNAPSHOT_SHA256 = ( + "31a9c0880a4d248aeb17b7946d356c224dfd7831a7d4f1bed51b8873e81227db" +) +EVENT_SNAPSHOT_SHA256 = ( + "62bb6f5f312382fa647ddb3a45f860bbd979fb03cfb61572544b865569a54e75" +) +EVENT_EVIDENCE_LABEL = "descriptive_observed_external_calendar_events" +EVENT_SCHEMA_VERSION = "1.0.0" + +DEFAULT_MAJOR_EVENT_IDS = ("677860", "684757") +DEFAULT_PUBLIC_GATHERING_TYPES = ( + "Athletic Race / Tour", + "Farmers Market", + "Parade", + "Plaza Event", + "Plaza Partner Event", + "Religious Event", + "Single Block Festival", + "Street Event", + "Street Festival", +) + + +@dataclass(frozen=True, slots=True) +class NYCEventsConfig: + """Pinned January 2024 official-calendar and permit-source contract.""" + + start_date: date = date(2024, 1, 1) + end_date: date = date(2024, 1, 31) + expected_holiday_rows: int = 2 + expected_event_rows: int = 6007 + expected_unique_event_ids: int = 951 + holiday_snapshot_sha256: str = HOLIDAY_SNAPSHOT_SHA256 + event_snapshot_sha256: str = EVENT_SNAPSHOT_SHA256 + major_event_ids: tuple[str, ...] = DEFAULT_MAJOR_EVENT_IDS + public_gathering_event_types: tuple[str, ...] = DEFAULT_PUBLIC_GATHERING_TYPES + + def __post_init__(self) -> None: + if self.start_date > self.end_date: + raise ValueError("event start_date must not exceed end_date") + if self.expected_holiday_rows < 1: + raise ValueError("expected_holiday_rows must be positive") + if self.expected_event_rows < 1 or self.expected_unique_event_ids < 1: + raise ValueError("event row and unique-ID expectations must be positive") + if self.expected_unique_event_ids > self.expected_event_rows: + raise ValueError("expected_unique_event_ids cannot exceed expected_event_rows") + for field_name in ("holiday_snapshot_sha256", "event_snapshot_sha256"): + digest = getattr(self, field_name) + if len(digest) != 64 or any( + character not in "0123456789abcdef" for character in digest + ): + raise ValueError(f"{field_name} must be a lowercase SHA-256 digest") + if not self.major_event_ids or len(set(self.major_event_ids)) != len( + self.major_event_ids + ): + raise ValueError("major_event_ids must be nonempty and unique") + if any(not event_id.strip() for event_id in self.major_event_ids): + raise ValueError("major_event_ids cannot contain blank IDs") + if not self.public_gathering_event_types or len( + set(self.public_gathering_event_types) + ) != len(self.public_gathering_event_types): + raise ValueError("public_gathering_event_types must be nonempty and unique") + + @property + def expected_calendar_days(self) -> int: + return (self.end_date - self.start_date).days + 1 + + +@dataclass(frozen=True, slots=True) +class NYCEventsArtifacts: + calendar_daily_path: Path + normalized_events_path: Path + event_type_daily_path: Path + daily_panel_path: Path + hourly_contrast_path: Path + summary_path: Path + manifest_path: Path + + def paths(self) -> tuple[Path, ...]: + return ( + self.calendar_daily_path, + self.normalized_events_path, + self.event_type_daily_path, + self.daily_panel_path, + self.hourly_contrast_path, + self.summary_path, + self.manifest_path, + ) + + +def _atomic_json(payload: dict[str, Any], path: Path) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + prefix=f".{path.stem}-", + suffix=path.suffix, + dir=path.parent, + delete=False, + ) as handle: + temporary = Path(handle.name) + json.dump(payload, handle, indent=2, sort_keys=True, allow_nan=False) + handle.write("\n") + temporary.replace(path) + return path + + +def _atomic_csv(frame: pd.DataFrame, path: Path) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="", + prefix=f".{path.stem}-", + suffix=path.suffix, + dir=path.parent, + delete=False, + ) as handle: + temporary = Path(handle.name) + frame.to_csv(handle, index=False) + temporary.replace(path) + return path + + +def download_nyc_permitted_events_snapshot( + destination: str | Path, + config: NYCEventsConfig | None = None, + *, + refresh: bool = False, +) -> Path: + """Atomically download and verify the pinned NYC Open Data CSV response.""" + + cfg = config or NYCEventsConfig() + target = Path(destination) + target.parent.mkdir(parents=True, exist_ok=True) + if target.is_file() and not refresh: + if sha256_file(target) != cfg.event_snapshot_sha256: + raise ValueError("cached NYC permitted-events SHA-256 does not match the pin") + return target + with tempfile.NamedTemporaryFile( + prefix=f".{target.stem}-", + suffix=target.suffix, + dir=target.parent, + delete=False, + ) as handle: + temporary = Path(handle.name) + request = urllib.request.Request( + NYC_PERMITTED_EVENTS_QUERY_URL, + headers={"User-Agent": "CausalMarketplaceLab/0.1 descriptive research"}, + ) + try: + with urllib.request.urlopen(request, timeout=120) as response, temporary.open( + "wb" + ) as stream: + while block := response.read(1024 * 1024): + stream.write(block) + if sha256_file(temporary) != cfg.event_snapshot_sha256: + raise ValueError("downloaded NYC permitted-events SHA-256 does not match the pin") + temporary.replace(target) + except Exception: + temporary.unlink(missing_ok=True) + raise + return target + + +def normalize_nyc_holiday_calendar( + holiday_snapshot_path: str | Path, + config: NYCEventsConfig | None = None, +) -> pd.DataFrame: + """Validate positive holiday rows and expand them to a complete daily calendar.""" + + cfg = config or NYCEventsConfig() + source = Path(holiday_snapshot_path) + if not source.is_file(): + raise FileNotFoundError(source) + if sha256_file(source) != cfg.holiday_snapshot_sha256: + raise ValueError("official holiday snapshot SHA-256 does not match the pin") + holidays = pd.read_csv(source, dtype="string", keep_default_na=False) + required_columns = ( + "service_date", + "federal_holiday_name", + "nyc_city_employee_holiday_name", + ) + missing = set(required_columns).difference(holidays.columns) + if missing: + raise ValueError(f"holiday snapshot missing fields: {sorted(missing)}") + if len(holidays) != cfg.expected_holiday_rows: + raise ValueError("holiday snapshot has an unexpected row count") + dates = pd.to_datetime(holidays["service_date"], errors="raise").dt.date + if holidays["service_date"].duplicated().any() or list(dates) != sorted(dates): + raise ValueError("holiday dates must be unique and sorted") + if any(day < cfg.start_date or day > cfg.end_date for day in dates): + raise ValueError("holiday snapshot contains a date outside the configured period") + for column in ("federal_holiday_name", "nyc_city_employee_holiday_name"): + if holidays[column].str.strip().eq("").any(): + raise ValueError(f"holiday snapshot contains a blank {column}") + + calendar = pd.DataFrame( + {"service_date": pd.date_range(cfg.start_date, cfg.end_date, freq="D").date} + ) + # Keep publication bytes independent of Python's hash-randomized set order. + selected = holidays.loc[:, required_columns].copy() + selected["service_date"] = dates + calendar = calendar.merge(selected, on="service_date", how="left", validate="1:1") + for column in ("federal_holiday_name", "nyc_city_employee_holiday_name"): + calendar[column] = calendar[column].fillna("").astype(str) + calendar["is_federal_holiday"] = calendar["federal_holiday_name"].ne("") + calendar["is_nyc_city_employee_holiday"] = calendar[ + "nyc_city_employee_holiday_name" + ].ne("") + calendar["is_any_official_holiday"] = ( + calendar["is_federal_holiday"] + | calendar["is_nyc_city_employee_holiday"] + ) + calendar["evidence_label"] = EVENT_EVIDENCE_LABEL + calendar["causal_claim"] = False + return calendar.sort_values("service_date").reset_index(drop=True) + + +def normalize_nyc_permitted_events( + event_snapshot_path: str | Path, + config: NYCEventsConfig | None = None, +) -> pd.DataFrame: + """Validate the complete ordered January-overlap permit response. + + Invalid source intervals are retained and flagged rather than silently repaired. + Such rows are excluded from date expansion. + """ + + cfg = config or NYCEventsConfig() + source = Path(event_snapshot_path) + if not source.is_file(): + raise FileNotFoundError(source) + if sha256_file(source) != cfg.event_snapshot_sha256: + raise ValueError("NYC permitted-events snapshot SHA-256 does not match the pin") + events = pd.read_csv(source, dtype="string", keep_default_na=False) + required = { + "event_id", + "event_name", + "start_date_time", + "end_date_time", + "event_agency", + "event_type", + "event_borough", + "event_location", + "community_board", + "police_precinct", + } + missing = required.difference(events.columns) + if missing: + raise ValueError(f"permitted-events snapshot missing fields: {sorted(missing)}") + if len(events) != cfg.expected_event_rows: + raise ValueError("permitted-events snapshot has an unexpected row count") + if events.duplicated().any(): + raise ValueError("permitted-events snapshot contains exact duplicate rows") + for column in ( + "event_id", + "start_date_time", + "end_date_time", + "event_agency", + "event_type", + "event_borough", + "event_location", + ): + if events[column].str.strip().eq("").any(): + raise ValueError(f"permitted-events snapshot contains a blank {column}") + if events["event_id"].nunique() != cfg.expected_unique_event_ids: + raise ValueError("permitted-events snapshot has an unexpected unique event-ID count") + if not set(cfg.major_event_ids).issubset(set(events["event_id"])): + raise ValueError("pre-specified major event IDs are missing from the snapshot") + if (events.groupby("event_id")["event_type"].nunique() > 1).any(): + raise ValueError("one event ID maps to multiple event types") + + start = pd.to_datetime(events["start_date_time"], errors="raise") + end = pd.to_datetime(events["end_date_time"], errors="raise") + ordered = events.assign( + _start=start, + _end=end, + _event_id_number=pd.to_numeric(events["event_id"], errors="raise"), + ).sort_values( + ["_start", "_end", "_event_id_number", "event_location"], + kind="mergesort", + ) + if not np.array_equal(ordered.index.to_numpy(), events.index.to_numpy()): + raise ValueError("permitted-events snapshot does not match the pinned query order") + + normalized = events.copy() + normalized["permit_start_local"] = start + normalized["permit_end_local"] = end + normalized["invalid_permit_interval"] = end < start + normalized["zero_duration_permit_interval"] = end == start + normalized["usable_for_daily_expansion"] = end > start + normalized["researcher_defined_major_event"] = normalized["event_id"].isin( + cfg.major_event_ids + ) + normalized["public_gathering_permit_subset"] = normalized["event_type"].isin( + cfg.public_gathering_event_types + ) + normalized["event_name_missing"] = normalized["event_name"].str.strip().eq("") + normalized["evidence_label"] = EVENT_EVIDENCE_LABEL + normalized["causal_claim"] = False + return normalized + + +def build_nyc_event_calendar( + holidays: pd.DataFrame, + events: pd.DataFrame, + config: NYCEventsConfig | None = None, +) -> tuple[pd.DataFrame, pd.DataFrame]: + """Expand valid permit rows to daily event-ID exposures and aggregate by type.""" + + cfg = config or NYCEventsConfig() + expected_dates = list(pd.date_range(cfg.start_date, cfg.end_date, freq="D").date) + if list(holidays["service_date"]) != expected_dates: + raise ValueError("holiday calendar is not complete for the configured period") + required = { + "event_id", + "event_name", + "event_type", + "permit_start_local", + "permit_end_local", + "usable_for_daily_expansion", + "researcher_defined_major_event", + "public_gathering_permit_subset", + } + missing = required.difference(events.columns) + if missing: + raise ValueError(f"normalized events missing fields: {sorted(missing)}") + + event_days: list[dict[str, object]] = [] + valid = events.loc[events["usable_for_daily_expansion"].astype(bool)] + period_start = pd.Timestamp(cfg.start_date) + period_end = pd.Timestamp(cfg.end_date) + for row in valid.itertuples(index=False): + permit_start = pd.Timestamp(row.permit_start_local) + permit_end = pd.Timestamp(row.permit_end_local) + first = max(permit_start.normalize(), period_start) + # Permit windows are half-open. An interval ending exactly at midnight + # does not create exposure on the following service date. + last = min( + (permit_end - pd.Timedelta(nanoseconds=1)).normalize(), + period_end, + ) + if first > last: + continue + for service_date in pd.date_range(first, last, freq="D").date: + event_days.append( + { + "service_date": service_date, + "event_id": str(row.event_id), + "event_name": str(row.event_name), + "event_type": str(row.event_type), + "researcher_defined_major_event": bool( + row.researcher_defined_major_event + ), + "public_gathering_permit_subset": bool( + row.public_gathering_permit_subset + ), + } + ) + expanded = pd.DataFrame(event_days) + if expanded.empty: + raise ValueError("no valid permitted-event rows overlap the configured period") + expanded = expanded.drop_duplicates(["service_date", "event_id"]) + + daily = ( + expanded.groupby("service_date", observed=True) + .agg( + active_permitted_event_count=("event_id", "nunique"), + active_public_gathering_permitted_event_count=( + "public_gathering_permit_subset", + "sum", + ), + active_major_permitted_event_count=( + "researcher_defined_major_event", + "sum", + ), + ) + .reset_index() + ) + major_names = ( + expanded.loc[expanded["researcher_defined_major_event"]] + .groupby("service_date", observed=True)["event_name"] + .agg(lambda values: " | ".join(sorted(set(values)))) + .rename("major_permitted_event_names") + .reset_index() + ) + daily = daily.merge(major_names, on="service_date", how="left", validate="1:1") + calendar = holidays.merge(daily, on="service_date", how="left", validate="1:1") + count_columns = ( + "active_permitted_event_count", + "active_public_gathering_permitted_event_count", + "active_major_permitted_event_count", + ) + for column in count_columns: + calendar[column] = calendar[column].fillna(0).astype(int) + calendar["major_permitted_event_names"] = calendar[ + "major_permitted_event_names" + ].fillna("") + calendar["is_researcher_defined_major_event_day"] = ( + calendar["active_major_permitted_event_count"] > 0 + ) + median_intensity = float(calendar["active_permitted_event_count"].median()) + calendar["monthly_median_active_permitted_event_count"] = median_intensity + calendar["is_above_monthly_median_permit_intensity_day"] = ( + calendar["active_permitted_event_count"] > median_intensity + ) + calendar["permit_intensity_band"] = np.where( + calendar["is_above_monthly_median_permit_intensity_day"], + "above_monthly_median", + "at_or_below_monthly_median", + ) + calendar["event_signal_spatial_granularity"] = "citywide" + calendar["event_signal_temporal_granularity"] = "service_date" + calendar["evidence_label"] = EVENT_EVIDENCE_LABEL + calendar["causal_claim"] = False + + type_daily = ( + expanded.groupby(["service_date", "event_type"], observed=True)["event_id"] + .nunique() + .rename("active_unique_permitted_events") + .reset_index() + .sort_values(["service_date", "event_type"]) + .reset_index(drop=True) + ) + type_daily["evidence_label"] = EVENT_EVIDENCE_LABEL + type_daily["causal_claim"] = False + return calendar, type_daily + + +def _sql_string(value: str) -> str: + return "'" + value.replace("'", "''") + "'" + + +def _scan_sql(paths: Sequence[Path]) -> str: + if not paths: + raise FileNotFoundError("NYC event analysis requires zone-time Parquet files") + rendered = ", ".join(_sql_string(str(path.resolve())) for path in paths) + return f"read_parquet([{rendered}], hive_partitioning=false)" + + +def _finite_correlation(left: pd.Series, right: pd.Series) -> float | None: + valid = left.notna() & right.notna() + if valid.sum() < 3 or left.loc[valid].nunique() < 2 or right.loc[valid].nunique() < 2: + return None + value = float(left.loc[valid].corr(right.loc[valid])) + return value if math.isfinite(value) else None + + +def _binary_contrast(frame: pd.DataFrame, flag: str) -> dict[str, float | int | None]: + selected = frame[flag].astype(bool) + true_mean = float(frame.loc[selected, "published_completed_trips"].mean()) + false_mean = float(frame.loc[~selected, "published_completed_trips"].mean()) + difference = true_mean - false_mean + return { + "exposed_days": int(selected.sum()), + "comparison_days": int((~selected).sum()), + "mean_daily_published_completed_trips_exposed": true_mean, + "mean_daily_published_completed_trips_comparison": false_mean, + "exposed_minus_comparison_mean_daily_published_completed_trips": difference, + "exposed_minus_comparison_relative_to_comparison": ( + difference / false_mean if false_mean else None + ), + } + + +def _within_group_demeaned_correlation( + frame: pd.DataFrame, + left: str, + right: str, + group: str, +) -> float | None: + left_residual = frame[left] - frame.groupby(group, observed=True)[left].transform("mean") + right_residual = frame[right] - frame.groupby(group, observed=True)[right].transform( + "mean" + ) + return _finite_correlation(left_residual, right_residual) + + +def event_demand_associations( + zone_time_paths: Sequence[str | Path], + calendar: pd.DataFrame, + events: pd.DataFrame, + type_daily: pd.DataFrame, + config: NYCEventsConfig | None = None, +) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]: + """Join citywide daily signals to trip totals and compute descriptive contrasts.""" + + cfg = config or NYCEventsConfig() + paths = tuple(Path(path) for path in zone_time_paths) + scan = _scan_sql(paths) + connection = duckdb.connect(database=":memory:") + try: + daily = connection.execute( + f""" + SELECT CAST(service_date AS DATE) AS service_date, + SUM(CAST(trip_count AS BIGINT)) AS published_completed_trips, + COUNT(DISTINCT zone_id) AS panel_zones, + SUM(CASE WHEN trip_count > 0 THEN 1 ELSE 0 END) AS occupied_zone_hours + FROM {scan} + GROUP BY 1 + ORDER BY 1 + """ + ).fetchdf() + hourly = connection.execute( + f""" + SELECT CAST(service_date AS DATE) AS service_date, + CAST(hour AS INTEGER) AS hour, + SUM(CAST(trip_count AS BIGINT)) AS published_completed_trips + FROM {scan} + GROUP BY 1, 2 + ORDER BY 1, 2 + """ + ).fetchdf() + finally: + connection.close() + daily["service_date"] = pd.to_datetime(daily["service_date"]).dt.date + hourly["service_date"] = pd.to_datetime(hourly["service_date"]).dt.date + expected_dates = set(pd.date_range(cfg.start_date, cfg.end_date, freq="D").date) + if set(daily["service_date"]) != expected_dates or len(daily) != cfg.expected_calendar_days: + raise ValueError("NYC zone-time panel does not cover the configured event month") + if len(hourly) != cfg.expected_calendar_days * 24: + raise ValueError("NYC zone-time panel does not contain every configured date-hour") + + event_calendar = calendar.copy() + event_calendar["service_date"] = pd.to_datetime( + event_calendar["service_date"], errors="raise" + ).dt.date + daily = daily.merge(event_calendar, on="service_date", how="left", validate="1:1") + if daily["evidence_label"].isna().any(): + raise ValueError("calendar/event coverage is incomplete after joining the NYC panel") + daily["iso_weekday"] = ( + pd.to_datetime(daily["service_date"]).dt.isocalendar().day.astype(int) + ) + + hourly = hourly.merge( + event_calendar[ + [ + "service_date", + "is_any_official_holiday", + "is_researcher_defined_major_event_day", + "is_above_monthly_median_permit_intensity_day", + ] + ], + on="service_date", + how="left", + validate="m:1", + ) + group_flag = "is_above_monthly_median_permit_intensity_day" + hourly_contrast = ( + hourly.groupby(["hour", group_flag], observed=True)["published_completed_trips"] + .agg(["count", "mean"]) + .reset_index() + .pivot(index="hour", columns=group_flag, values=["count", "mean"]) + ) + hourly_contrast.columns = [ + f"{'days' if measure == 'count' else 'mean_published_completed_trips'}_" + f"{'above_median_intensity' if high else 'at_or_below_median_intensity'}" + for measure, high in hourly_contrast.columns + ] + hourly_contrast = hourly_contrast.reset_index() + needed_columns = ( + "days_above_median_intensity", + "days_at_or_below_median_intensity", + "mean_published_completed_trips_above_median_intensity", + "mean_published_completed_trips_at_or_below_median_intensity", + ) + for column in needed_columns: + if column not in hourly_contrast: + hourly_contrast[column] = np.nan + hourly_contrast["above_minus_at_or_below_mean_published_completed_trips"] = ( + hourly_contrast["mean_published_completed_trips_above_median_intensity"] + - hourly_contrast[ + "mean_published_completed_trips_at_or_below_median_intensity" + ] + ) + hourly_contrast["event_signal_temporal_granularity"] = "service_date" + hourly_contrast["evidence_label"] = EVENT_EVIDENCE_LABEL + hourly_contrast["causal_claim"] = False + + major = daily["is_researcher_defined_major_event_day"].astype(bool) + holiday = daily["is_any_official_holiday"].astype(bool) + high = daily["is_above_monthly_median_permit_intensity_day"].astype(bool) + weekend = daily["iso_weekday"] >= 6 + weekdays = daily.loc[~weekend].copy() + valid_events = events["usable_for_daily_expansion"].astype(bool) + summary = { + "schema_version": EVENT_SCHEMA_VERSION, + "evidence_label": EVENT_EVIDENCE_LABEL, + "causal_claim": False, + "scope": { + "city": "New York City", + "pickup_month": "2024-01", + "published_completed_trip_days": len(daily), + "event_signal_spatial_granularity": "citywide", + "event_signal_temporal_granularity": "service_date", + "population_claim": False, + }, + "definitions": { + "official_holiday": ( + "A positive date in the complete January transcription of the OPM " + "federal and/or NYC employee holiday schedules." + ), + "active_permitted_event_count": ( + "Unique NYC Open Data event IDs with at least one positive-duration " + "permit row whose half-open [start, end) interval overlaps the service date." + ), + "public_gathering_permit_subset": list(cfg.public_gathering_event_types), + "above_monthly_median_permit_intensity": ( + "Active unique permitted-event count strictly above the source-only " + "monthly median; trip outcomes are not used to set the threshold." + ), + "researcher_defined_major_permitted_event": { + "event_ids": list(cfg.major_event_ids), + "event_names": sorted( + set( + events.loc[ + events["event_id"].isin(cfg.major_event_ids), "event_name" + ].astype(str) + ) + ), + "official_severity_classification": False, + }, + }, + "coverage": { + "holiday_source_positive_rows": cfg.expected_holiday_rows, + "joined_days": len(daily), + "joined_date_hours": len(hourly), + "federal_holiday_days": int(daily["is_federal_holiday"].sum()), + "nyc_city_employee_holiday_days": int( + daily["is_nyc_city_employee_holiday"].sum() + ), + "any_official_holiday_days": int(holiday.sum()), + "source_permit_rows": len(events), + "source_unique_event_ids": int(events["event_id"].nunique()), + "valid_interval_rows": int(valid_events.sum()), + "invalid_interval_rows_retained_but_not_expanded": int( + events["invalid_permit_interval"].sum() + ), + "zero_duration_interval_rows_retained_but_not_expanded": int( + events["zero_duration_permit_interval"].sum() + ), + "all_nonpositive_interval_rows_retained_but_not_expanded": int( + (~valid_events).sum() + ), + "event_name_missing_rows_retained": int(events["event_name_missing"].sum()), + "valid_unique_event_ids": int( + events.loc[valid_events, "event_id"].nunique() + ), + "event_types": int(events["event_type"].nunique()), + "expanded_unique_event_days": int( + type_daily["active_unique_permitted_events"].sum() + ), + "minimum_daily_active_permitted_events": int( + daily["active_permitted_event_count"].min() + ), + "median_daily_active_permitted_events": float( + daily["active_permitted_event_count"].median() + ), + "maximum_daily_active_permitted_events": int( + daily["active_permitted_event_count"].max() + ), + "above_median_permit_intensity_days": int(high.sum()), + "at_or_below_median_permit_intensity_days": int((~high).sum()), + "weekend_days": int(weekend.sum()), + "above_median_permit_intensity_weekend_days": int((high & weekend).sum()), + "at_or_below_median_permit_intensity_weekend_days": int( + ((~high) & weekend).sum() + ), + "researcher_defined_major_event_days": int(major.sum()), + }, + "associations": { + "above_vs_at_or_below_median_permit_intensity": _binary_contrast( + daily, "is_above_monthly_median_permit_intensity_day" + ), + "above_vs_at_or_below_median_permit_intensity_weekdays_only": ( + _binary_contrast( + weekdays, "is_above_monthly_median_permit_intensity_day" + ) + ), + "official_holiday_vs_nonholiday": _binary_contrast( + daily, "is_any_official_holiday" + ), + "major_permitted_event_day_vs_other_days": _binary_contrast( + daily, "is_researcher_defined_major_event_day" + ), + "active_permitted_event_count_daily_trip_correlation": _finite_correlation( + daily["active_permitted_event_count"], + daily["published_completed_trips"], + ), + "active_public_gathering_permit_count_daily_trip_correlation": ( + _finite_correlation( + daily["active_public_gathering_permitted_event_count"], + daily["published_completed_trips"], + ) + ), + "weekday_demeaned_active_permit_count_daily_trip_correlation": ( + _within_group_demeaned_correlation( + daily, + "active_permitted_event_count", + "published_completed_trips", + "iso_weekday", + ) + ), + }, + "identification_checks": { + "major_event_days_are_subset_of_holiday_days": bool((~major | holiday).all()), + "all_weekend_days_are_above_median_permit_intensity": bool( + high.loc[weekend].all() + ), + "major_event_contrast_separately_identifies_event_effect": False, + "permit_intensity_assignment_is_randomized": False, + "causal_effect_identified": False, + }, + "conservation": { + "zone_time_trip_sum": int(daily["published_completed_trips"].sum()), + "daily_trip_sum": int(daily["published_completed_trips"].sum()), + "passes": True, + }, + "limitations": [ + "All contrasts are observational associations; weekday, seasonality, weather, holidays, and other demand or supply shocks confound them.", + "In this month every weekend is above the permit-intensity median, so the unstratified high-versus-lower contrast is mechanically entangled with weekend composition; weekday-only and weekday-demeaned diagnostics remain descriptive.", + "Permit timestamps often include setup and breakdown and do not measure attendance, realized event scale, or the actual audience window.", + "Signals are citywide daily proxies: borough/board/precinct strings are not a validated Taxi Zone crosswalk, so zone- and hour-specific exposure is unavailable.", + "The historical permit dataset does not enumerate every arena, stadium, theater, concert, or private-venue event.", + "One reversed and eight zero-duration source intervals are retained and flagged but excluded from date expansion; no undocumented timestamp correction is made.", + "The narrow major-event flag occurs only on New Year's Day, so its one-day contrast cannot be separated from the holiday or extrapolated.", + "Published completed trips exclude latent requests, unserved demand, and available drivers.", + "One January month does not establish seasonal or annual transportability.", + ], + } + return daily, hourly_contrast, summary + + +def _portable(path: Path, root: Path) -> str: + try: + return str(path.resolve().relative_to(root.resolve())) + except ValueError as exc: + raise ValueError(f"event artifact path is outside project_root: {path}") from exc + + +def _manifest_entry( + path: Path, + root: Path, + role: str, + *, + source_url: str | None = None, +) -> dict[str, Any]: + entry: dict[str, Any] = { + "path": _portable(path, root), + "role": role, + "bytes": path.stat().st_size, + "sha256": sha256_file(path), + } + if source_url is not None: + entry["source_url"] = source_url + return entry + + +def _entries_digest(entries: list[dict[str, Any]]) -> str: + return hashlib.sha256( + json.dumps(entries, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + + +def write_nyc_events_bundle( + holiday_snapshot_path: str | Path, + event_snapshot_path: str | Path, + panel_directory: str | Path, + data_manifest_path: str | Path, + output_directory: str | Path, + *, + project_root: str | Path, + config: NYCEventsConfig | None = None, +) -> NYCEventsArtifacts: + """Create a manifest-last, hash-verified NYC calendar/event bundle.""" + + cfg = config or NYCEventsConfig() + root = Path(project_root).resolve() + holiday_source = Path(holiday_snapshot_path).resolve() + event_source = Path(event_snapshot_path).resolve() + panel_root = Path(panel_directory).resolve() + source_manifest_path = Path(data_manifest_path).resolve() + output = Path(output_directory).resolve() + output.mkdir(parents=True, exist_ok=True) + marker = output / "NYC_EVENTS_INCOMPLETE.json" + manifest_path = output / "manifest.json" + manifest_path.unlink(missing_ok=True) + _atomic_json({"status": "incomplete"}, marker) + stage = Path(tempfile.mkdtemp(prefix=f".{output.name}-", dir=output.parent)) + + try: + source_manifest = json.loads(source_manifest_path.read_text(encoding="utf-8")) + if ( + source_manifest.get("config", {}).get("source") != "nyc_hvfhv" + or source_manifest.get("config", {}).get("mode") != "full" + or source_manifest.get("metadata", {}).get("evidence_label") + != "descriptive_real_data" + or source_manifest.get("metadata", {}).get("causal_claim") is not False + ): + raise ValueError("event analysis requires the verified NYC full-data manifest") + panel_paths = tuple(sorted(path.resolve() for path in panel_root.rglob("*.parquet"))) + if not panel_paths: + raise FileNotFoundError("NYC full zone-time panel is unavailable") + declared: dict[Path, dict[str, Any]] = {} + for entry in source_manifest.get("files", []): + if not isinstance(entry, dict) or not isinstance(entry.get("path"), str): + raise ValueError("NYC source manifest contains a malformed file entry") + declared_path = Path(entry["path"]) + if declared_path.is_absolute() or ".." in declared_path.parts: + raise ValueError("NYC source manifest contains a nonportable path") + resolved = (root / declared_path).resolve() + try: + resolved.relative_to(root) + except ValueError as exc: + raise ValueError("NYC source manifest path escapes project_root") from exc + if resolved in declared: + raise ValueError("NYC source manifest contains duplicate file paths") + declared[resolved] = entry + declared_panel_paths = { + path + for path in declared + if path.suffix == ".parquet" and path.is_relative_to(panel_root) + } + if set(panel_paths) != declared_panel_paths: + raise ValueError( + "NYC event panel files do not exactly match the source manifest" + ) + for path in panel_paths: + entry = declared[path] + if path.stat().st_size != entry.get("bytes") or sha256_file(path) != entry.get( + "sha256" + ): + raise ValueError(f"NYC event panel lineage mismatch: {path}") + + holidays = normalize_nyc_holiday_calendar(holiday_source, cfg) + events = normalize_nyc_permitted_events(event_source, cfg) + calendar, type_daily = build_nyc_event_calendar(holidays, events, cfg) + daily, hourly, summary = event_demand_associations( + panel_paths, calendar, events, type_daily, cfg + ) + expected_trips = int( + source_manifest["metadata"]["full_month_processing"]["row_conservation"][ + "zone_time_trip_sum" + ] + ) + if summary["conservation"]["daily_trip_sum"] != expected_trips: + raise ValueError("NYC event daily panel does not conserve published trips") + summary["provenance"] = { + "holiday_snapshot_path": _portable(holiday_source, root), + "holiday_snapshot_bytes": holiday_source.stat().st_size, + "holiday_snapshot_sha256": sha256_file(holiday_source), + "opm_2024_holiday_url": OPM_2024_HOLIDAY_URL, + "nyc_2024_employee_holiday_url": NYC_2024_HOLIDAY_URL, + "permitted_events_dataset_url": NYC_PERMITTED_EVENTS_DATASET_URL, + "permitted_events_query_url": NYC_PERMITTED_EVENTS_QUERY_URL, + "event_snapshot_path": _portable(event_source, root), + "event_snapshot_bytes": event_source.stat().st_size, + "event_snapshot_sha256": sha256_file(event_source), + "nyc_data_manifest_path": _portable(source_manifest_path, root), + "nyc_data_manifest_sha256": sha256_file(source_manifest_path), + "panel_files_verified": len(panel_paths), + "hashes_recomputed": True, + } + + staged_paths = { + "calendar_daily": _atomic_csv(calendar, stage / "calendar_event_daily.csv"), + "normalized_events": _atomic_csv( + events, stage / "permitted_events_normalized.csv" + ), + "event_type_daily": _atomic_csv( + type_daily, stage / "permitted_event_type_daily.csv" + ), + "daily_panel": _atomic_csv(daily, stage / "event_trip_daily.csv"), + "hourly_contrast": _atomic_csv( + hourly, stage / "event_hourly_contrasts.csv" + ), + "summary": _atomic_json(summary, stage / "event_associations.json"), + } + published: dict[str, Path] = {} + for key, staged_path in staged_paths.items(): + destination = output / staged_path.name + staged_path.replace(destination) + published[key] = destination + + files = [ + _manifest_entry(published["calendar_daily"], root, "normalized_daily_calendar"), + _manifest_entry( + published["normalized_events"], root, "normalized_permit_records" + ), + _manifest_entry( + published["event_type_daily"], root, "daily_permit_type_counts" + ), + _manifest_entry(published["daily_panel"], root, "joined_daily_trip_panel"), + _manifest_entry( + published["hourly_contrast"], root, "descriptive_hourly_profiles" + ), + _manifest_entry(published["summary"], root, "descriptive_summary"), + ] + inputs = [ + _manifest_entry( + holiday_source, + root, + "official_holiday_snapshot", + source_url=OPM_2024_HOLIDAY_URL, + ), + _manifest_entry( + event_source, + root, + "official_nyc_permitted_events_snapshot", + source_url=NYC_PERMITTED_EVENTS_QUERY_URL, + ), + _manifest_entry( + source_manifest_path, + root, + "nyc_full_data_manifest", + ), + *[ + _manifest_entry(path, root, "nyc_full_zone_time_panel") + for path in panel_paths + ], + ] + _atomic_json( + { + "schema_version": EVENT_SCHEMA_VERSION, + "evidence_label": EVENT_EVIDENCE_LABEL, + "causal_claim": False, + "portable_paths": True, + "files": files, + "inputs": inputs, + "declared_file_set_sha256": _entries_digest(files), + "declared_input_set_sha256": _entries_digest(inputs), + "checks": { + "holiday_snapshot_hash_matches": ( + sha256_file(holiday_source) == cfg.holiday_snapshot_sha256 + ), + "event_snapshot_hash_matches": ( + sha256_file(event_source) == cfg.event_snapshot_sha256 + ), + "calendar_complete": len(calendar) == cfg.expected_calendar_days, + "holiday_schedule_coverage_complete": True, + "event_source_rows_verified": len(events) == cfg.expected_event_rows, + "event_source_unique_ids_verified": ( + events["event_id"].nunique() == cfg.expected_unique_event_ids + ), + "invalid_source_intervals_retained_and_excluded": ( + int(events["invalid_permit_interval"].sum()) == 1 + if cfg == NYCEventsConfig() + else True + ), + "zero_duration_source_intervals_retained_and_excluded": ( + int(events["zero_duration_permit_interval"].sum()) == 8 + if cfg == NYCEventsConfig() + else True + ), + "daily_signal_is_citywide_not_zone_exposure": True, + "hourly_profiles_repeat_daily_signal_not_event_hour_exposure": True, + "major_event_is_researcher_defined": True, + "major_event_contrast_separately_identified": False, + "nyc_source_manifest_valid": True, + "panel_files_verified": len(panel_paths), + "joined_days": len(daily), + "joined_date_hours": cfg.expected_calendar_days * 24, + "trip_conservation": True, + "causal_claim_is_false": True, + }, + }, + manifest_path, + ) + marker.unlink(missing_ok=True) + return NYCEventsArtifacts( + calendar_daily_path=published["calendar_daily"], + normalized_events_path=published["normalized_events"], + event_type_daily_path=published["event_type_daily"], + daily_panel_path=published["daily_panel"], + hourly_contrast_path=published["hourly_contrast"], + summary_path=published["summary"], + manifest_path=manifest_path, + ) + finally: + shutil.rmtree(stage, ignore_errors=True) + + +__all__ = [ + "DEFAULT_MAJOR_EVENT_IDS", + "DEFAULT_PUBLIC_GATHERING_TYPES", + "EVENT_EVIDENCE_LABEL", + "EVENT_SCHEMA_VERSION", + "EVENT_SNAPSHOT_SHA256", + "HOLIDAY_SNAPSHOT_SHA256", + "NYCEventsArtifacts", + "NYCEventsConfig", + "NYC_2024_HOLIDAY_URL", + "NYC_PERMITTED_EVENTS_DATASET_URL", + "NYC_PERMITTED_EVENTS_QUERY_URL", + "OPM_2024_HOLIDAY_URL", + "build_nyc_event_calendar", + "download_nyc_permitted_events_snapshot", + "event_demand_associations", + "normalize_nyc_holiday_calendar", + "normalize_nyc_permitted_events", + "write_nyc_events_bundle", +] diff --git a/CasualLab/src/casuallab/nyc_full_analysis.py b/CasualLab/src/casuallab/nyc_full_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..2de94d325580d80e67ab6ed653a0a4437ee059d1 --- /dev/null +++ b/CasualLab/src/casuallab/nyc_full_analysis.py @@ -0,0 +1,684 @@ +"""Fail-closed descriptive validation for a streamed NYC full-month build.""" + +from __future__ import annotations + +import json +import platform +import tempfile +from calendar import monthrange +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from datetime import UTC, date, datetime +from pathlib import Path +from time import perf_counter +from typing import Any + +import duckdb +import numpy as np +import pyarrow.parquet as pq + +from casuallab.analysis import write_descriptive_artifacts +from casuallab.data import ( + NYC_HVFHV_RAW_SCHEMA, + REQUIRED_RAW_COLUMNS, + DataConfig, + load_data_config, + nyc_hvfhv_urls, + read_partitioned_parquet, + sha256_file, + write_manifest, +) + +try: # pragma: no cover - resource is unavailable only on non-POSIX platforms. + import resource +except ImportError: # pragma: no cover + resource = None # type: ignore[assignment] + + +@dataclass(frozen=True, slots=True) +class NYCFullAnalysisArtifacts: + """Generated validation, report, tables, and lineage manifest.""" + + validation_path: Path + report_path: Path + daily_path: Path + hourly_path: Path + weekday_path: Path + zone_path: Path + od_month_path: Path + descriptive_paths: tuple[Path, ...] + manifest_path: Path + + def paths(self) -> tuple[Path, ...]: + return ( + self.validation_path, + self.report_path, + self.daily_path, + self.hourly_path, + self.weekday_path, + self.zone_path, + self.od_month_path, + *self.descriptive_paths, + self.manifest_path, + ) + + +def _json_safe(value: Any) -> Any: + if isinstance(value, Path): + return str(value) + if isinstance(value, (date, datetime)): + return value.isoformat() + if isinstance(value, Mapping): + return {str(key): _json_safe(item) for key, item in value.items()} + if isinstance(value, (list, tuple, set, frozenset)): + return [_json_safe(item) for item in value] + if isinstance(value, (np.integer, np.floating)): + value = value.item() + if isinstance(value, float) and not np.isfinite(value): + return None + return value + + +def _atomic_text(text: str, destination: Path) -> Path: + destination.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + prefix=f".{destination.stem}-", + suffix=destination.suffix, + dir=destination.parent, + delete=False, + ) as handle: + temporary = Path(handle.name) + handle.write(text) + temporary.replace(destination) + return destination + + +def _atomic_json(payload: Mapping[str, Any], destination: Path) -> Path: + return _atomic_text( + json.dumps(_json_safe(payload), indent=2, sort_keys=True, allow_nan=False) + "\n", + destination, + ) + + +def _write_descriptive_artifacts_atomically( + panel: Any, + output_directory: Path, +) -> dict[str, Path]: + """Stage descriptive outputs before atomically promoting each file.""" + + output_directory.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory( + prefix=f".{output_directory.name}-", + dir=output_directory.parent, + ) as temporary_directory: + staged = write_descriptive_artifacts(panel, Path(temporary_directory)) + output_directory.mkdir(parents=True, exist_ok=True) + promoted: dict[str, Path] = {} + for name, staged_path in staged.items(): + destination = output_directory / staged_path.name + staged_path.replace(destination) + promoted[name] = destination + return promoted + + +def _sql_string(value: str) -> str: + return "'" + value.replace("'", "''") + "'" + + +def _portable_path(path: Path, project_root: Path) -> str: + try: + return str(path.resolve().relative_to(project_root.resolve())) + except ValueError: + return str(path.resolve()) + + +def _scan_sql(paths: Sequence[Path]) -> str: + if not paths: + raise FileNotFoundError("expected at least one Parquet file") + rendered = ", ".join(_sql_string(str(path.resolve())) for path in paths) + return f"read_parquet([{rendered}], hive_partitioning=false)" + + +def _row(connection: duckdb.DuckDBPyConnection, query: str) -> dict[str, Any]: + result = connection.execute(query) + values = result.fetchone() + if values is None: + raise RuntimeError("validation query returned no row") + return { + description[0]: value + for description, value in zip(result.description, values, strict=True) + } + + +def _copy_csv( + connection: duckdb.DuckDBPyConnection, + query: str, + destination: Path, +) -> Path: + destination.parent.mkdir(parents=True, exist_ok=True) + temporary = destination.with_name(f".{destination.name}.tmp") + temporary.unlink(missing_ok=True) + try: + connection.execute( + f"COPY ({query}) TO {_sql_string(str(temporary.resolve()))} " + "(FORMAT CSV, HEADER true)" + ) + temporary.replace(destination) + except BaseException: + temporary.unlink(missing_ok=True) + raise + return destination + + +def _manifest_integrity(manifest_path: Path, project_root: Path) -> dict[str, Any]: + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + mismatches: list[str] = [] + for entry in manifest.get("files", []): + path = Path(entry["path"]) + resolved = path if path.is_absolute() else project_root / path + if not resolved.is_file(): + mismatches.append(f"missing:{entry['path']}") + continue + if resolved.stat().st_size != int(entry["bytes"]): + mismatches.append(f"bytes:{entry['path']}") + continue + if sha256_file(resolved) != entry["sha256"]: + mismatches.append(f"sha256:{entry['path']}") + return { + "entries": len(manifest.get("files", [])), + "mismatches": mismatches, + "all_files_valid": not mismatches, + "config_is_full_nyc": ( + manifest.get("config", {}).get("source") == "nyc_hvfhv" + and manifest.get("config", {}).get("mode") == "full" + ), + "causal_claim": manifest.get("metadata", {}).get("causal_claim"), + "sample_selection_present": "sample_selection" + in manifest.get("metadata", {}), + } + + +def _max_rss_bytes() -> int | None: + if resource is None: + return None + raw = int(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) + return raw if platform.system() == "Darwin" else raw * 1024 + + +def write_nyc_full_analysis( + config: DataConfig | str | Path, + output_directory: str | Path, + *, + started_at_monotonic: float | None = None, + raw_cached: bool = True, + command: str | None = None, + resource_overrides: Mapping[str, Any] | None = None, +) -> NYCFullAnalysisArtifacts: + """Validate and summarize one completed full-month NYC pipeline build. + + All trip-level scans stay in DuckDB. Only compact scalar results and CSV + aggregates are materialized in Python. + """ + + cfg = load_data_config(config) if not isinstance(config, DataConfig) else config + if cfg.source != "nyc_hvfhv" or cfg.mode != "full": + raise ValueError("NYC full analysis requires source=nyc_hvfhv and mode=full") + if len(cfg.nyc_months) != 1: + raise ValueError("NYC full analysis currently requires exactly one month") + output = Path(output_directory) + output.mkdir(parents=True, exist_ok=True) + manifest_path = output / "manifest.json" + analysis_incomplete = output / "NYC_FULL_ANALYSIS_INCOMPLETE.json" + manifest_path.unlink(missing_ok=True) + _atomic_json( + { + "status": "incomplete", + "started_at_utc": datetime.now(UTC).isoformat(), + "config": cfg.as_serializable_dict(), + "interpretation": ( + "The NYC full-month analysis outputs must not be treated as a " + "successful run while this marker exists." + ), + }, + analysis_incomplete, + ) + incomplete = cfg.manifest_path.with_name("NYC_FULL_INCOMPLETE.json") + if incomplete.exists(): + raise RuntimeError("NYC full pipeline is marked incomplete") + if not cfg.manifest_path.is_file() or not cfg.diagnostics_path.is_file(): + raise FileNotFoundError("NYC full manifest and diagnostics are required") + + month = cfg.nyc_months[0] + month_start = date(cfg.nyc_year, month, 1) + next_month_start = ( + date(cfg.nyc_year + 1, 1, 1) + if month == 12 + else date(cfg.nyc_year, month + 1, 1) + ) + raw_files = tuple( + cfg.raw_dir / Path(url).name for url in nyc_hvfhv_urls(cfg) + ) + clean_files = tuple(sorted((cfg.clean_dir / "trips").rglob("*.parquet"))) + zone_files = tuple(sorted((cfg.panel_dir / "zone_time").rglob("*.parquet"))) + od_files = tuple(sorted((cfg.panel_dir / "od_flow").rglob("*.parquet"))) + for path in (*raw_files, *clean_files, *zone_files, *od_files): + if not path.is_file(): + raise FileNotFoundError(path) + + parquet = pq.ParquetFile(raw_files[0]) + raw_schema = parquet.schema_arrow + actual_columns = raw_schema.names + required = REQUIRED_RAW_COLUMNS["nyc_hvfhv"] + expected = set(NYC_HVFHV_RAW_SCHEMA) + diagnostics = json.loads(cfg.diagnostics_path.read_text(encoding="utf-8")) + integrity = _manifest_integrity(cfg.manifest_path, cfg.project_root.resolve()) + + connection = duckdb.connect() + connection.execute("SET threads = 1") + connection.execute("SET memory_limit = '1GB'") + connection.execute(f"CREATE TEMP VIEW clean AS SELECT * FROM {_scan_sql(clean_files)}") + connection.execute(f"CREATE TEMP VIEW zone AS SELECT * FROM {_scan_sql(zone_files)}") + connection.execute(f"CREATE TEMP VIEW od AS SELECT * FROM {_scan_sql(od_files)}") + try: + coverage = _row( + connection, + f""" + SELECT + count(*)::BIGINT AS clean_rows, + count(*) FILTER (WHERE pickup_datetime IS NULL)::BIGINT + AS pickup_null_count, + min(pickup_datetime) AS pickup_min, + max(pickup_datetime) AS pickup_max, + count(DISTINCT service_date)::INTEGER AS service_dates, + count(DISTINCT hour(pickup_datetime))::INTEGER AS hours_of_day, + count(DISTINCT date_trunc('hour', pickup_datetime))::INTEGER + AS date_hours, + count(*) FILTER ( + WHERE pickup_datetime < TIMESTAMP '{month_start.isoformat()}' + OR pickup_datetime >= TIMESTAMP '{next_month_start.isoformat()}' + )::BIGINT AS outside_month_count, + count(*) FILTER ( + WHERE dropoff_datetime < pickup_datetime + )::BIGINT AS reverse_timestamp_count, + count(*) FILTER ( + WHERE abs(trip_seconds - date_diff('second', pickup_datetime, + dropoff_datetime)) > 60 + )::BIGINT AS trip_time_delta_mismatch_count, + count(*) FILTER ( + WHERE pickup_zone_id IS NOT NULL AND dropoff_zone_id IS NOT NULL + )::BIGINT AS observed_od_pairs, + count(DISTINCT pickup_zone_id)::INTEGER AS pickup_zones, + count(DISTINCT dropoff_zone_id)::INTEGER AS dropoff_zones + FROM clean + """, + ) + zone_stats = _row( + connection, + """ + SELECT + count(*)::BIGINT AS zone_time_rows, + count(*) FILTER (WHERE trip_count > 0)::BIGINT + AS observed_zone_time_rows, + count(*) FILTER (WHERE trip_count = 0)::BIGINT + AS synthesized_zero_rows, + coalesce(sum(trip_count), 0)::BIGINT AS zone_trip_sum, + coalesce(sum(od_pair_observed_count), 0)::BIGINT + AS zone_observed_od_pair_sum, + count(*) - count(DISTINCT (source, zone_type, zone_id, time_bin)) + AS zone_key_duplicates, + count(DISTINCT zone_id)::INTEGER AS zones, + count(DISTINCT time_bin)::INTEGER AS periods + FROM zone + """, + ) + od_stats = _row( + connection, + """ + SELECT + count(*)::BIGINT AS od_rows, + coalesce(sum(trip_count), 0)::BIGINT AS od_trip_sum, + count(*) - count(DISTINCT ( + source, zone_type, origin_zone_id, destination_zone_id, time_bin + )) AS od_key_duplicates, + count(*) FILTER (WHERE trip_count <= 0)::BIGINT + AS od_nonpositive_rows + FROM od + """, + ) + descriptive = _row( + connection, + """ + SELECT + count(*)::BIGINT AS trip_count, + count(fare)::BIGINT AS fare_known, + avg(fare) AS fare_mean, + median(fare) AS fare_median, + quantile_cont(fare, 0.10) AS fare_p10, + quantile_cont(fare, 0.90) AS fare_p90, + quantile_cont(fare, 0.99) AS fare_p99, + count(*) FILTER (WHERE fare < 0)::BIGINT AS negative_fare, + count(*) FILTER (WHERE fare = 0)::BIGINT AS zero_fare, + count(trip_miles)::BIGINT AS miles_known, + avg(trip_miles) AS miles_mean, + median(trip_miles) AS miles_median, + quantile_cont(trip_miles, 0.90) AS miles_p90, + count(trip_seconds)::BIGINT AS duration_known, + avg(trip_seconds) / 60.0 AS duration_minutes_mean, + median(trip_seconds) / 60.0 AS duration_minutes_median, + quantile_cont(trip_seconds, 0.90) / 60.0 + AS duration_minutes_p90, + count(airport_trip)::BIGINT AS airport_known, + avg(airport_trip::DOUBLE) AS airport_share, + count(shared_requested)::BIGINT AS shared_requested_known, + avg(shared_requested::DOUBLE) AS shared_requested_share, + count(shared_matched)::BIGINT AS shared_matched_known, + avg(shared_matched::DOUBLE) AS shared_matched_share, + avg(shared_matched::DOUBLE) FILTER (WHERE shared_requested) + AS shared_matched_given_requested + FROM clean + """, + ) + + daily_path = _copy_csv( + connection, + """ + SELECT + service_date, + isodow(service_date)::INTEGER AS iso_weekday, + count(*)::BIGINT AS trip_count, + count(*)::DOUBLE / sum(count(*)) OVER () AS month_share, + count(DISTINCT pickup_zone_id)::INTEGER AS active_zones, + avg(fare) AS avg_fare, + avg(airport_trip::DOUBLE) AS airport_share, + avg(shared_requested::DOUBLE) AS shared_requested_share, + avg(shared_matched::DOUBLE) AS shared_matched_share, + 'descriptive_real_data' AS evidence_label + FROM clean + GROUP BY service_date + ORDER BY service_date + """, + output / "daily_summary.csv", + ) + hourly_path = _copy_csv( + connection, + """ + SELECT + hour(pickup_datetime)::INTEGER AS hour, + count(*)::BIGINT AS trip_count, + count(*)::DOUBLE / sum(count(*)) OVER () AS month_share, + count(DISTINCT service_date)::INTEGER AS dates_observed, + count(*)::DOUBLE / count(DISTINCT service_date) + AS mean_trips_per_date, + avg(fare) AS avg_fare, + avg(airport_trip::DOUBLE) AS airport_share, + avg(shared_requested::DOUBLE) AS shared_requested_share, + avg(shared_matched::DOUBLE) AS shared_matched_share, + 'descriptive_real_data' AS evidence_label + FROM clean + GROUP BY hour + ORDER BY hour + """, + output / "hourly_summary.csv", + ) + weekday_path = _copy_csv( + connection, + """ + SELECT + isodow(service_date)::INTEGER AS iso_weekday, + count(DISTINCT service_date)::INTEGER AS dates_in_month, + count(*)::BIGINT AS total_trips, + count(*)::DOUBLE / count(DISTINCT service_date) + AS mean_trips_per_date, + avg(fare) AS avg_fare, + avg(airport_trip::DOUBLE) AS airport_share, + 'descriptive_real_data' AS evidence_label + FROM clean + GROUP BY iso_weekday + ORDER BY iso_weekday + """, + output / "weekday_summary.csv", + ) + zone_path = _copy_csv( + connection, + """ + SELECT + pickup_zone_id AS zone_id, + count(*)::BIGINT AS trip_count, + count(*)::DOUBLE / sum(count(*)) OVER () AS month_share, + count(DISTINCT date_trunc('hour', pickup_datetime))::INTEGER + AS occupied_hours, + avg(fare) AS avg_fare, + avg(trip_miles) AS avg_trip_miles, + avg(airport_trip::DOUBLE) AS airport_share, + 'descriptive_real_data' AS evidence_label + FROM clean + GROUP BY pickup_zone_id + ORDER BY trip_count DESC, zone_id + """, + output / "zone_summary.csv", + ) + od_month_path = _copy_csv( + connection, + """ + SELECT + origin_zone_id, + destination_zone_id, + sum(trip_count)::BIGINT AS trip_count, + sum(avg_fare * trip_count) / sum(trip_count) AS avg_fare, + sum(avg_trip_miles * trip_count) / sum(trip_count) + AS avg_trip_miles, + sum(trip_count)::DOUBLE + / sum(sum(trip_count)) OVER (PARTITION BY origin_zone_id) + AS origin_flow_share, + 'descriptive_real_data' AS evidence_label, + 'Observed flow; not a causal spatial-substitution estimate.' + AS interpretation_warning + FROM od + GROUP BY origin_zone_id, destination_zone_id + ORDER BY origin_zone_id, trip_count DESC, destination_zone_id + """, + output / "od_month_summary.csv", + ) + finally: + connection.close() + + panel = read_partitioned_parquet(cfg.panel_dir / "zone_time") + descriptive_outputs = _write_descriptive_artifacts_atomically( + panel, + output / "marketplace_associations", + ) + panel_associations = json.loads( + descriptive_outputs["moments"].read_text(encoding="utf-8") + ) + + expected_dates = monthrange(cfg.nyc_year, month)[1] + expected_date_hours = expected_dates * 24 + raw_rows = sum(int(pq.ParquetFile(path).metadata.num_rows) for path in raw_files) + raw_bytes = sum(path.stat().st_size for path in raw_files) + max_rss = _max_rss_bytes() + effective_max_rss = int( + (resource_overrides or {}).get("max_rss_bytes", max_rss or 0) + ) + checks = { + "raw_equals_clean": raw_rows == int(coverage["clean_rows"]), + "zone_conserves_clean": int(zone_stats["zone_trip_sum"]) + == int(coverage["clean_rows"]) - int(coverage["pickup_null_count"]), + "od_conserves_clean": int(od_stats["od_trip_sum"]) + == int(coverage["clean_rows"]) - int(coverage["pickup_null_count"]), + "zone_od_coverage_matches_clean": int(zone_stats["zone_observed_od_pair_sum"]) + == int(coverage["observed_od_pairs"]), + "calendar_complete": ( + int(coverage["service_dates"]) == expected_dates + and int(coverage["hours_of_day"]) == 24 + and int(coverage["date_hours"]) == expected_date_hours + and int(coverage["outside_month_count"]) == 0 + ), + "zone_keys_unique": int(zone_stats["zone_key_duplicates"]) == 0, + "od_keys_unique": int(od_stats["od_key_duplicates"]) == 0, + "od_counts_positive": int(od_stats["od_nonpositive_rows"]) == 0, + "complete_zone_grid": ( + not cfg.complete_panel_grid + or int(zone_stats["zone_time_rows"]) + == int(zone_stats["zones"]) * expected_date_hours + ), + "diagnostics_rows_match": int(diagnostics["row_count"]) + == int(coverage["clean_rows"]), + "manifest_files_valid": bool(integrity["all_files_valid"]), + "manifest_scope_valid": bool(integrity["config_is_full_nyc"]) + and integrity["causal_claim"] is False + and not bool(integrity["sample_selection_present"]), + "resource_limit_passed": 0 < effective_max_rss < 16 * 1024**3, + } + resources = { + "command": command, + "raw_cached": raw_cached, + "elapsed_seconds": ( + perf_counter() - started_at_monotonic + if started_at_monotonic is not None + else None + ), + "max_rss_bytes": max_rss, + "memory_limit_bytes": 16 * 1024**3, + "input_bytes": raw_bytes, + "final_data_bytes": sum( + path.stat().st_size + for path in cfg.manifest_path.parent.rglob("*") + if path.is_file() + ), + "exit_status": 0, + } + resources.update(_json_safe(resource_overrides or {})) + validation = { + "evidence_label": "descriptive_real_data", + "causal_claim": False, + "validation_passed": all(checks.values()), + "checks": checks, + "scope": { + "source": "nyc_hvfhv", + "pickup_month": f"{cfg.nyc_year}-{month:02d}", + "unit": "published_completed_trip_record", + "population_claim": False, + }, + "provenance": { + "source_urls": list(nyc_hvfhv_urls(cfg)), + "local_paths": [ + _portable_path(path, cfg.project_root) + for path in raw_files + ], + "sha256": [sha256_file(path) for path in raw_files], + "bytes": raw_bytes, + "parquet_num_rows": raw_rows, + "num_row_groups": sum( + int(pq.ParquetFile(path).metadata.num_row_groups) for path in raw_files + ), + "data_manifest": _portable_path(cfg.manifest_path, cfg.project_root), + "data_manifest_sha256": sha256_file(cfg.manifest_path), + }, + "schema": { + "actual": [ + {"name": field.name, "dtype": str(field.type)} for field in raw_schema + ], + "missing_required": sorted(required - set(actual_columns)), + "missing_optional": sorted(expected - set(actual_columns) - required), + "unexpected": sorted(set(actual_columns) - expected), + }, + "coverage": coverage, + "conservation": {**zone_stats, **od_stats, "raw_rows": raw_rows}, + "quality": { + "diagnostics": diagnostics, + "reverse_timestamp_count": coverage["reverse_timestamp_count"], + "trip_time_delta_mismatch_count": coverage[ + "trip_time_delta_mismatch_count" + ], + }, + "descriptive": { + **descriptive, + "pickup_zones": coverage["pickup_zones"], + "dropoff_zones": coverage["dropoff_zones"], + "airport_definition": ( + "airport_fee > 0 or pickup/dropoff zone in {1, 132, 138}" + ), + }, + "panel_associations": panel_associations, + "manifest_integrity": integrity, + "resources": resources, + "limitations": [ + "Published completed-trip records exclude latent and unserved demand.", + "Observed fare-demand relationships are endogenous associations, not elasticities.", + "Observed OD flows are connections, not causal spatial-substitution effects.", + "No treatment assignment exists in these records; no causal intervention effect is estimated.", + "The complete grid uses zones observed at least once in this published month.", + ], + } + validation_path = _atomic_json(validation, output / "validation.json") + rss_label = f"{effective_max_rss / 1024**3:.3f} GiB" + report = f"""# NYC January 2024 full-month validation + +Evidence label: `descriptive_real_data`; causal claim: **false**. + +- Published trip records: {raw_rows:,} +- Pickup coverage: {coverage['pickup_min']} through {coverage['pickup_max']} +- Complete zone-hour rows: {int(zone_stats['zone_time_rows']):,} + ({int(zone_stats['observed_zone_time_rows']):,} occupied and + {int(zone_stats['synthesized_zero_rows']):,} zero-trip grid cells) +- OD-hour rows: {int(od_stats['od_rows']):,} +- Zone and OD trip-count sums: {int(zone_stats['zone_trip_sum']):,} and {int(od_stats['od_trip_sum']):,} +- Fare mean/median: {float(descriptive['fare_mean']):.4f} / {float(descriptive['fare_median']):.4f} +- Mean distance: {float(descriptive['miles_mean']):.4f} miles +- Mean duration: {float(descriptive['duration_minutes_mean']):.4f} minutes +- Airport-trip share: {float(descriptive['airport_share']):.4%} +- Shared-request / shared-match shares: {float(descriptive['shared_requested_share']):.4%} / {float(descriptive['shared_matched_share']):.4%} +- Exact one-hour zone-demand association: {panel_associations['zone_exact_lag_demand_correlation_association']:.4f} + across {int(panel_associations['zone_exact_lag_support_pairs']):,} adjacent-hour pairs; + this is not a causal persistence parameter. +- Peak RSS: {rss_label} +- Validation passed: **{all(checks.values())}** + +These are descriptive facts about the pinned published object. They are not a +population model of latent demand and do not identify fare elasticity, spatial +substitution, or the effect of any discount or incentive. +""" + report_path = _atomic_text(report, output / "full_month_report.md") + output_files = ( + validation_path, + report_path, + daily_path, + hourly_path, + weekday_path, + zone_path, + od_month_path, + *descriptive_outputs.values(), + cfg.manifest_path, + cfg.diagnostics_path, + ) + manifest_path = write_manifest( + output_files, + manifest_path, + config=cfg, + root=cfg.project_root, + metadata={ + "evidence_label": "descriptive_real_data", + "causal_claim": False, + "validation_passed": all(checks.values()), + "source_data_manifest_sha256": sha256_file(cfg.manifest_path), + }, + ) + if not manifest_path.is_file(): + raise RuntimeError("NYC full analysis completed without a final hash manifest") + analysis_incomplete.unlink(missing_ok=True) + return NYCFullAnalysisArtifacts( + validation_path=validation_path, + report_path=report_path, + daily_path=daily_path, + hourly_path=hourly_path, + weekday_path=weekday_path, + zone_path=zone_path, + od_month_path=od_month_path, + descriptive_paths=tuple(descriptive_outputs.values()), + manifest_path=manifest_path, + ) + + +__all__ = ["NYCFullAnalysisArtifacts", "write_nyc_full_analysis"] diff --git a/CasualLab/src/casuallab/nyc_graph_benchmark.py b/CasualLab/src/casuallab/nyc_graph_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..21278a89650e3db126307efd35da19b4ea7fd235 --- /dev/null +++ b/CasualLab/src/casuallab/nyc_graph_benchmark.py @@ -0,0 +1,1429 @@ +"""Known-truth interference benchmark on a validated NYC OD graph. + +The NYC calibration bundle contributes only a fixed, pre-treatment exposure +geometry. Its completed-trip weights determine relative neighbor weights after +row normalization; they are not estimates of spillover strength. Treatment is +then randomized by a two-stage saturation design and outcomes are generated from +an explicit additive DGP with known controlled own, neighbor, and history slopes. + +Consequently, benchmark recovery is semi-synthetic evidence about an estimator on +NYC-shaped geometry. It is not an empirical estimate of a NYC treatment effect. +""" + +from __future__ import annotations + +import json +import shutil +import tempfile +from collections.abc import Mapping +from dataclasses import asdict, dataclass +from hashlib import sha256 +from math import isfinite +from numbers import Integral, Real +from pathlib import Path +from typing import Any, Final + +import numpy as np +import pandas as pd + +from .benchmark import summarize_monte_carlo +from .config import EstimatorConfig +from .data import sha256_file +from .estimators import cluster_robust +from .interference import ( + ExposureMappingConfig, + TwoStageSaturationConfig, + add_mapped_exposures, + estimate_exposure_response, + two_stage_saturation_assignment, +) + +CALIBRATION_EVIDENCE: Final = "descriptive_real_data" +BENCHMARK_EVIDENCE: Final = "semi_synthetic_known_truth_on_descriptive_nyc_graph" +MAPPING_FILENAME: Final = "exposure_mapping_edges.csv" +CALIBRATION_FILENAME: Final = "calibration.json" +MANIFEST_FILENAME: Final = "manifest.json" +NYC_GRAPH_BENCHMARK_ARTIFACT_SCHEMA_VERSION: Final = "1.0.0" +SELECTION_RULE: Final = ( + "Within a connected component large enough for the requested sample, start at " + "the zone with greatest raw OD weighted degree, then greedily add the zone with " + "greatest raw OD weight to already selected zones; break ties by full-graph " + "weighted degree, neighbor count, and lexical zone ID. Only pre-treatment graph " + "fields are used." +) + +TARGET_DEFINITIONS: Final[Mapping[str, str]] = { + "controlled_zone_direct_effect": ( + "Per-unit own-treatment response holding NYC-graph neighbor exposure and " + "lagged own exposure fixed." + ), + "spillover_effect": ( + "Per-unit response to row-normalized NYC OD-neighbor exposure holding own and " + "lagged exposure fixed; the coefficient is declared by the DGP, not learned " + "from OD weights." + ), + "controlled_history_exposure_response": ( + "Per-unit response to exact-lag own-treatment history holding current own and " + "NYC-graph neighbor exposure fixed." + ), + "market_total_effect": ( + "Full-horizon all-selected-zone treatment versus all-zero under the declared " + "additive DGP and startup-history convention." + ), +} + + +@dataclass(frozen=True, slots=True) +class NYCGraphBenchmarkConfig: + """Laptop-safe Monte Carlo settings for the NYC-geometry benchmark.""" + + replications: int = 12 + seed: int = 912_731 + n_zones: int = 16 + n_periods: int = 24 + individuals_per_cell: int = 20 + saturation_levels: tuple[float, ...] = (0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0) + history_lags: int = 1 + own_effect: float = 2.0 + neighbor_effect: float = 1.5 + history_effect: float = 0.7 + outcome_noise_sd: float = 0.06 + cluster_noise_sd: float = 0.04 + confidence_level: float = 0.95 + minimum_inference_clusters: int = 8 + + def __post_init__(self) -> None: + integer_values = { + "replications": self.replications, + "seed": self.seed, + "n_zones": self.n_zones, + "n_periods": self.n_periods, + "individuals_per_cell": self.individuals_per_cell, + "history_lags": self.history_lags, + "minimum_inference_clusters": self.minimum_inference_clusters, + } + for name, value in integer_values.items(): + if isinstance(value, bool) or not isinstance(value, Integral): + raise ValueError(f"{name} must be an integer") + if self.replications < 2: + raise ValueError("replications must be at least two") + if self.n_zones < 4: + raise ValueError("n_zones must be at least four") + if self.n_periods <= self.history_lags + 1: + raise ValueError("n_periods must leave at least two complete history periods") + if self.individuals_per_cell < 1: + raise ValueError("individuals_per_cell must be positive") + if self.history_lags < 1: + raise ValueError("history_lags must be at least one") + if self.minimum_inference_clusters < 2: + raise ValueError("minimum_inference_clusters must be at least two") + if not 0.5 < self.confidence_level < 1.0: + raise ValueError("confidence_level must lie between 0.5 and 1") + + numeric_values = { + "own_effect": self.own_effect, + "neighbor_effect": self.neighbor_effect, + "history_effect": self.history_effect, + "outcome_noise_sd": self.outcome_noise_sd, + "cluster_noise_sd": self.cluster_noise_sd, + } + for name, value in numeric_values.items(): + if not isinstance(value, Real) or not isfinite(float(value)): + raise ValueError(f"{name} must be a finite number") + if self.outcome_noise_sd < 0 or self.cluster_noise_sd < 0: + raise ValueError("noise standard deviations must be non-negative") + + levels = tuple(float(value) for value in self.saturation_levels) + object.__setattr__(self, "saturation_levels", levels) + TwoStageSaturationConfig( + n_clusters=self.n_zones, + individuals_per_cell=self.individuals_per_cell, + saturation_levels=levels, + seed=self.seed, + ) + if not any(0.0 < level < 1.0 for level in levels): + raise ValueError( + "saturation_levels must include an interior arm to separate current " + "treatment from lagged history" + ) + + +@dataclass(frozen=True, slots=True) +class NYCGraphEstimands: + """Known DGP slopes and the distinct full-policy contrast.""" + + controlled_zone_direct_effect: float + spillover_effect: float + controlled_history_exposure_response: float + full_horizon_history_contribution: float + market_total_effect: float + + def to_dict(self) -> dict[str, float]: + return {name: float(value) for name, value in asdict(self).items()} + + +@dataclass(frozen=True) +class ValidatedNYCGraphBundle: + """Validated fixed graph plus calibration provenance.""" + + directory: Path + edges: pd.DataFrame + manifest: Mapping[str, Any] + calibration: Mapping[str, Any] + manifest_sha256: str + mapping_sha256: str + verified_files: Mapping[str, str] + + +@dataclass(frozen=True) +class NYCGraphBenchmarkResult: + """Replication records, summaries, fit audit, failures, and graph provenance.""" + + records: pd.DataFrame + summary: pd.DataFrame + fit_ledger: pd.DataFrame + failures: pd.DataFrame + metadata: Mapping[str, Any] + + +def _portable_bundle_directory(directory: Path) -> str: + """Record the calibration directory relative to the repository when possible.""" + + resolved = directory.resolve() + candidate_roots = ( + Path(__file__).resolve().parents[2], + Path.cwd().resolve(), + ) + for root in dict.fromkeys(candidate_roots): + try: + relative = resolved.relative_to(root) + except ValueError: + continue + if relative.parts and relative != Path("."): + return relative.as_posix() + # Synthetic fixtures conventionally put the named bundle directly below the + # project_root later supplied to the artifact writer. + return resolved.name + + +def known_nyc_graph_estimands( + config: NYCGraphBenchmarkConfig | None = None, +) -> NYCGraphEstimands: + """Return known truths without reading a calibration bundle.""" + + cfg = config or NYCGraphBenchmarkConfig() + supported_history_periods = cfg.n_periods - cfg.history_lags + history_contribution = ( + cfg.history_effect * supported_history_periods / cfg.n_periods + ) + return NYCGraphEstimands( + controlled_zone_direct_effect=float(cfg.own_effect), + spillover_effect=float(cfg.neighbor_effect), + controlled_history_exposure_response=float(cfg.history_effect), + full_horizon_history_contribution=float(history_contribution), + market_total_effect=float( + cfg.own_effect + cfg.neighbor_effect + history_contribution + ), + ) + + +def _load_json(path: Path, label: str) -> Mapping[str, Any]: + try: + value = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise ValueError(f"invalid {label}: {path}") from exc + if not isinstance(value, Mapping): + raise ValueError(f"{label} must contain a JSON object") + return value + + +def _require_descriptive_header(payload: Mapping[str, Any], label: str) -> None: + if payload.get("schema_version") != "1.0.0": + raise ValueError(f"{label} has unsupported schema_version") + if payload.get("evidence_label") != CALIBRATION_EVIDENCE: + raise ValueError(f"{label} must be labeled descriptive_real_data") + if payload.get("causal_claim") is not False: + raise ValueError(f"{label} must explicitly set causal_claim=false") + + +def _is_sha256(value: Any) -> bool: + return ( + isinstance(value, str) + and len(value) == 64 + and all(character in "0123456789abcdef" for character in value.lower()) + ) + + +def _validate_source_attestation(source: Any, label: str) -> Mapping[str, Any]: + if not isinstance(source, Mapping): + raise ValueError(f"{label} source_data_manifest must be an object") + required_true = ( + "all_valid", + "hashes_recomputed", + "queried_files_listed", + "scope_is_full_nyc_descriptive", + ) + if any(source.get(key) is not True for key in required_true): + raise ValueError(f"{label} source-data attestation is not fully valid") + if source.get("mismatches") != []: + raise ValueError(f"{label} source-data attestation records mismatches") + source_hash = source.get("sha256") + if not _is_sha256(source_hash): + raise ValueError(f"{label} source-data attestation lacks a SHA-256 digest") + if not _is_sha256(source.get("declared_file_set_sha256")): + raise ValueError(f"{label} source-data attestation lacks a file-set digest") + entries = source.get("entries") + if isinstance(entries, bool) or not isinstance(entries, Integral) or entries < 1: + raise ValueError(f"{label} source-data attestation has no declared files") + source_path = source.get("path") + if not isinstance(source_path, str) or not source_path.strip(): + raise ValueError(f"{label} source-data attestation lacks a manifest path") + return source + + +def _validate_manifest_files( + directory: Path, + manifest: Mapping[str, Any], +) -> tuple[dict[str, Path], dict[str, str]]: + entries = manifest.get("files") + if not isinstance(entries, list) or not entries: + raise ValueError("calibration manifest files must be a nonempty list") + paths: dict[str, Path] = {} + hashes: dict[str, str] = {} + for entry in entries: + if not isinstance(entry, Mapping): + raise ValueError("calibration manifest contains a malformed file entry") + name = entry.get("path") + if not isinstance(name, str) or Path(name).name != name or Path(name).is_absolute(): + raise ValueError("calibration manifest file paths must be portable basenames") + if name == MANIFEST_FILENAME or name in paths: + raise ValueError("calibration manifest contains a duplicate or recursive path") + path = directory / name + if path.is_symlink() or not path.is_file(): + raise ValueError(f"calibration bundle file is missing or unsafe: {name}") + declared_bytes = entry.get("bytes") + declared_hash = entry.get("sha256") + if ( + isinstance(declared_bytes, bool) + or not isinstance(declared_bytes, Integral) + or int(declared_bytes) < 0 + ): + raise ValueError(f"calibration manifest has invalid bytes for {name}") + if not _is_sha256(declared_hash): + raise ValueError(f"calibration manifest has invalid SHA-256 for {name}") + if path.stat().st_size != int(declared_bytes): + raise ValueError(f"calibration bundle byte-size mismatch: {name}") + actual_hash = sha256_file(path) + if actual_hash != declared_hash: + raise ValueError(f"calibration bundle SHA-256 mismatch: {name}") + paths[name] = path + hashes[name] = actual_hash + + actual_files = { + path.name + for path in directory.iterdir() + if path.is_file() and path.name != MANIFEST_FILENAME + } + if actual_files != set(paths): + raise ValueError("calibration bundle file set differs from its manifest") + return paths, hashes + + +def _validate_mapping(path: Path) -> pd.DataFrame: + required = { + "focal_zone_id", + "neighbor_zone_id", + "weight", + "evidence_label", + "weight_definition", + "interpretation_warning", + } + try: + frame = pd.read_csv( + path, + dtype={"focal_zone_id": "string", "neighbor_zone_id": "string"}, + ) + except (OSError, ValueError, pd.errors.ParserError) as exc: + raise ValueError("invalid NYC exposure mapping CSV") from exc + missing = required.difference(frame.columns) + if missing: + raise ValueError(f"NYC exposure mapping missing columns: {sorted(missing)}") + if frame.empty: + raise ValueError("NYC exposure mapping must not be empty") + if frame[list(required)].isna().any().any(): + raise ValueError("NYC exposure mapping contains missing required values") + frame["focal_zone_id"] = frame["focal_zone_id"].astype(str) + frame["neighbor_zone_id"] = frame["neighbor_zone_id"].astype(str) + if (frame["focal_zone_id"].str.strip() == "").any() or ( + frame["neighbor_zone_id"].str.strip() == "" + ).any(): + raise ValueError("NYC exposure mapping contains blank zone IDs") + if frame.duplicated(["focal_zone_id", "neighbor_zone_id"]).any(): + raise ValueError("NYC exposure mapping contains duplicate directed edges") + if (frame["focal_zone_id"] == frame["neighbor_zone_id"]).any(): + raise ValueError("NYC exposure mapping must not contain self edges") + weights = pd.to_numeric(frame["weight"], errors="coerce") + if weights.isna().any() or not np.isfinite(weights.to_numpy(dtype=float)).all(): + raise ValueError("NYC exposure mapping weights must be finite numeric values") + if (weights <= 0).any(): + raise ValueError("NYC exposure mapping weights must be strictly positive") + frame["weight"] = weights.astype(float) + if not frame["evidence_label"].eq(CALIBRATION_EVIDENCE).all(): + raise ValueError("NYC exposure mapping evidence labels are not descriptive_real_data") + if not frame["weight_definition"].str.contains( + "row-normalizes weight", case=False, regex=False + ).all(): + raise ValueError("NYC exposure mapping lacks its row-normalization definition") + if not frame["interpretation_warning"].str.contains( + "not an estimated spillover effect", case=False, regex=False + ).all(): + raise ValueError("NYC graph weights are not explicitly separated from spillover effects") + + indexed = frame.set_index(["focal_zone_id", "neighbor_zone_id"])["weight"] + reverse_index = pd.MultiIndex.from_arrays( + [frame["neighbor_zone_id"], frame["focal_zone_id"]], + names=["focal_zone_id", "neighbor_zone_id"], + ) + reverse = indexed.reindex(reverse_index) + if reverse.isna().any() or not np.allclose( + frame["weight"].to_numpy(dtype=float), + reverse.to_numpy(dtype=float), + rtol=0.0, + atol=1e-12, + ): + raise ValueError("NYC exposure mapping must be symmetric with equal reverse weights") + return frame.sort_values( + ["focal_zone_id", "neighbor_zone_id"] + ).reset_index(drop=True) + + +def validate_nyc_graph_bundle( + bundle_directory: str | Path, +) -> ValidatedNYCGraphBundle: + """Fail closed unless every calibration artifact and evidence contract validates.""" + + directory = Path(bundle_directory).resolve() + if not directory.is_dir(): + raise FileNotFoundError(directory) + manifest_path = directory / MANIFEST_FILENAME + if manifest_path.is_symlink() or not manifest_path.is_file(): + raise FileNotFoundError(manifest_path) + manifest = _load_json(manifest_path, "calibration manifest") + _require_descriptive_header(manifest, "calibration manifest") + if manifest.get("portable_paths") is not True: + raise ValueError("calibration manifest must declare portable_paths=true") + manifest_config = manifest.get("config") + if not isinstance(manifest_config, Mapping): + raise ValueError("calibration manifest lacks its generating configuration") + data_config = manifest_config.get("data") + calibration_config = manifest_config.get("calibration") + if ( + not isinstance(data_config, Mapping) + or data_config.get("source") != "nyc_hvfhv" + or data_config.get("mode") != "full" + ): + raise ValueError("calibration manifest is not scoped to full-mode NYC HVFHV data") + if not isinstance(calibration_config, Mapping) or ( + calibration_config.get("verify_source_hashes") is not True + ): + raise ValueError("calibration manifest did not require source hash verification") + warning = manifest.get("interpretation_warning") + if not isinstance(warning, str) or "do not identify" not in warning: + raise ValueError("calibration manifest lacks its causal interpretation warning") + manifest_source = _validate_source_attestation( + manifest.get("source_data_manifest"), "calibration manifest" + ) + paths, hashes = _validate_manifest_files(directory, manifest) + if {CALIBRATION_FILENAME, MAPPING_FILENAME}.difference(paths): + raise ValueError("calibration manifest omits required graph benchmark inputs") + + calibration = _load_json(paths[CALIBRATION_FILENAME], "calibration payload") + _require_descriptive_header(calibration, "calibration payload") + if calibration.get("bundle_valid") is not True: + raise ValueError("calibration payload does not declare bundle_valid=true") + scope = calibration.get("scope") + if ( + not isinstance(scope, Mapping) + or scope.get("source") != "nyc_hvfhv" + or scope.get("population_claim") is not False + ): + raise ValueError("calibration payload is not a descriptive NYC HVFHV scope") + checks = calibration.get("checks") + if not isinstance(checks, Mapping) or not checks or any( + value is not True for value in checks.values() + ): + raise ValueError("calibration payload contains failed conservation checks") + critical_warning = calibration.get("critical_warning") + if not isinstance(critical_warning, str) or "do not identify" not in critical_warning: + raise ValueError("calibration payload lacks its causal interpretation warning") + provenance = calibration.get("provenance") + if not isinstance(provenance, Mapping): + raise ValueError("calibration payload lacks provenance") + calibration_source = _validate_source_attestation( + provenance.get("source_data_manifest"), "calibration payload" + ) + if dict(calibration_source) != dict(manifest_source): + raise ValueError("manifest and calibration source attestations disagree") + + graph = calibration.get("od_flow_graph") + if not isinstance(graph, Mapping): + raise ValueError("calibration payload lacks od_flow_graph metadata") + if graph.get("evidence_label") != CALIBRATION_EVIDENCE: + raise ValueError("OD graph metadata is not labeled descriptive_real_data") + if graph.get("exposure_mapping_file") != MAPPING_FILENAME: + raise ValueError("OD graph points to an unexpected exposure mapping file") + if graph.get("exposure_mapping_schema") != [ + "focal_zone_id", + "neighbor_zone_id", + "weight", + ]: + raise ValueError("OD graph exposure mapping schema is incompatible") + interpretation = graph.get("interpretation") + if not isinstance(interpretation, str) or ( + "do not estimate interference" not in interpretation + ): + raise ValueError("OD graph metadata does not separate weights from interference") + + edges = _validate_mapping(paths[MAPPING_FILENAME]) + return ValidatedNYCGraphBundle( + directory=directory, + edges=edges, + manifest=manifest, + calibration=calibration, + manifest_sha256=sha256_file(manifest_path), + mapping_sha256=hashes[MAPPING_FILENAME], + verified_files=hashes, + ) + + +def _selected_graph( + edges: pd.DataFrame, + n_zones: int, +) -> tuple[pd.DataFrame, list[str], dict[str, Any], dict[str, float]]: + nodes = sorted( + set(edges["focal_zone_id"]).union(edges["neighbor_zone_id"]) + ) + weighted_degree = edges.groupby("focal_zone_id")["weight"].sum().to_dict() + neighbor_count = edges.groupby("focal_zone_id")["neighbor_zone_id"].nunique().to_dict() + adjacency: dict[str, dict[str, float]] = {node: {} for node in nodes} + for row in edges.itertuples(index=False): + adjacency[str(row.focal_zone_id)][str(row.neighbor_zone_id)] = float(row.weight) + + components: list[list[str]] = [] + unvisited = set(nodes) + while unvisited: + start = min(unvisited) + stack = [start] + component: list[str] = [] + unvisited.remove(start) + while stack: + node = stack.pop() + component.append(node) + unseen_neighbors = sorted(set(adjacency[node]).intersection(unvisited), reverse=True) + for neighbor in unseen_neighbors: + unvisited.remove(neighbor) + stack.append(neighbor) + components.append(sorted(component)) + eligible = [component for component in components if len(component) >= n_zones] + if not eligible: + largest = max((len(component) for component in components), default=0) + raise ValueError( + f"NYC graph has no connected component with {n_zones} zones; largest has {largest}" + ) + component = min( + eligible, + key=lambda values: ( + -sum(float(weighted_degree[node]) for node in values), + -len(values), + values[0], + ), + ) + first = min( + component, + key=lambda node: ( + -float(weighted_degree[node]), + -int(neighbor_count[node]), + node, + ), + ) + selected = [first] + selected_set = {first} + while len(selected) < n_zones: + candidates = set(component).difference(selected_set) + connected_candidates = [ + node + for node in candidates + if any(neighbor in selected_set for neighbor in adjacency[node]) + ] + if not connected_candidates: + raise RuntimeError("connected-zone selector lost graph support") + chosen = min( + connected_candidates, + key=lambda node: ( + -sum( + weight + for neighbor, weight in adjacency[node].items() + if neighbor in selected_set + ), + -float(weighted_degree[node]), + -int(neighbor_count[node]), + node, + ), + ) + selected.append(chosen) + selected_set.add(chosen) + + subset = edges.loc[ + edges["focal_zone_id"].isin(selected_set) + & edges["neighbor_zone_id"].isin(selected_set), + ["focal_zone_id", "neighbor_zone_id", "weight"], + ].copy() + if subset.empty or set(subset["focal_zone_id"]) != selected_set: + raise RuntimeError("selected NYC graph does not map every focal zone") + canonical = [ + { + "focal_zone_id": str(row.focal_zone_id), + "neighbor_zone_id": str(row.neighbor_zone_id), + "weight": format(float(row.weight), ".17g"), + } + for row in subset.sort_values( + ["focal_zone_id", "neighbor_zone_id"] + ).itertuples(index=False) + ] + subset_digest = sha256( + json.dumps(canonical, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + log_degree = np.log1p( + np.asarray([float(weighted_degree[node]) for node in selected], dtype=float) + ) + scale = float(log_degree.std(ddof=0)) + graph_score_values = ( + np.zeros_like(log_degree) + if scale == 0 + else (log_degree - float(log_degree.mean())) / scale + ) + graph_score = dict(zip(selected, graph_score_values.tolist(), strict=True)) + possible_directed_edges = n_zones * (n_zones - 1) + metadata = { + "selection_rule": SELECTION_RULE, + "selection_uses_only_pre_treatment_graph_fields": True, + "selected_zone_ids_in_order": selected, + "selected_zone_count": len(selected), + "selected_directed_edges": int(len(subset)), + "selected_directed_density": float(len(subset) / possible_directed_edges), + "subset_raw_mapping_sha256": subset_digest, + "subset_weight_handling": ( + "Raw completed-trip weights are restricted to the selected induced graph and " + "row-normalized by add_mapped_exposures." + ), + "selection_scores": [ + { + "zone_id": node, + "full_graph_raw_weighted_degree": float(weighted_degree[node]), + "full_graph_neighbor_count": int(neighbor_count[node]), + } + for node in selected + ], + } + return subset.reset_index(drop=True), selected, metadata, graph_score + + +def _replication_seeds(seed: int, replications: int) -> tuple[tuple[int, int], ...]: + children = np.random.SeedSequence(seed).spawn(replications) + return tuple( + tuple(int(value) for value in child.generate_state(2, dtype=np.uint32)) + for child in children + ) + + +def _simulate( + config: NYCGraphBenchmarkConfig, + edges: pd.DataFrame, + selected_zones: list[str], + graph_score: Mapping[str, float], + *, + assignment_seed: int, + outcome_seed: int, +) -> pd.DataFrame: + units = pd.MultiIndex.from_product( + [range(config.n_periods), selected_zones], + names=["period_id", "zone_id"], + ).to_frame(index=False) + assignment = two_stage_saturation_assignment( + units, + TwoStageSaturationConfig( + n_clusters=config.n_zones, + individuals_per_cell=config.individuals_per_cell, + saturation_levels=config.saturation_levels, + seed=assignment_seed, + ), + ) + frame = add_mapped_exposures( + assignment, + edges, + history_lags=config.history_lags, + ) + frame["graph_baseline_score"] = frame["zone_id"].map(graph_score).astype(float) + period_angle = ( + 2.0 * np.pi * frame["period_id"].to_numpy(dtype=float) / config.n_periods + ) + frame["period_sin"] = np.sin(period_angle) + frame["period_cos"] = np.cos(period_angle) + rng = np.random.default_rng(outcome_seed) + cluster_shocks = rng.normal(0.0, config.cluster_noise_sd, config.n_zones) + history_for_outcome = frame["history_exposure"].fillna(0.0).to_numpy(dtype=float) + frame["outcome"] = ( + 8.0 + + 0.30 * frame["graph_baseline_score"].to_numpy(dtype=float) + + 0.20 * frame["period_sin"].to_numpy(dtype=float) + - 0.15 * frame["period_cos"].to_numpy(dtype=float) + + cluster_shocks[frame["cluster_id"].to_numpy(dtype=int)] + + config.own_effect * frame["treatment"].to_numpy(dtype=float) + + config.neighbor_effect * frame["neighbor_exposure"].to_numpy(dtype=float) + + config.history_effect * history_for_outcome + + rng.normal(0.0, config.outcome_noise_sd, len(frame)) + ) + frame["dgp_evidence_type"] = BENCHMARK_EVIDENCE + return frame + + +def _mapped_records( + frame: pd.DataFrame, + config: NYCGraphBenchmarkConfig, + truths: NYCGraphEstimands, + *, + replication: int, + assignment_seed: int, + outcome_seed: int, +) -> list[dict[str, Any]]: + estimates = estimate_exposure_response( + frame, + ExposureMappingConfig( + outcome="outcome", + own_exposure="treatment", + neighbor_exposure="neighbor_exposure", + history_exposure="history_exposure", + cluster="randomization_cluster", + covariates=("graph_baseline_score", "period_sin", "period_cos"), + alpha=1.0 - config.confidence_level, + minimum_inference_clusters=config.minimum_inference_clusters, + ), + ) + truth_values = truths.to_dict() + records: list[dict[str, Any]] = [] + for estimate in estimates.to_dict("records"): + target = str(estimate["target_estimand"]) + truth = truth_values[target] + records.append( + { + **estimate, + "design": "two_stage_saturation_on_fixed_nyc_od_graph", + "estimator": "nyc_graph_exposure_mapped_cluster_regression", + "replication": replication, + "seed": assignment_seed, + "assignment_seed": assignment_seed, + "outcome_seed": outcome_seed, + "std_error": float(estimate["standard_error"]), + "truth": truth, + "market_total_truth": truths.market_total_effect, + "estimation_error": float(estimate["estimate"]) - truth, + "diagnostic_gap_to_market_total": np.nan, + "identified": True, + "comparison_status": "identified_controlled_exposure_response", + "inference_valid_for_target": bool(estimate["inference_valid"]), + "coefficient_inference_cluster_aware": True, + "controlled_exposure_not_market_total": True, + "graph_weight_is_spillover_strength": False, + "fit_status": "ok", + "design_cost": float(config.n_zones * config.n_periods), + "evidence_type": BENCHMARK_EVIDENCE, + "input_graph_evidence_label": CALIBRATION_EVIDENCE, + "estimand_definition": TARGET_DEFINITIONS[target], + } + ) + return records + + +def _naive_record( + frame: pd.DataFrame, + config: NYCGraphBenchmarkConfig, + truths: NYCGraphEstimands, + *, + replication: int, + assignment_seed: int, + outcome_seed: int, +) -> dict[str, Any]: + estimate = cluster_robust( + frame, + EstimatorConfig( + method="cluster_robust", + outcome="outcome", + treatment="cluster_saturation", + covariates=("graph_baseline_score", "period_sin", "period_cos"), + cluster="randomization_cluster", + target_estimand="market_total_effect", + alpha=1.0 - config.confidence_level, + ), + ) + return { + "method": "cluster_robust", + "exposure_term": "cluster_saturation", + "target_estimand": "market_total_effect", + "coefficient_estimand": "stage_one_saturation_assignment_slope", + "design": "two_stage_saturation_on_fixed_nyc_od_graph", + "estimator": "nyc_graph_naive_assignment_cluster_regression", + "replication": replication, + "seed": assignment_seed, + "assignment_seed": assignment_seed, + "outcome_seed": outcome_seed, + "estimate": estimate.estimate, + "standard_error": estimate.standard_error, + "std_error": estimate.standard_error, + "ci_low": estimate.ci_low, + "ci_high": estimate.ci_high, + "p_value": estimate.p_value, + "n_obs": estimate.n_obs, + "n_clusters": int(estimate.diagnostics["n_clusters"]), + "truth": truths.market_total_effect, + "market_total_truth": truths.market_total_effect, + "estimation_error": np.nan, + "diagnostic_gap_to_market_total": estimate.estimate - truths.market_total_effect, + "identified": False, + "comparison_status": "target_mismatch", + "inference_valid": int(estimate.diagnostics["n_clusters"]) + >= config.minimum_inference_clusters, + "inference_valid_for_target": False, + "coefficient_inference_cluster_aware": True, + "controlled_exposure_not_market_total": False, + "graph_weight_is_spillover_strength": False, + "fit_status": "ok", + "design_cost": float(config.n_zones * config.n_periods), + "effect_scale": "stage-one saturation coefficient; not full-policy market total", + "identification_scope": ( + "Randomization identifies an assignment-saturation contrast. Omitted NYC-graph " + "neighbor exposure and history prevent relabeling it market_total_effect." + ), + "evidence_type": "semi_synthetic_nyc_graph_target_mismatch_diagnostic", + "input_graph_evidence_label": CALIBRATION_EVIDENCE, + "estimand_definition": TARGET_DEFINITIONS["market_total_effect"], + } + + +def _fit_ledger( + records: pd.DataFrame, + failures: pd.DataFrame, + config: NYCGraphBenchmarkConfig, +) -> pd.DataFrame: + plans = [ + { + "estimator": "nyc_graph_exposure_mapped_cluster_regression", + "target_estimand": target, + "identified": True, + "comparison_status": "identified_controlled_exposure_response", + } + for target in ( + "controlled_zone_direct_effect", + "spillover_effect", + "controlled_history_exposure_response", + ) + ] + plans.append( + { + "estimator": "nyc_graph_naive_assignment_cluster_regression", + "target_estimand": "market_total_effect", + "identified": False, + "comparison_status": "target_mismatch", + } + ) + ledger = pd.DataFrame(plans) + keys = ["estimator", "target_estimand"] + successful = ( + records.loc[records["fit_status"].eq("ok")] + .groupby(keys) + .size() + .rename("successful_fits") + .reset_index() + ) + ledger = ledger.merge(successful, on=keys, how="left", validate="one_to_one") + ledger["attempted_fits"] = int(config.replications) + ledger["successful_fits"] = ledger["successful_fits"].fillna(0).astype(int) + ledger["failed_fits"] = ledger["attempted_fits"] - ledger["successful_fits"] + ledger["fit_complete"] = ledger["failed_fits"].eq(0) + inference = ( + records.groupby(keys)["inference_valid_for_target"] + .mean() + .rename("target_inference_valid_rate") + .reset_index() + ) + ledger = ledger.merge(inference, on=keys, how="left", validate="one_to_one") + ledger["target_inference_valid_rate"] = ledger[ + "target_inference_valid_rate" + ].fillna(0.0) + ledger["decision_eligible"] = ( + ledger["identified"] + & ledger["fit_complete"] + & ledger["target_inference_valid_rate"].eq(1.0) + ) + ledger["recorded_failure_rows"] = int(len(failures)) + ledger["evidence_type"] = "semi_synthetic_nyc_graph_fit_ledger" + return ledger.sort_values(keys).reset_index(drop=True) + + +def _summary( + records: pd.DataFrame, + ledger: pd.DataFrame, + config: NYCGraphBenchmarkConfig, + truths: NYCGraphEstimands, +) -> pd.DataFrame: + mapped = records.loc[records["identified"] & records["fit_status"].eq("ok")].copy() + if mapped.empty: + mapped_summary = pd.DataFrame() + else: + mapped_summary = summarize_monte_carlo( + mapped, + confidence_level=config.confidence_level, + group_columns=["design", "estimator", "target_estimand"], + ) + mapped_summary["identified"] = True + mapped_summary["comparison_status"] = "identified_controlled_exposure_response" + mapped_summary["market_total_truth"] = truths.market_total_effect + mapped_summary["controlled_exposure_not_market_total"] = True + mapped_summary["graph_weight_is_spillover_strength"] = False + mapped_summary["diagnostic_mean_gap_to_market_total"] = np.nan + mapped_summary["diagnostic_gap_mcse"] = np.nan + mapped_summary["evidence_type"] = ( + "semi_synthetic_nyc_graph_known_truth_monte_carlo" + ) + inference = ( + mapped.groupby(["design", "estimator", "target_estimand"])[ + "inference_valid_for_target" + ] + .all() + .rename("inference_valid_for_target") + .reset_index() + ) + mapped_summary = mapped_summary.merge( + inference, + on=["design", "estimator", "target_estimand"], + how="left", + validate="one_to_one", + ) + invalid = ~mapped_summary["inference_valid_for_target"].astype(bool) + mapped_summary.loc[ + invalid, ["coverage", "coverage_mcse", "power", "power_mcse"] + ] = np.nan + mapped_summary["withheld_reason"] = np.where( + invalid, + "cluster count is below the predeclared inference minimum", + None, + ) + + naive = records.loc[ + records["estimator"].eq("nyc_graph_naive_assignment_cluster_regression") + & records["fit_status"].eq("ok") + ].copy() + if naive.empty: + naive_summary = pd.DataFrame() + else: + diagnostic = naive["diagnostic_gap_to_market_total"].astype(float) + naive_summary = pd.DataFrame( + [ + { + "design": "two_stage_saturation_on_fixed_nyc_od_graph", + "estimator": "nyc_graph_naive_assignment_cluster_regression", + "target_estimand": "market_total_effect", + "truth": truths.market_total_effect, + "mean_estimate": float(naive["estimate"].mean()), + "bias": np.nan, + "bias_mcse": np.nan, + "variance": float(naive["estimate"].var(ddof=1)), + "rmse": np.nan, + "rmse_mcse": np.nan, + "coverage": np.nan, + "coverage_mcse": np.nan, + "power": np.nan, + "power_mcse": np.nan, + "mean_std_error": float(naive["std_error"].mean()), + "replications": int(len(naive)), + "mean_design_cost": float(naive["design_cost"].mean()), + "information_cost": np.nan, + "confidence_level": config.confidence_level, + "identified": False, + "comparison_status": "target_mismatch", + "market_total_truth": truths.market_total_effect, + "controlled_exposure_not_market_total": False, + "graph_weight_is_spillover_strength": False, + "diagnostic_mean_gap_to_market_total": float(diagnostic.mean()), + "diagnostic_gap_mcse": float( + diagnostic.std(ddof=1) / np.sqrt(len(diagnostic)) + ), + "inference_valid_for_target": False, + "withheld_reason": ( + "The assignment coefficient omits mapped NYC-graph neighbor and " + "history exposure; market-total bias, RMSE, coverage, and power " + "are withheld." + ), + "evidence_type": ( + "semi_synthetic_nyc_graph_target_mismatch_diagnostic" + ), + } + ] + ) + summary = pd.concat([mapped_summary, naive_summary], ignore_index=True, sort=False) + fit_columns = [ + "estimator", + "target_estimand", + "fit_complete", + "successful_fits", + "failed_fits", + "decision_eligible", + ] + summary = summary.merge( + ledger[fit_columns], + on=["estimator", "target_estimand"], + how="left", + validate="one_to_one", + ) + return summary.sort_values( + ["identified", "target_estimand"], ascending=[False, True] + ).reset_index(drop=True) + + +def run_nyc_graph_benchmark( + bundle_directory: str | Path, + config: NYCGraphBenchmarkConfig | None = None, +) -> NYCGraphBenchmarkResult: + """Validate a calibration bundle and run the known-truth NYC-graph benchmark.""" + + cfg = config or NYCGraphBenchmarkConfig() + bundle = validate_nyc_graph_bundle(bundle_directory) + edges, selected_zones, selection_metadata, graph_score = _selected_graph( + bundle.edges, cfg.n_zones + ) + truths = known_nyc_graph_estimands(cfg) + records: list[dict[str, Any]] = [] + failures: list[dict[str, Any]] = [] + for replication, seed_pair in enumerate(_replication_seeds(cfg.seed, cfg.replications)): + assignment_seed, outcome_seed = seed_pair + frame = _simulate( + cfg, + edges, + selected_zones, + graph_score, + assignment_seed=assignment_seed, + outcome_seed=outcome_seed, + ) + try: + records.extend( + _mapped_records( + frame, + cfg, + truths, + replication=replication, + assignment_seed=assignment_seed, + outcome_seed=outcome_seed, + ) + ) + except (ValueError, np.linalg.LinAlgError) as exc: + for target in ( + "controlled_zone_direct_effect", + "spillover_effect", + "controlled_history_exposure_response", + ): + failures.append( + { + "replication": replication, + "assignment_seed": assignment_seed, + "outcome_seed": outcome_seed, + "estimator": "nyc_graph_exposure_mapped_cluster_regression", + "target_estimand": target, + "stage": "estimation", + "error": str(exc), + } + ) + try: + records.append( + _naive_record( + frame, + cfg, + truths, + replication=replication, + assignment_seed=assignment_seed, + outcome_seed=outcome_seed, + ) + ) + except (ValueError, np.linalg.LinAlgError) as exc: + failures.append( + { + "replication": replication, + "assignment_seed": assignment_seed, + "outcome_seed": outcome_seed, + "estimator": "nyc_graph_naive_assignment_cluster_regression", + "target_estimand": "market_total_effect", + "stage": "estimation", + "error": str(exc), + } + ) + + record_frame = pd.DataFrame(records) + if record_frame.empty: + raise RuntimeError("NYC graph benchmark produced no successful fits") + failure_frame = pd.DataFrame( + failures, + columns=[ + "replication", + "assignment_seed", + "outcome_seed", + "estimator", + "target_estimand", + "stage", + "error", + ], + ) + ledger = _fit_ledger(record_frame, failure_frame, cfg) + summary = _summary(record_frame, ledger, cfg, truths) + metadata: dict[str, Any] = { + "evidence_type": BENCHMARK_EVIDENCE, + "causal_claim_from_nyc_data": False, + "input_graph_evidence_label": CALIBRATION_EVIDENCE, + "config": asdict(cfg), + "known_estimands": truths.to_dict(), + "estimand_definitions": dict(TARGET_DEFINITIONS), + "calibration_bundle": { + "directory_name": _portable_bundle_directory(bundle.directory), + "manifest_sha256": bundle.manifest_sha256, + "exposure_mapping_sha256": bundle.mapping_sha256, + "verified_file_sha256": dict(bundle.verified_files), + "manifest_source_data_attestation": dict( + bundle.manifest["source_data_manifest"] + ), + }, + "zone_subset": selection_metadata, + "assignment_design": ( + "one randomized geographic cluster per selected zone; balanced saturation " + "arms followed by within-zone-period binomial opportunity assignment" + ), + "graph_weight_role": ( + "Completed-trip OD weights define relative neighbor exposure geometry only. " + "They are row-normalized and are not spillover strength, a causal effect, " + "substitution, mobility, or equilibrium response." + ), + "history_mapping": f"mean of {cfg.history_lags} exact own-treatment lag(s)", + "market_total_bridge": ( + "Known only because the benchmark declares an additive DGP. Controlled " + "exposure slopes remain separate from market_total_effect." + ), + "naive_assignment_status": ( + "target mismatch; cluster-aware coefficient uncertainty does not justify " + "market-total bias, RMSE, coverage, or power" + ), + } + return NYCGraphBenchmarkResult( + records=record_frame.sort_values( + ["replication", "estimator", "target_estimand"] + ).reset_index(drop=True), + summary=summary, + fit_ledger=ledger, + failures=failure_frame, + metadata=metadata, + ) + + +def _artifact_json_safe(value: Any) -> Any: + if isinstance(value, Path): + return str(value) + if isinstance(value, Mapping): + return {str(key): _artifact_json_safe(item) for key, item in value.items()} + if isinstance(value, (list, tuple, set, frozenset)): + return [_artifact_json_safe(item) for item in value] + if isinstance(value, (np.integer, np.floating, np.bool_)): + return value.item() + if hasattr(value, "value"): + return _artifact_json_safe(value.value) + return value + + +def _artifact_output_path( + output_dir: str | Path, + project_root: str | Path | None, +) -> tuple[Path, str]: + root = ( + Path(project_root).resolve() + if project_root is not None + else Path.cwd().resolve() + ) + raw = Path(output_dir) + output = ((root / raw) if not raw.is_absolute() else raw).resolve() + if output.parent == output: + raise ValueError("artifact output_dir must not be a filesystem root") + if output == Path.cwd().resolve(): + raise ValueError("artifact output_dir must not overwrite the current workspace") + if output == root: + raise ValueError("artifact output_dir must not overwrite project_root") + try: + portable = output.relative_to(root).as_posix() + except ValueError as exc: + raise ValueError("artifact output_dir must be contained by project_root") from exc + if output.exists() and not output.is_dir(): + raise ValueError("artifact output_dir exists and is not a directory") + return output, portable + + +def _artifact_project_root(project_root: str | Path | None) -> Path: + return ( + Path(project_root).resolve() + if project_root is not None + else Path.cwd().resolve() + ) + + +def _artifact_portable_input_path(value: Any, label: str) -> Path: + if not isinstance(value, str) or not value: + raise ValueError(f"{label} must be a nonempty path string") + path = Path(value) + if path.is_absolute() or ".." in path.parts or path == Path("."): + raise ValueError(f"{label} must be project-relative and portable") + return path + + +def _artifact_input_entry( + path: Path, + *, + project_root: Path, + expected_sha256: Any, + role: str, + media_type: str, +) -> dict[str, Any]: + if not _is_sha256(expected_sha256): + raise ValueError(f"{role} declared SHA-256 is invalid") + resolved = path.resolve() + try: + portable = resolved.relative_to(project_root).as_posix() + except ValueError as exc: + raise ValueError(f"{role} must be contained by project_root") from exc + if not resolved.is_file(): + raise FileNotFoundError(f"{role} is required: {resolved}") + actual = sha256_file(resolved) + if actual != expected_sha256: + raise ValueError(f"{role} SHA-256 disagrees with result metadata") + return { + "path": portable, + "role": role, + "media_type": media_type, + "bytes": resolved.stat().st_size, + "sha256": actual, + "evidence_types": [CALIBRATION_EVIDENCE], + } + + +def _artifact_calibration_inputs( + metadata: Mapping[str, Any], project_root: Path +) -> list[dict[str, Any]]: + calibration = metadata.get("calibration_bundle") + if not isinstance(calibration, Mapping): + raise ValueError("result metadata lacks calibration_bundle provenance") + relative_directory = _artifact_portable_input_path( + calibration.get("directory_name"), + "result metadata calibration_bundle.directory_name", + ) + directory = (project_root / relative_directory).resolve() + try: + directory.relative_to(project_root) + except ValueError as exc: + raise ValueError("calibration bundle must be contained by project_root") from exc + + reverified = validate_nyc_graph_bundle(directory) + expected_manifest = calibration.get("manifest_sha256") + expected_mapping = calibration.get("exposure_mapping_sha256") + if ( + reverified.manifest_sha256 != expected_manifest + or reverified.mapping_sha256 != expected_mapping + ): + raise ValueError("revalidated calibration hashes disagree with result metadata") + declared_files = calibration.get("verified_file_sha256") + if not isinstance(declared_files, Mapping) or dict( + reverified.verified_files + ) != dict(declared_files): + raise ValueError("revalidated calibration file set disagrees with result metadata") + + return [ + _artifact_input_entry( + directory / MANIFEST_FILENAME, + project_root=project_root, + expected_sha256=expected_manifest, + role="calibration_manifest", + media_type="application/json", + ), + _artifact_input_entry( + directory / MAPPING_FILENAME, + project_root=project_root, + expected_sha256=expected_mapping, + role="exposure_mapping", + media_type="text/csv", + ), + ] + + +def _artifact_write_table(frame: pd.DataFrame, destination: Path) -> Path: + if not isinstance(frame, pd.DataFrame): + raise TypeError("benchmark artifact tables must be pandas DataFrames") + frame.to_csv(destination, index=False, lineterminator="\n") + return destination + + +def _artifact_write_json(payload: Mapping[str, Any], destination: Path) -> Path: + destination.write_text( + json.dumps( + _artifact_json_safe(payload), + indent=2, + sort_keys=True, + allow_nan=False, + ) + + "\n", + encoding="utf-8", + ) + return destination + + +def _artifact_evidence_types(frame: pd.DataFrame, default: str) -> list[str]: + if "evidence_type" not in frame or frame.empty: + return [default] + values = sorted(frame["evidence_type"].dropna().astype(str).unique().tolist()) + return values or [default] + + +def _artifact_publish_directory(stage: Path, output: Path, temporary_root: Path) -> None: + backup = temporary_root / "previous_bundle" + if output.exists(): + output.replace(backup) + try: + stage.replace(output) + except BaseException: + if backup.exists() and not output.exists(): + backup.replace(output) + raise + if backup.exists(): + shutil.rmtree(backup) + + +def write_nyc_graph_benchmark_artifacts( + result: NYCGraphBenchmarkResult, + output_dir: str | Path, + *, + project_root: str | Path | None = None, +) -> dict[str, Path]: + """Atomically publish a self-contained NYC-graph benchmark bundle. + + The bundle keeps descriptive input-graph provenance separate from semi-synthetic + known-truth results. Equal result objects produce byte-identical artifacts. + """ + + if not isinstance(result, NYCGraphBenchmarkResult): + raise TypeError("result must be an NYCGraphBenchmarkResult") + if not isinstance(result.metadata, Mapping): + raise TypeError("result.metadata must be a mapping") + artifact_root = _artifact_project_root(project_root) + inputs = _artifact_calibration_inputs(result.metadata, artifact_root) + output, portable_output = _artifact_output_path(output_dir, project_root) + output.parent.mkdir(parents=True, exist_ok=True) + temporary_root = Path( + tempfile.mkdtemp(prefix=f".{output.name}-stage-", dir=output.parent) + ) + stage = temporary_root / "bundle" + stage.mkdir() + tables = { + "records": result.records, + "summary": result.summary, + "fit_ledger": result.fit_ledger, + "failures": result.failures, + } + filenames = {name: f"{name}.csv" for name in tables} + try: + for name, frame in tables.items(): + _artifact_write_table(frame, stage / filenames[name]) + + metadata = dict(result.metadata) + if "artifact_bundle" in metadata: + raise ValueError("result metadata already contains reserved artifact_bundle") + metadata["artifact_bundle"] = { + "schema_version": NYC_GRAPH_BENCHMARK_ARTIFACT_SCHEMA_VERSION, + "artifact_type": "nyc_graph_interference_benchmark", + "portable_output_directory": portable_output, + "portable_paths": True, + "bundle_valid": True, + "evidence_type": BENCHMARK_EVIDENCE, + "causal_claim": False, + "causal_claim_from_nyc_data": False, + "input_graph_evidence_label": CALIBRATION_EVIDENCE, + "inputs": inputs, + "tables": { + name: {"path": filenames[name], "rows": int(len(frame))} + for name, frame in tables.items() + }, + } + metadata_path = _artifact_write_json(metadata, stage / "metadata.json") + + files: list[dict[str, Any]] = [] + for name, frame in tables.items(): + path = stage / filenames[name] + files.append( + { + "path": path.name, + "role": name, + "media_type": "text/csv", + "rows": int(len(frame)), + "bytes": path.stat().st_size, + "sha256": sha256_file(path), + "evidence_types": _artifact_evidence_types( + frame, BENCHMARK_EVIDENCE + ), + } + ) + files.append( + { + "path": metadata_path.name, + "role": "metadata", + "media_type": "application/json", + "bytes": metadata_path.stat().st_size, + "sha256": sha256_file(metadata_path), + "evidence_types": [BENCHMARK_EVIDENCE], + } + ) + manifest = { + "schema_version": NYC_GRAPH_BENCHMARK_ARTIFACT_SCHEMA_VERSION, + "artifact_type": "nyc_graph_interference_benchmark", + "evidence_type": BENCHMARK_EVIDENCE, + "causal_claim": False, + "causal_claim_from_nyc_data": False, + "input_graph_evidence_label": CALIBRATION_EVIDENCE, + "portable_paths": True, + "bundle_valid": True, + "artifact_directory": portable_output, + "metadata_file": metadata_path.name, + "files": files, + "inputs": inputs, + } + _artifact_write_json(manifest, stage / "manifest.json") + _artifact_publish_directory(stage, output, temporary_root) + finally: + if temporary_root.exists(): + shutil.rmtree(temporary_root) + + return { + "output_directory": output, + **{name: output / filename for name, filename in filenames.items()}, + "metadata": output / "metadata.json", + "manifest": output / "manifest.json", + } + + +__all__ = [ + "NYCGraphBenchmarkConfig", + "NYCGraphBenchmarkResult", + "NYCGraphEstimands", + "ValidatedNYCGraphBundle", + "known_nyc_graph_estimands", + "run_nyc_graph_benchmark", + "validate_nyc_graph_bundle", + "write_nyc_graph_benchmark_artifacts", +] diff --git a/CasualLab/src/casuallab/nyc_income.py b/CasualLab/src/casuallab/nyc_income.py new file mode 100644 index 0000000000000000000000000000000000000000..fe9c2c389f0ceb55c50b27a09835060a18b51c61 --- /dev/null +++ b/CasualLab/src/casuallab/nyc_income.py @@ -0,0 +1,1776 @@ +"""Auditable NYC taxi-zone income heterogeneity as descriptive evidence. + +This module spatially allocates Census ACS ``B19001`` household-income-bin +counts to TLC Taxi Zones. It never takes medians of tract or NTA medians: +tract bin counts are summed to 2020 NTAs, the complete NTA distribution is +allocated by equal-area polygon overlap, and grouped medians are computed only +after aggregation. The allocation assumes households are uniformly located +within each NTA, so all trip comparisons are ecological, observational, and +non-causal. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import re +import tempfile +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from datetime import date +from pathlib import Path +from typing import Any + +import duckdb +import numpy as np +import pandas as pd +import shapefile +from pyproj import Transformer +from shapely.geometry import shape +from shapely.ops import transform +from shapely.strtree import STRtree + +from casuallab.data import sha256_file + +TAXI_ZONES_URL = "https://d37ci6vzurychx.cloudfront.net/misc/taxi_zones.zip" +TAXI_ZONES_SHA256 = "f6d711917bb4340f8f644d5366c51665489eb2d426dd1a4a55677721ae5adf17" +NTA2020_URL = ( + "https://data.cityofnewyork.us/resource/9nt8-h7nd.geojson?" + "$limit=500&$order=nta2020" +) +NTA2020_SHA256 = "4a036c53ce665a73954f260ef4f3a8c49f33d75fb2fc859fe0baf92f4b7f8af8" +TRACT_TO_NTA_URL = ( + "https://data.cityofnewyork.us/resource/63ge-mke6.csv?" + "$select=geoid,nta2020,ntaname,borocode,boroname&" + "$where=nta2020%20is%20not%20null&$limit=5000&$order=geoid" +) +TRACT_TO_NTA_SHA256 = ( + "a23087eca9279f0081e6984e53bcd46ea13e2076be63235386d483e91bf7dc96" +) +ACS_B19001_PARENT_URL = ( + "https://www2.census.gov/programs-surveys/acs/summary_file/2022/" + "table-based-SF/data/5YRData/acsdt5y2022-b19001.dat" +) +ACS_B19001_PARENT_BYTES = 69_201_868 +ACS_B19001_PARENT_SHA256 = ( + "3cdb575ba0d2f03fa9f008617504e675577ee3cbe503461de9d80c0c3280fdac" +) +ACS_B19001_NYC_SLICE_SHA256 = ( + "b26ec3e7298e1842d383c8581e11ecbe3fd027e6e09238bd5c67da928bc1c215" +) + +INCOME_EVIDENCE_LABEL = "descriptive_observed_external_neighborhood_income" +INCOME_SCHEMA_VERSION = "1.0.0" +NYC_COUNTY_FIPS = ("005", "047", "061", "081", "085") +EQUAL_AREA_CRS = "EPSG:6933" +TAXI_SOURCE_CRS = "EPSG:2263" +NTA_SOURCE_CRS = "EPSG:4326" + +# B19001 estimate bins 002--017. The final bin is open-ended (>= $200,000). +INCOME_BIN_LOWER_USD = ( + 0.0, + 10_000.0, + 15_000.0, + 20_000.0, + 25_000.0, + 30_000.0, + 35_000.0, + 40_000.0, + 45_000.0, + 50_000.0, + 60_000.0, + 75_000.0, + 100_000.0, + 125_000.0, + 150_000.0, + 200_000.0, +) +INCOME_BIN_UPPER_USD = ( + 10_000.0, + 15_000.0, + 20_000.0, + 25_000.0, + 30_000.0, + 35_000.0, + 40_000.0, + 45_000.0, + 50_000.0, + 60_000.0, + 75_000.0, + 100_000.0, + 125_000.0, + 150_000.0, + 200_000.0, + None, +) +ESTIMATE_COLUMNS = tuple(f"B19001_E{index:03d}" for index in range(1, 18)) +MOE_COLUMNS = tuple(f"B19001_M{index:03d}" for index in range(1, 18)) +BIN_ESTIMATE_COLUMNS = ESTIMATE_COLUMNS[1:] +BIN_MOE_COLUMNS = MOE_COLUMNS[1:] + + +@dataclass(frozen=True, slots=True) +class NYCIncomeConfig: + """Pinned source, geometry, grouping, and month contract.""" + + expected_taxi_sha256: str = TAXI_ZONES_SHA256 + expected_nta_sha256: str = NTA2020_SHA256 + expected_tract_to_nta_sha256: str = TRACT_TO_NTA_SHA256 + expected_acs_sha256: str = ACS_B19001_NYC_SLICE_SHA256 + expected_taxi_features: int = 263 + expected_nta_features: int = 262 + expected_tract_rows: int = 2_325 + expected_acs_rows: int = 2_327 + taxi_source_crs: str = TAXI_SOURCE_CRS + nta_source_crs: str = NTA_SOURCE_CRS + equal_area_crs: str = EQUAL_AREA_CRS + minimum_intersection_area_m2: float = 1.0 + minimum_residential_nta_area_coverage: float = 0.98 + minimum_allocated_households: float = 1.0 + minimum_residential_taxi_zone_area_share: float = 0.5 + residential_nta_type_codes: tuple[str, ...] = ("0",) + start_date: date = date(2024, 1, 1) + end_date: date = date(2024, 1, 31) + + def __post_init__(self) -> None: + for name in ( + "expected_taxi_sha256", + "expected_nta_sha256", + "expected_tract_to_nta_sha256", + "expected_acs_sha256", + ): + digest = str(getattr(self, name)) + if len(digest) != 64 or any(character not in "0123456789abcdef" for character in digest): + raise ValueError(f"{name} must be a lowercase SHA-256 digest") + for name in ( + "expected_taxi_features", + "expected_nta_features", + "expected_tract_rows", + "expected_acs_rows", + ): + if int(getattr(self, name)) < 1: + raise ValueError(f"{name} must be positive") + if self.start_date > self.end_date: + raise ValueError("income start_date must not exceed end_date") + if not math.isfinite(self.minimum_intersection_area_m2) or self.minimum_intersection_area_m2 < 0: + raise ValueError("minimum_intersection_area_m2 must be finite and nonnegative") + if not 0 < self.minimum_residential_nta_area_coverage <= 1: + raise ValueError("minimum_residential_nta_area_coverage must be in (0, 1]") + if not math.isfinite(self.minimum_allocated_households) or self.minimum_allocated_households <= 0: + raise ValueError("minimum_allocated_households must be finite and positive") + if not 0 <= self.minimum_residential_taxi_zone_area_share <= 1: + raise ValueError( + "minimum_residential_taxi_zone_area_share must be in [0, 1]" + ) + if ( + not self.residential_nta_type_codes + or any(not str(code).strip() for code in self.residential_nta_type_codes) + or len(set(self.residential_nta_type_codes)) + != len(self.residential_nta_type_codes) + ): + raise ValueError("residential_nta_type_codes must be unique nonempty strings") + + +@dataclass(frozen=True, slots=True) +class NYCIncomeArtifacts: + """Published crosswalk, income summaries, trip descriptions, and manifest.""" + + crosswalk_path: Path + nta_income_path: Path + zone_income_path: Path + daily_path: Path + monthly_path: Path + summary_path: Path + manifest_path: Path + + def paths(self) -> tuple[Path, ...]: + return ( + self.crosswalk_path, + self.nta_income_path, + self.zone_income_path, + self.daily_path, + self.monthly_path, + self.summary_path, + self.manifest_path, + ) + + +def _require_pinned_file(path: str | Path, expected_sha256: str, role: str) -> Path: + source = Path(path).resolve() + if not source.is_file(): + raise FileNotFoundError(source) + if sha256_file(source) != expected_sha256: + raise ValueError(f"{role} SHA-256 does not match the configured pin") + return source + + +def _portable(path: Path, root: Path) -> str: + try: + return str(path.resolve().relative_to(root.resolve())) + except ValueError as exc: + raise ValueError(f"income path is outside project_root: {path}") from exc + + +def _sql_string(value: str) -> str: + return "'" + value.replace("'", "''") + "'" + + +def _scan_sql(paths: Sequence[Path]) -> str: + if not paths: + raise FileNotFoundError("NYC income analysis requires zone-time Parquet files") + rendered = ", ".join(_sql_string(str(path.resolve())) for path in paths) + return f"read_parquet([{rendered}], hive_partitioning=false)" + + +def _atomic_csv(frame: pd.DataFrame, path: Path) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="", + prefix=f".{path.stem}-", + suffix=path.suffix, + dir=path.parent, + delete=False, + ) as handle: + temporary = Path(handle.name) + frame.to_csv(handle, index=False) + temporary.replace(path) + return path + + +def _atomic_json(payload: Mapping[str, Any], path: Path) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + prefix=f".{path.stem}-", + suffix=path.suffix, + dir=path.parent, + delete=False, + ) as handle: + temporary = Path(handle.name) + json.dump(payload, handle, indent=2, sort_keys=True, allow_nan=False) + handle.write("\n") + temporary.replace(path) + return path + + +def _finite_or_none(value: float) -> float | None: + return float(value) if math.isfinite(float(value)) else None + + +def _grouped_median(bin_counts: Sequence[float]) -> tuple[float | None, bool]: + """Return a grouped-distribution median and whether it is top-coded.""" + + counts = np.asarray(bin_counts, dtype=float) + if counts.shape != (16,) or not np.isfinite(counts).all() or (counts < 0).any(): + raise ValueError("B19001 grouped-median counts must be 16 finite nonnegative values") + total = float(counts.sum()) + if total <= 0: + return None, False + rank = 0.5 * total + cumulative = np.cumsum(counts) + index = int(np.searchsorted(cumulative, rank, side="left")) + lower = INCOME_BIN_LOWER_USD[index] + upper = INCOME_BIN_UPPER_USD[index] + if upper is None: + return lower, True + before = float(cumulative[index - 1]) if index else 0.0 + within = float(counts[index]) + if within <= 0: + raise ValueError("grouped median selected an empty B19001 bin") + fraction = min(max((rank - before) / within, 0.0), 1.0) + return lower + fraction * (upper - lower), False + + +def _load_taxi_geometries( + source_path: Path, + config: NYCIncomeConfig, +) -> list[dict[str, Any]]: + reader = shapefile.Reader(str(source_path)) + if len(reader) != config.expected_taxi_features: + raise ValueError("TLC Taxi Zone source has an unexpected feature count") + transformer = Transformer.from_crs( + config.taxi_source_crs, + config.equal_area_crs, + always_xy=True, + ) + records: list[dict[str, Any]] = [] + for feature, record in zip(reader.shapes(), reader.records(), strict=True): + properties = record.as_dict() + location_id = int(properties["LocationID"]) + geometry = shape(feature.__geo_interface__) + if geometry.is_empty or not geometry.is_valid: + raise ValueError(f"TLC Taxi Zone {location_id} has invalid geometry") + projected = transform(transformer.transform, geometry) + if projected.is_empty or not projected.is_valid or projected.area <= 0: + raise ValueError(f"TLC Taxi Zone {location_id} failed equal-area projection") + records.append( + { + "location_id": location_id, + "taxi_zone_name": str(properties["zone"]), + "taxi_borough": str(properties["borough"]), + "geometry": projected, + "taxi_zone_area_m2": float(projected.area), + } + ) + ids = [int(record["location_id"]) for record in records] + expected_ids = set(range(1, config.expected_taxi_features + 1)) + if len(set(ids)) != len(ids) or set(ids) != expected_ids: + raise ValueError("TLC Taxi Zone LocationIDs must be unique and calendar-complete") + return records + + +def _load_nta_geometries( + source_path: Path, + config: NYCIncomeConfig, +) -> list[dict[str, Any]]: + payload = json.loads(source_path.read_text(encoding="utf-8")) + features = payload.get("features") + if payload.get("type") != "FeatureCollection" or not isinstance(features, list): + raise ValueError("NTA source must be a GeoJSON FeatureCollection") + if len(features) != config.expected_nta_features: + raise ValueError("NTA source has an unexpected feature count") + transformer = Transformer.from_crs( + config.nta_source_crs, + config.equal_area_crs, + always_xy=True, + ) + records: list[dict[str, Any]] = [] + for feature in features: + properties = feature.get("properties", {}) + nta2020 = str(properties.get("nta2020", "")).strip() + geometry = shape(feature.get("geometry")) + if not nta2020 or geometry.is_empty or not geometry.is_valid: + raise ValueError("NTA source contains a missing code or invalid geometry") + projected = transform(transformer.transform, geometry) + if projected.is_empty or not projected.is_valid or projected.area <= 0: + raise ValueError(f"NTA {nta2020} failed equal-area projection") + records.append( + { + "nta2020": nta2020, + "nta_name": str(properties.get("ntaname", "")), + "nta_type": str(properties.get("ntatype", "")), + "nta_borough": str(properties.get("boroname", "")), + "geometry": projected, + "nta_area_m2": float(projected.area), + } + ) + codes = [str(record["nta2020"]) for record in records] + if len(set(codes)) != len(codes): + raise ValueError("NTA2020 codes must be unique") + return records + + +def build_taxi_zone_nta_crosswalk( + taxi_zone_zip_path: str | Path, + nta_geojson_path: str | Path, + config: NYCIncomeConfig | None = None, +) -> tuple[pd.DataFrame, dict[str, Any]]: + """Intersect official polygons in an equal-area CRS and retain full lineage.""" + + cfg = config or NYCIncomeConfig() + taxi_path = _require_pinned_file( + taxi_zone_zip_path, + cfg.expected_taxi_sha256, + "TLC Taxi Zone source", + ) + nta_path = _require_pinned_file( + nta_geojson_path, + cfg.expected_nta_sha256, + "NYC NTA source", + ) + taxi_records = _load_taxi_geometries(taxi_path, cfg) + nta_records = _load_nta_geometries(nta_path, cfg) + nta_geometries = [record["geometry"] for record in nta_records] + tree = STRtree(nta_geometries) + rows: list[dict[str, Any]] = [] + for taxi in taxi_records: + candidates = tree.query(taxi["geometry"], predicate="intersects") + matched = False + for raw_index in candidates: + nta = nta_records[int(raw_index)] + area = float(taxi["geometry"].intersection(nta["geometry"]).area) + if area <= cfg.minimum_intersection_area_m2: + continue + matched = True + rows.append( + { + "location_id": taxi["location_id"], + "taxi_zone_name": taxi["taxi_zone_name"], + "taxi_borough": taxi["taxi_borough"], + "nta2020": nta["nta2020"], + "nta_name": nta["nta_name"], + "nta_type": nta["nta_type"], + "nta_borough": nta["nta_borough"], + "taxi_zone_area_m2": taxi["taxi_zone_area_m2"], + "nta_area_m2": nta["nta_area_m2"], + "intersection_area_m2": area, + "has_positive_area_overlap": True, + } + ) + if not matched: + rows.append( + { + "location_id": taxi["location_id"], + "taxi_zone_name": taxi["taxi_zone_name"], + "taxi_borough": taxi["taxi_borough"], + "nta2020": None, + "nta_name": None, + "nta_type": None, + "nta_borough": None, + "taxi_zone_area_m2": taxi["taxi_zone_area_m2"], + "nta_area_m2": np.nan, + "intersection_area_m2": 0.0, + "has_positive_area_overlap": False, + } + ) + if not rows: + raise ValueError("Taxi Zone and NTA sources have no positive-area intersections") + crosswalk = pd.DataFrame(rows) + crosswalk["taxi_zone_area_share"] = crosswalk["intersection_area_m2"] / crosswalk["taxi_zone_area_m2"] + crosswalk["nta_area_share"] = ( + crosswalk["intersection_area_m2"] / crosswalk["nta_area_m2"] + ) + nta_intersection_sum = crosswalk.groupby("nta2020")["intersection_area_m2"].transform("sum") + crosswalk["nta_allocation_weight"] = ( + crosswalk["intersection_area_m2"] / nta_intersection_sum + ).fillna(0.0) + positive = crosswalk["has_positive_area_overlap"] + dominant_index = crosswalk.loc[positive].groupby("location_id")["intersection_area_m2"].idxmax() + crosswalk["is_dominant_nta"] = False + crosswalk.loc[dominant_index, "is_dominant_nta"] = True + crosswalk["evidence_label"] = INCOME_EVIDENCE_LABEL + crosswalk["causal_claim"] = False + crosswalk = crosswalk.sort_values( + ["location_id", "intersection_area_m2", "nta2020"], + ascending=[True, False, True], + ).reset_index(drop=True) + + taxi_coverage = ( + crosswalk.groupby("location_id", as_index=False, dropna=False) + .agg( + covered_area_m2=("intersection_area_m2", "sum"), + taxi_zone_area_m2=("taxi_zone_area_m2", "first"), + ) + ) + taxi_coverage["coverage"] = ( + taxi_coverage["covered_area_m2"] / taxi_coverage["taxi_zone_area_m2"] + ) + nta_coverage = ( + crosswalk.loc[positive].groupby("nta2020", as_index=False) + .agg( + covered_area_m2=("intersection_area_m2", "sum"), + nta_area_m2=("nta_area_m2", "first"), + ) + ) + nta_coverage["coverage"] = nta_coverage["covered_area_m2"] / nta_coverage["nta_area_m2"] + diagnostics = { + "taxi_source_features": len(taxi_records), + "taxi_source_unique_location_ids": len({row["location_id"] for row in taxi_records}), + "nta_source_features": len(nta_records), + "crosswalk_rows_including_unmapped_zones": len(crosswalk), + "positive_area_intersections": int(positive.sum()), + "taxi_zones_with_nta_overlap": int(crosswalk.loc[positive, "location_id"].nunique()), + "taxi_zones_without_nta_overlap": int((~positive).sum()), + "ntas_with_taxi_zone_overlap": int(crosswalk["nta2020"].nunique()), + "minimum_taxi_zone_area_coverage": float(taxi_coverage["coverage"].min()), + "median_taxi_zone_area_coverage": float(taxi_coverage["coverage"].median()), + "minimum_nta_area_coverage": float(nta_coverage["coverage"].min()), + "median_nta_area_coverage": float(nta_coverage["coverage"].median()), + "equal_area_crs": cfg.equal_area_crs, + "minimum_intersection_area_m2": cfg.minimum_intersection_area_m2, + } + return crosswalk, diagnostics + + +def aggregate_acs_b19001_to_nta( + tract_to_nta_path: str | Path, + acs_b19001_path: str | Path, + nta_codes: Sequence[str], + config: NYCIncomeConfig | None = None, +) -> tuple[pd.DataFrame, dict[str, Any]]: + """Aggregate tract B19001 counts to NTAs before calculating any median.""" + + cfg = config or NYCIncomeConfig() + tract_path = _require_pinned_file( + tract_to_nta_path, + cfg.expected_tract_to_nta_sha256, + "NYC tract-to-NTA source", + ) + acs_path = _require_pinned_file( + acs_b19001_path, + cfg.expected_acs_sha256, + "Census ACS B19001 source", + ) + tract_map = pd.read_csv(tract_path, dtype="string") + required_map = {"geoid", "nta2020", "ntaname", "borocode", "boroname"} + if required_map.difference(tract_map.columns): + raise ValueError("tract-to-NTA source is missing required fields") + if len(tract_map) != cfg.expected_tract_rows: + raise ValueError("tract-to-NTA source has an unexpected row count") + if tract_map["geoid"].isna().any() or tract_map["geoid"].duplicated().any(): + raise ValueError("tract-to-NTA GEOIDs must be nonmissing and unique") + if not tract_map["geoid"].str.fullmatch(r"36\d{9}").all(): + raise ValueError("tract-to-NTA source contains an invalid New York GEOID") + if tract_map["nta2020"].isna().any(): + raise ValueError("tract-to-NTA source contains a missing NTA code") + + acs = pd.read_csv(acs_path, sep="|", dtype={"GEO_ID": "string"}) + required_acs = {"GEO_ID", *ESTIMATE_COLUMNS, *MOE_COLUMNS} + if required_acs.difference(acs.columns): + raise ValueError("ACS B19001 source is missing estimates or margins of error") + if len(acs) != cfg.expected_acs_rows: + raise ValueError("ACS B19001 source has an unexpected row count") + if acs["GEO_ID"].isna().any() or acs["GEO_ID"].duplicated().any(): + raise ValueError("ACS B19001 GEO_ID values must be nonmissing and unique") + pattern = re.compile(r"^1400000US36(?:005|047|061|081|085)\d{6}$") + if not acs["GEO_ID"].astype(str).map(lambda value: bool(pattern.fullmatch(value))).all(): + raise ValueError("ACS slice must contain only NYC Census tracts") + numeric_columns = [*ESTIMATE_COLUMNS, *MOE_COLUMNS] + acs[numeric_columns] = acs[numeric_columns].apply(pd.to_numeric, errors="raise") + if not np.isfinite(acs[numeric_columns].to_numpy(dtype=float)).all(): + raise ValueError("ACS B19001 contains non-finite estimates or margins of error") + if (acs[numeric_columns] < 0).any().any(): + raise ValueError("ACS B19001 contains negative estimates or margins of error") + if not ( + acs[ESTIMATE_COLUMNS[0]].to_numpy(dtype=int) + == acs[list(BIN_ESTIMATE_COLUMNS)].sum(axis=1).to_numpy(dtype=int) + ).all(): + raise ValueError("ACS B19001 totals do not equal the sixteen income bins") + + acs["geoid"] = acs["GEO_ID"].str.removeprefix("1400000US") + merged = acs.merge( + tract_map[["geoid", "nta2020", "ntaname", "boroname"]], + on="geoid", + how="left", + validate="1:1", + indicator=True, + ) + missing_map = merged["_merge"] != "both" + unmatched_households = int(merged.loc[missing_map, ESTIMATE_COLUMNS[0]].sum()) + if unmatched_households != 0: + raise ValueError("ACS tracts omitted by the clipped NYC crosswalk contain households") + if not set(tract_map["geoid"]).issubset(set(acs["geoid"])): + raise ValueError("tract-to-NTA source contains GEOIDs absent from ACS") + known_nta_codes = {str(code) for code in nta_codes} + if not set(tract_map["nta2020"]).issubset(known_nta_codes): + raise ValueError("tract-to-NTA source references an NTA absent from geometry") + + mapped = merged.loc[~missing_map].copy() + estimates = mapped.groupby("nta2020", as_index=False)[list(ESTIMATE_COLUMNS)].sum() + moe_squared = mapped[list(MOE_COLUMNS)].astype(float).pow(2) + moe_squared["nta2020"] = mapped["nta2020"].to_numpy() + moes = moe_squared.groupby("nta2020", as_index=False)[list(MOE_COLUMNS)].sum() + moes[list(MOE_COLUMNS)] = np.sqrt(moes[list(MOE_COLUMNS)]) + names = ( + mapped.groupby("nta2020", as_index=False) + .agg(nta_name=("ntaname", "first"), nta_borough=("boroname", "first")) + ) + nta = names.merge(estimates, on="nta2020", validate="1:1").merge( + moes, + on="nta2020", + validate="1:1", + ) + medians = nta[list(BIN_ESTIMATE_COLUMNS)].apply( + lambda row: _grouped_median(row.to_numpy(dtype=float)), + axis=1, + ) + nta["grouped_median_household_income_usd"] = [value[0] for value in medians] + nta["grouped_median_top_coded"] = [value[1] for value in medians] + total = nta[ESTIMATE_COLUMNS[0]].astype(float) + nta["share_households_under_50k"] = ( + nta[list(ESTIMATE_COLUMNS[1:10])].sum(axis=1) / total.replace(0, np.nan) + ) + nta["share_households_100k_plus"] = ( + nta[list(ESTIMATE_COLUMNS[13:])].sum(axis=1) / total.replace(0, np.nan) + ) + nta["evidence_label"] = INCOME_EVIDENCE_LABEL + nta["causal_claim"] = False + nta = nta.sort_values("nta2020").reset_index(drop=True) + + citywide_counts = nta[list(BIN_ESTIMATE_COLUMNS)].sum(axis=0).to_numpy(dtype=float) + citywide_median, citywide_top_coded = _grouped_median(citywide_counts) + if citywide_median is None or citywide_top_coded: + raise ValueError("citywide grouped median must be finite and below the open top bin") + diagnostics = { + "acs_tract_rows": len(acs), + "mapped_tract_rows": len(mapped), + "unmatched_zero_household_tract_rows": int(missing_map.sum()), + "unmatched_households": unmatched_households, + "nta_rows_with_acs_tracts": len(nta), + "acs_total_households": int(acs[ESTIMATE_COLUMNS[0]].sum()), + "mapped_total_households": int(nta[ESTIMATE_COLUMNS[0]].sum()), + "citywide_grouped_median_household_income_usd": citywide_median, + "citywide_grouped_median_top_coded": citywide_top_coded, + "totals_equal_sum_of_bins": True, + "median_of_medians_used": False, + "nta_moe_aggregation": "root_sum_of_squares approximation across tracts", + } + return nta, diagnostics + + +def allocate_nta_income_to_taxi_zones( + crosswalk: pd.DataFrame, + nta_income: pd.DataFrame, + citywide_grouped_median_usd: float, + config: NYCIncomeConfig | None = None, +) -> tuple[pd.DataFrame, dict[str, Any]]: + """Allocate complete NTA income-bin distributions by normalized area overlap.""" + + cfg = config or NYCIncomeConfig() + required_crosswalk = { + "location_id", + "taxi_zone_name", + "taxi_borough", + "nta2020", + "nta_type", + "nta_area_share", + "nta_allocation_weight", + "taxi_zone_area_share", + "intersection_area_m2", + "is_dominant_nta", + } + if required_crosswalk.difference(crosswalk.columns): + raise ValueError("Taxi Zone-NTA crosswalk is missing allocation fields") + required_income = {"nta2020", *ESTIMATE_COLUMNS} + if required_income.difference(nta_income.columns): + raise ValueError("NTA income summary is missing B19001 counts") + merged = crosswalk.merge( + nta_income[["nta2020", *ESTIMATE_COLUMNS]], + on="nta2020", + how="left", + validate="m:1", + ) + merged[list(ESTIMATE_COLUMNS)] = merged[list(ESTIMATE_COLUMNS)].fillna(0.0) + residential_types = {str(code) for code in cfg.residential_nta_type_codes} + merged["residential_nta_eligible"] = merged["nta_type"].astype("string").isin( + residential_types + ) + residential = merged[ESTIMATE_COLUMNS[0]] > 0 + residential_coverage = ( + merged.loc[residential] + .groupby("nta2020", as_index=False) + .agg(coverage=("nta_area_share", "sum")) + ) + if residential_coverage.empty: + raise ValueError("no household-bearing NTA intersects a Taxi Zone") + if ( + residential_coverage["coverage"] + < cfg.minimum_residential_nta_area_coverage + ).any(): + raise ValueError("a household-bearing NTA lacks sufficient Taxi Zone area coverage") + allocation_sums = merged.groupby("nta2020")["nta_allocation_weight"].sum() + if not np.allclose(allocation_sums.to_numpy(dtype=float), 1.0, rtol=0, atol=1e-10): + raise ValueError("NTA allocation weights do not sum to one") + + allocated_columns: list[str] = [] + for column in ESTIMATE_COLUMNS: + allocated = f"allocated_{column}" + merged[allocated] = ( + merged[column].astype(float) * merged["nta_allocation_weight"].astype(float) + ) + allocated_columns.append(allocated) + merged["area_allocated_residential_households"] = np.where( + merged["residential_nta_eligible"], + merged[f"allocated_{ESTIMATE_COLUMNS[0]}"], + 0.0, + ) + zone_counts = merged.groupby("location_id", as_index=False)[allocated_columns].sum() + renamed = {allocated: original for allocated, original in zip(allocated_columns, ESTIMATE_COLUMNS, strict=True)} + zone_counts = zone_counts.rename(columns=renamed) + zone_meta = ( + crosswalk.groupby("location_id", as_index=False) + .agg( + taxi_zone_name=("taxi_zone_name", "first"), + taxi_borough=("taxi_borough", "first"), + taxi_zone_area_m2=("taxi_zone_area_m2", "first"), + nta_covered_area_share=("taxi_zone_area_share", "sum"), + intersecting_ntas=("nta2020", "nunique"), + ) + ) + residential_overlap = ( + merged.loc[merged["residential_nta_eligible"]] + .groupby("location_id", as_index=False) + .agg( + residential_intersection_area_m2=("intersection_area_m2", "sum"), + residential_taxi_zone_area_share=("taxi_zone_area_share", "sum"), + residential_nta_count=("nta2020", "nunique"), + area_allocated_residential_households=( + "area_allocated_residential_households", + "sum", + ), + ) + ) + dominant = ( + crosswalk.loc[ + crosswalk["is_dominant_nta"], + ["location_id", "nta2020", "nta_name", "nta_type"], + ] + .rename( + columns={ + "nta2020": "dominant_nta2020", + "nta_name": "dominant_nta_name", + "nta_type": "dominant_nta_type", + } + ) + ) + zones = ( + zone_meta.merge(dominant, on="location_id", how="left", validate="1:1") + .merge(residential_overlap, on="location_id", how="left", validate="1:1") + .merge( + zone_counts, + on="location_id", + how="left", + validate="1:1", + ) + ) + for column in ( + "residential_intersection_area_m2", + "residential_taxi_zone_area_share", + "residential_nta_count", + "area_allocated_residential_households", + ): + zones[column] = zones[column].fillna(0.0) + zones["residential_nta_count"] = zones["residential_nta_count"].astype(int) + zones["dominant_nta_type"] = zones["dominant_nta_type"].astype("string") + zones["dominant_nta_residential_eligible"] = zones["dominant_nta_type"].isin( + residential_types + ) + medians = zones[list(BIN_ESTIMATE_COLUMNS)].apply( + lambda row: _grouped_median(row.to_numpy(dtype=float)), + axis=1, + ) + zones["grouped_median_household_income_usd"] = [value[0] for value in medians] + zones["grouped_median_top_coded"] = [value[1] for value in medians] + total = zones[ESTIMATE_COLUMNS[0]].astype(float) + zones["share_households_under_50k"] = ( + zones[list(ESTIMATE_COLUMNS[1:10])].sum(axis=1) / total.replace(0, np.nan) + ) + zones["share_households_100k_plus"] = ( + zones[list(ESTIMATE_COLUMNS[13:])].sum(axis=1) / total.replace(0, np.nan) + ) + zones["citywide_grouped_median_threshold_usd"] = citywide_grouped_median_usd + zones["grouped_median_distance_from_citywide_threshold_usd"] = ( + zones["grouped_median_household_income_usd"] - citywide_grouped_median_usd + ) + zones["absolute_grouped_median_distance_from_citywide_threshold_usd"] = zones[ + "grouped_median_distance_from_citywide_threshold_usd" + ].abs() + sensitivity_classified = ( + zones[ESTIMATE_COLUMNS[0]] >= cfg.minimum_allocated_households + ) & zones["grouped_median_household_income_usd"].notna() + zones["income_group_all_zone_area_allocation_sensitivity"] = "unclassified" + zones.loc[ + sensitivity_classified + & ( + zones["grouped_median_household_income_usd"] + < citywide_grouped_median_usd + ), + "income_group_all_zone_area_allocation_sensitivity", + ] = "low_income_area" + zones.loc[ + sensitivity_classified + & ( + zones["grouped_median_household_income_usd"] + >= citywide_grouped_median_usd + ), + "income_group_all_zone_area_allocation_sensitivity", + ] = "high_income_area" + zones["primary_income_classification_eligible"] = ( + sensitivity_classified + & zones["dominant_nta_residential_eligible"] + & ( + zones["residential_taxi_zone_area_share"] + >= cfg.minimum_residential_taxi_zone_area_share + ) + ) + zones["income_group"] = np.where( + zones["primary_income_classification_eligible"], + zones["income_group_all_zone_area_allocation_sensitivity"], + "unclassified", + ) + zones["evidence_label"] = INCOME_EVIDENCE_LABEL + zones["causal_claim"] = False + zones = zones.sort_values("location_id").reset_index(drop=True) + + source_households = float(nta_income[ESTIMATE_COLUMNS[0]].sum()) + allocated_households = float(zones[ESTIMATE_COLUMNS[0]].sum()) + source_bins = nta_income[list(BIN_ESTIMATE_COLUMNS)].sum(axis=0).to_numpy(dtype=float) + allocated_bins = zones[list(BIN_ESTIMATE_COLUMNS)].sum(axis=0).to_numpy(dtype=float) + if not math.isclose(source_households, allocated_households, rel_tol=0, abs_tol=1e-6): + raise ValueError("area allocation does not conserve ACS households") + if not np.allclose(source_bins, allocated_bins, rtol=0, atol=1e-6): + raise ValueError("area allocation does not conserve ACS income-bin counts") + diagnostics = { + "zone_rows": len(zones), + "classified_zone_rows": int((zones["income_group"] != "unclassified").sum()), + "low_income_zone_rows": int((zones["income_group"] == "low_income_area").sum()), + "high_income_zone_rows": int((zones["income_group"] == "high_income_area").sum()), + "unclassified_zone_rows": int((zones["income_group"] == "unclassified").sum()), + "sensitivity_classified_zone_rows": int( + ( + zones["income_group_all_zone_area_allocation_sensitivity"] + != "unclassified" + ).sum() + ), + "sensitivity_low_income_zone_rows": int( + ( + zones["income_group_all_zone_area_allocation_sensitivity"] + == "low_income_area" + ).sum() + ), + "sensitivity_high_income_zone_rows": int( + ( + zones["income_group_all_zone_area_allocation_sensitivity"] + == "high_income_area" + ).sum() + ), + "dominant_nonresidential_zone_rows": int( + ( + zones["dominant_nta_type"].notna() + & ~zones["dominant_nta_residential_eligible"] + ).sum() + ), + "dominant_nonresidential_zones_classified_only_in_sensitivity": int( + ( + zones["dominant_nta_type"].notna() + & ~zones["dominant_nta_residential_eligible"] + & ( + zones["income_group_all_zone_area_allocation_sensitivity"] + != "unclassified" + ) + ).sum() + ), + "residential_nta_type_codes": sorted(residential_types), + "minimum_allocated_households": cfg.minimum_allocated_households, + "minimum_residential_taxi_zone_area_share": ( + cfg.minimum_residential_taxi_zone_area_share + ), + "minimum_primary_classified_residential_taxi_zone_area_share": ( + float( + zones.loc[ + zones["primary_income_classification_eligible"], + "residential_taxi_zone_area_share", + ].min() + ) + if zones["primary_income_classification_eligible"].any() + else None + ), + "minimum_primary_classified_allocated_households": ( + float( + zones.loc[ + zones["primary_income_classification_eligible"], + ESTIMATE_COLUMNS[0], + ].min() + ) + if zones["primary_income_classification_eligible"].any() + else None + ), + "primary_eligibility_rule": ( + "dominant NTA type is pre-specified residential and allocated " + "households and residential Taxi Zone area share meet configured minima" + ), + "source_nta_households": source_households, + "allocated_taxi_zone_households": allocated_households, + "households_conserved": True, + "all_sixteen_bins_conserved": True, + "minimum_household_nta_area_coverage": float(residential_coverage["coverage"].min()), + "allocation_assumption": "households are uniformly distributed within each NTA", + "median_of_medians_used": False, + } + return zones, diagnostics + + +def income_trip_descriptions( + zone_time_paths: Sequence[str | Path], + zone_income: pd.DataFrame, + config: NYCIncomeConfig | None = None, +) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, dict[str, Any]]: + """Describe published trips by ecological high/low-income area group.""" + + cfg = config or NYCIncomeConfig() + paths = tuple(Path(path).resolve() for path in zone_time_paths) + required_zone = { + "location_id", + "taxi_zone_name", + "taxi_borough", + "income_group", + "income_group_all_zone_area_allocation_sensitivity", + "primary_income_classification_eligible", + "grouped_median_household_income_usd", + "grouped_median_top_coded", + "citywide_grouped_median_threshold_usd", + "nta_covered_area_share", + "dominant_nta2020", + "dominant_nta_name", + "dominant_nta_type", + "dominant_nta_residential_eligible", + "residential_intersection_area_m2", + "residential_taxi_zone_area_share", + "residential_nta_count", + "area_allocated_residential_households", + ESTIMATE_COLUMNS[0], + } + if required_zone.difference(zone_income.columns): + raise ValueError("Taxi Zone income profile is missing required fields") + if zone_income["location_id"].duplicated().any(): + raise ValueError("Taxi Zone income profile must be unique by LocationID") + allowed_groups = {"low_income_area", "high_income_area", "unclassified"} + if not set(zone_income["income_group"]).issubset(allowed_groups): + raise ValueError("Taxi Zone income profile contains an unknown group") + + connection = duckdb.connect(database=":memory:") + try: + daily_zone = connection.execute( + f""" + SELECT CAST(zone_id AS VARCHAR) AS panel_zone_id, + CAST(service_date AS DATE) AS service_date, + COUNT(*)::BIGINT AS zone_hours, + SUM(CASE WHEN trip_count > 0 THEN 1 ELSE 0 END)::BIGINT + AS occupied_zone_hours, + SUM(CAST(trip_count AS BIGINT))::BIGINT + AS published_completed_trips + FROM {_scan_sql(paths)} + GROUP BY 1, 2 + ORDER BY 2, 1 + """ + ).fetchdf() + finally: + connection.close() + if daily_zone.empty: + raise ValueError("NYC zone-time panel produced no income-analysis rows") + daily_zone["service_date"] = pd.to_datetime( + daily_zone["service_date"], + errors="raise", + ).dt.date + expected_dates = set(pd.date_range(cfg.start_date, cfg.end_date, freq="D").date) + observed_dates = set(daily_zone["service_date"]) + if observed_dates != expected_dates: + raise ValueError("NYC income panel does not cover the configured calendar") + daily_zone["numeric_location_id"] = pd.to_numeric( + daily_zone["panel_zone_id"], + errors="coerce", + ).astype("Int64") + profile_columns = [ + "location_id", + "taxi_zone_name", + "taxi_borough", + "income_group", + "income_group_all_zone_area_allocation_sensitivity", + "primary_income_classification_eligible", + "grouped_median_household_income_usd", + "grouped_median_top_coded", + "citywide_grouped_median_threshold_usd", + "nta_covered_area_share", + "dominant_nta2020", + "dominant_nta_name", + "dominant_nta_type", + "dominant_nta_residential_eligible", + "residential_intersection_area_m2", + "residential_taxi_zone_area_share", + "residential_nta_count", + "area_allocated_residential_households", + ESTIMATE_COLUMNS[0], + ] + profile = zone_income[profile_columns].copy() + profile["location_id"] = profile["location_id"].astype("Int64") + joined = daily_zone.merge( + profile, + left_on="numeric_location_id", + right_on="location_id", + how="left", + validate="m:1", + ) + joined["official_taxi_zone"] = joined["location_id"].notna() + joined["income_group"] = joined["income_group"].fillna("unclassified") + sensitivity_group_column = "income_group_all_zone_area_allocation_sensitivity" + joined[sensitivity_group_column] = joined[sensitivity_group_column].fillna( + "unclassified" + ) + joined["evidence_label"] = INCOME_EVIDENCE_LABEL + joined["causal_claim"] = False + + daily = ( + joined.groupby(["service_date", "income_group"], as_index=False, observed=True) + .agg( + panel_zones=("panel_zone_id", "nunique"), + zone_hours=("zone_hours", "sum"), + occupied_zone_hours=("occupied_zone_hours", "sum"), + published_completed_trips=("published_completed_trips", "sum"), + ) + .sort_values(["service_date", "income_group"]) + .reset_index(drop=True) + ) + daily["mean_published_completed_trips_per_zone_hour"] = ( + daily["published_completed_trips"] / daily["zone_hours"] + ) + daily["evidence_label"] = INCOME_EVIDENCE_LABEL + daily["causal_claim"] = False + + monthly = ( + joined.groupby("income_group", as_index=False, observed=True) + .agg( + panel_zones=("panel_zone_id", "nunique"), + observed_days=("service_date", "nunique"), + zone_hours=("zone_hours", "sum"), + occupied_zone_hours=("occupied_zone_hours", "sum"), + published_completed_trips=("published_completed_trips", "sum"), + ) + .sort_values("income_group") + .reset_index(drop=True) + ) + trip_total = float(monthly["published_completed_trips"].sum()) + classified_total = float( + monthly.loc[ + monthly["income_group"].isin({"low_income_area", "high_income_area"}), + "published_completed_trips", + ].sum() + ) + monthly["mean_published_completed_trips_per_zone_hour"] = ( + monthly["published_completed_trips"] / monthly["zone_hours"] + ) + monthly["mean_daily_published_completed_trips"] = ( + monthly["published_completed_trips"] / monthly["observed_days"] + ) + monthly["share_of_all_published_completed_trips"] = ( + monthly["published_completed_trips"] / trip_total + ) + monthly["share_of_classified_published_completed_trips"] = np.where( + monthly["income_group"].isin({"low_income_area", "high_income_area"}) + & (classified_total > 0), + monthly["published_completed_trips"] / classified_total, + np.nan, + ) + monthly["evidence_label"] = INCOME_EVIDENCE_LABEL + monthly["causal_claim"] = False + + sensitivity_monthly = ( + joined.groupby(sensitivity_group_column, as_index=False, observed=True) + .agg( + panel_zones=("panel_zone_id", "nunique"), + observed_days=("service_date", "nunique"), + zone_hours=("zone_hours", "sum"), + published_completed_trips=("published_completed_trips", "sum"), + ) + .sort_values(sensitivity_group_column) + .reset_index(drop=True) + ) + sensitivity_monthly["mean_published_completed_trips_per_zone_hour"] = ( + sensitivity_monthly["published_completed_trips"] + / sensitivity_monthly["zone_hours"] + ) + + observed_zone = ( + joined.groupby("panel_zone_id", as_index=False, dropna=False) + .agg( + panel_days=("service_date", "nunique"), + zone_hours=("zone_hours", "sum"), + occupied_zone_hours=("occupied_zone_hours", "sum"), + published_completed_trips=("published_completed_trips", "sum"), + ) + ) + profile_for_output = zone_income.copy() + profile_for_output["panel_zone_id"] = profile_for_output["location_id"].astype(str) + zone_summary = profile_for_output.merge( + observed_zone, + on="panel_zone_id", + how="outer", + validate="1:1", + indicator=True, + ) + zone_summary["official_taxi_zone"] = zone_summary["_merge"] != "right_only" + zone_summary["observed_in_panel"] = zone_summary["_merge"] != "left_only" + zone_summary = zone_summary.drop(columns="_merge") + zone_summary["income_group"] = zone_summary["income_group"].fillna("unclassified") + zone_summary[sensitivity_group_column] = zone_summary[ + sensitivity_group_column + ].fillna("unclassified") + for column in ( + "primary_income_classification_eligible", + "dominant_nta_residential_eligible", + ): + zone_summary[column] = ( + zone_summary[column].astype("boolean").fillna(False).astype(bool) + ) + for column in ( + "residential_intersection_area_m2", + "residential_taxi_zone_area_share", + "area_allocated_residential_households", + ): + zone_summary[column] = zone_summary[column].fillna(0) + zone_summary["residential_nta_count"] = ( + zone_summary["residential_nta_count"].fillna(0).astype(int) + ) + for column in ( + "panel_days", + "zone_hours", + "occupied_zone_hours", + "published_completed_trips", + ): + zone_summary[column] = zone_summary[column].fillna(0).astype(int) + zone_summary["mean_daily_published_completed_trips"] = ( + zone_summary["published_completed_trips"] + / zone_summary["panel_days"].replace(0, np.nan) + ) + zone_summary["mean_published_completed_trips_per_zone_hour"] = ( + zone_summary["published_completed_trips"] + / zone_summary["zone_hours"].replace(0, np.nan) + ) + zone_summary["share_of_all_published_completed_trips"] = ( + zone_summary["published_completed_trips"] / trip_total + ) + zone_summary["evidence_label"] = INCOME_EVIDENCE_LABEL + zone_summary["causal_claim"] = False + zone_summary = zone_summary.sort_values( + "panel_zone_id", + key=lambda series: pd.to_numeric(series, errors="coerce"), + ).reset_index(drop=True) + + indexed = monthly.set_index("income_group") + for required_group in ("low_income_area", "high_income_area"): + if required_group not in indexed.index: + raise ValueError("NYC income panel lacks a required high/low-income group") + low_rate = float( + indexed.loc["low_income_area", "mean_published_completed_trips_per_zone_hour"] + ) + high_rate = float( + indexed.loc["high_income_area", "mean_published_completed_trips_per_zone_hour"] + ) + classified_trips = int( + joined.loc[ + joined["income_group"].isin({"low_income_area", "high_income_area"}), + "published_completed_trips", + ].sum() + ) + sensitivity_indexed = sensitivity_monthly.set_index(sensitivity_group_column) + for required_group in ("low_income_area", "high_income_area"): + if required_group not in sensitivity_indexed.index: + raise ValueError("NYC income sensitivity lacks a required high/low-income group") + sensitivity_low_rate = float( + sensitivity_indexed.loc[ + "low_income_area", + "mean_published_completed_trips_per_zone_hour", + ] + ) + sensitivity_high_rate = float( + sensitivity_indexed.loc[ + "high_income_area", + "mean_published_completed_trips_per_zone_hour", + ] + ) + sensitivity_classified = joined[sensitivity_group_column].isin( + {"low_income_area", "high_income_area"} + ) + sensitivity_classified_trips = int( + joined.loc[sensitivity_classified, "published_completed_trips"].sum() + ) + primary_eligible = ( + joined["primary_income_classification_eligible"] + .astype("boolean") + .fillna(False) + .astype(bool) + ) + dominant_residential_eligible = ( + joined["dominant_nta_residential_eligible"] + .astype("boolean") + .fillna(False) + .astype(bool) + ) + dominant_nonresidential = ( + joined["dominant_nta_type"].notna() + & ~dominant_residential_eligible + ) + sensitivity_nonresidential_classified = ( + dominant_nonresidential & sensitivity_classified + ) + primary_classified = joined["income_group"].isin( + {"low_income_area", "high_income_area"} + ) + if (primary_classified & ~primary_eligible).any(): + raise ValueError("primary income classification contains an ineligible Taxi Zone") + if (primary_classified & dominant_nonresidential).any(): + raise ValueError("primary income classification contains a non-residential Taxi Zone") + + primary_groups: dict[str, dict[str, float | int | None]] = {} + for group in ("high_income_area", "low_income_area", "unclassified"): + if group in indexed.index: + row = indexed.loc[group] + group_trips = int(row["published_completed_trips"]) + primary_groups[group] = { + "panel_zones": int(row["panel_zones"]), + "published_completed_trips": group_trips, + "share_of_all_published_completed_trips": group_trips / trip_total, + "mean_published_completed_trips_per_zone_hour": _finite_or_none( + float(row["mean_published_completed_trips_per_zone_hour"]) + ), + } + else: + primary_groups[group] = { + "panel_zones": 0, + "published_completed_trips": 0, + "share_of_all_published_completed_trips": 0.0, + "mean_published_completed_trips_per_zone_hour": None, + } + + sensitivity_groups: dict[str, dict[str, float | int | None]] = {} + for group in ("high_income_area", "low_income_area", "unclassified"): + if group in sensitivity_indexed.index: + row = sensitivity_indexed.loc[group] + group_trips = int(row["published_completed_trips"]) + group_rate = _finite_or_none( + float(row["mean_published_completed_trips_per_zone_hour"]) + ) + sensitivity_groups[group] = { + "panel_zones": int(row["panel_zones"]), + "published_completed_trips": group_trips, + "share_of_all_published_completed_trips": group_trips / trip_total, + "mean_published_completed_trips_per_zone_hour": group_rate, + } + else: + sensitivity_groups[group] = { + "panel_zones": 0, + "published_completed_trips": 0, + "share_of_all_published_completed_trips": 0.0, + "mean_published_completed_trips_per_zone_hour": None, + } + + grouped_median_distance = ( + joined["grouped_median_household_income_usd"] + - joined["citywide_grouped_median_threshold_usd"] + ).abs() + threshold_proximity: dict[str, dict[str, float | int]] = {} + for threshold_usd in (1_000, 2_500, 5_000, 10_000): + near_threshold = primary_eligible & grouped_median_distance.le(threshold_usd) + near_trips = int(joined.loc[near_threshold, "published_completed_trips"].sum()) + threshold_proximity[f"within_{threshold_usd}_usd"] = { + "primary_eligible_panel_zones": int( + joined.loc[near_threshold, "panel_zone_id"].nunique() + ), + "published_completed_trips": near_trips, + "share_of_primary_classified_trips": ( + near_trips / classified_trips if classified_trips else 0.0 + ), + } + summary = { + "schema_version": INCOME_SCHEMA_VERSION, + "evidence_label": INCOME_EVIDENCE_LABEL, + "causal_claim": False, + "scope": { + "city": "New York City", + "pickup_month": cfg.start_date.strftime("%Y-%m"), + "income_source": "2022 ACS 5-year B19001 household income distribution", + "income_reference_period": "2018-2022 five-year estimates", + "population_claim": False, + "individual_income_claim": False, + }, + "definitions": { + "income_measure": ( + "grouped median calculated from spatially allocated B19001 household " + "income-bin counts; never a median of tract or NTA medians" + ), + "high_income_area": ( + "Primary-eligible Taxi Zone with dominant residential NTA and grouped " + "median greater than or equal to the aggregate NYC grouped median" + ), + "low_income_area": ( + "Primary-eligible Taxi Zone with dominant residential NTA and grouped " + "median below the aggregate NYC grouped median" + ), + "unclassified": ( + "no supported household distribution, including non-NYC/unknown zones " + "and every Taxi Zone whose dominant NTA is non-residential" + ), + "primary_residential_eligibility": ( + "dominant NTA has pre-specified NTAType 0 (residential) and the area-" + "allocated distribution meets the configured household minimum and " + f"residential Taxi Zone area share >= " + f"{cfg.minimum_residential_taxi_zone_area_share:g}" + ), + "all_zone_area_allocation_sensitivity": ( + "legacy classification based only on allocated households and grouped " + "median; retained as sensitivity and never used for the primary result" + ), + "allocation": ( + "NTA bin counts allocated by EPSG:6933 equal-area overlap, normalized " + "within NTA to conserve all sixteen B19001 bins" + ), + "grouped_median_top_coded": ( + "true means the grouped median falls in B19001's open >=$200,000 " + "bin; the numeric value is then a $200,000 lower bound" + ), + "area_allocated_B19001_fields": ( + "fractional ecological allocations of official NTA counts, not exact " + "Taxi Zone household counts" + ), + }, + "coverage": { + "panel_zone_rows": int(joined["panel_zone_id"].nunique()), + "official_taxi_zones_in_panel": int( + joined.loc[joined["official_taxi_zone"], "panel_zone_id"].nunique() + ), + "classified_panel_zones": int( + joined.loc[ + joined["income_group"] != "unclassified", + "panel_zone_id", + ].nunique() + ), + "published_completed_trips": int(trip_total), + "classified_published_completed_trips": classified_trips, + "classified_trip_coverage": classified_trips / trip_total, + "unclassified_published_completed_trips": int(trip_total) - classified_trips, + "observed_days": len(observed_dates), + "dominant_nonresidential_panel_zones": int( + joined.loc[dominant_nonresidential, "panel_zone_id"].nunique() + ), + "dominant_nonresidential_published_completed_trips": int( + joined.loc[ + dominant_nonresidential, + "published_completed_trips", + ].sum() + ), + }, + "associations": { + "mean_published_completed_trips_per_zone_hour_high_income_area": high_rate, + "mean_published_completed_trips_per_zone_hour_low_income_area": low_rate, + "high_minus_low_mean_published_completed_trips_per_zone_hour": high_rate - low_rate, + "high_to_low_mean_published_completed_trips_per_zone_hour_ratio": ( + high_rate / low_rate if low_rate else None + ), + }, + "primary_classification": { + "primary_result": True, + "residential_nta_type_codes": list(cfg.residential_nta_type_codes), + "minimum_allocated_households": cfg.minimum_allocated_households, + "minimum_residential_taxi_zone_area_share": ( + cfg.minimum_residential_taxi_zone_area_share + ), + "groups": primary_groups, + }, + "sensitivity": { + "all_zone_area_allocation": { + "primary_result": False, + "classification_rule": ( + "allocated households >= configured minimum; dominant NTA " + "residential eligibility intentionally ignored" + ), + "minimum_allocated_households": cfg.minimum_allocated_households, + "ignored_primary_residential_taxi_zone_area_share_threshold": ( + cfg.minimum_residential_taxi_zone_area_share + ), + "groups": sensitivity_groups, + "classified_panel_zones": int( + joined.loc[sensitivity_classified, "panel_zone_id"].nunique() + ), + "classified_published_completed_trips": sensitivity_classified_trips, + "classified_trip_coverage": sensitivity_classified_trips / trip_total, + "mean_published_completed_trips_per_zone_hour_high_income_area": ( + sensitivity_high_rate + ), + "mean_published_completed_trips_per_zone_hour_low_income_area": ( + sensitivity_low_rate + ), + "high_minus_low_mean_published_completed_trips_per_zone_hour": ( + sensitivity_high_rate - sensitivity_low_rate + ), + "high_to_low_mean_published_completed_trips_per_zone_hour_ratio": ( + sensitivity_high_rate / sensitivity_low_rate + if sensitivity_low_rate + else None + ), + "dominant_nonresidential_zones_classified": int( + joined.loc[ + sensitivity_nonresidential_classified, + "panel_zone_id", + ].nunique() + ), + "dominant_nonresidential_classified_published_completed_trips": int( + joined.loc[ + sensitivity_nonresidential_classified, + "published_completed_trips", + ].sum() + ), + } + }, + "classification_uncertainty": { + "zone_grouped_medians_are_point_estimates": True, + "zone_level_margin_of_error_propagated": False, + "nta_b19001_margins_of_error_retained": True, + "interpretation": ( + "Threshold proximity shows decisions most exposed to grouped-median " + "measurement error; it is not a confidence interval" + ), + "threshold_proximity": threshold_proximity, + }, + "conservation": { + "zone_trip_sum": int(zone_summary["published_completed_trips"].sum()), + "daily_group_trip_sum": int(daily["published_completed_trips"].sum()), + "monthly_group_trip_sum": int(monthly["published_completed_trips"].sum()), + "sensitivity_group_trip_sum": int( + sensitivity_monthly["published_completed_trips"].sum() + ), + "primary_classified_plus_unclassified_trip_sum": int( + joined["published_completed_trips"].sum() + ), + "primary_nonresidential_classified_zones": int( + joined.loc[ + primary_classified & dominant_nonresidential, + "panel_zone_id", + ].nunique() + ), + "passes": ( + int(zone_summary["published_completed_trips"].sum()) + == int(daily["published_completed_trips"].sum()) + == int(monthly["published_completed_trips"].sum()) + == int(sensitivity_monthly["published_completed_trips"].sum()) + and not (primary_classified & dominant_nonresidential).any() + ), + }, + "limitations": [ + "ACS B19001 measures household income by residence; it is not rider or driver individual income.", + "Area allocation assumes households are uniformly distributed within each NTA and introduces ecological measurement error.", + "ACS margins of error are retained at NTA level, but no exact margin of error is available for area-allocated Taxi Zone grouped medians.", + "Taxi Zone income groups use point estimates; threshold-proximity counts are diagnostics, not propagated margins of error or confidence intervals.", + "Published completed trips omit latent requests, unserved demand, and available drivers.", + "High-versus-low contrasts are observational descriptions confounded by land use, transit access, population, employment, time patterns, and other shocks.", + "The primary contrast excludes Taxi Zones dominated by airports, parks, cemeteries, facilities, Rikers Island, or other non-residential NTA types; the previous all-zone rule is sensitivity only.", + "Neither income effects, discrimination, causal demand response, nor individual behavior is identified.", + ], + } + if not summary["conservation"]["passes"]: + raise ValueError("income group tables do not conserve published trips") + return zone_summary, daily, monthly, summary + + +def _verified_panel_inputs( + panel_directory: Path, + data_manifest_path: Path, + project_root: Path, +) -> tuple[tuple[Path, ...], dict[str, Any], int]: + source_manifest = json.loads(data_manifest_path.read_text(encoding="utf-8")) + if ( + source_manifest.get("config", {}).get("source") != "nyc_hvfhv" + or source_manifest.get("config", {}).get("mode") != "full" + or source_manifest.get("metadata", {}).get("evidence_label") + != "descriptive_real_data" + or source_manifest.get("metadata", {}).get("causal_claim") is not False + ): + raise ValueError("income analysis requires the verified NYC full-data manifest") + panel_paths = tuple(sorted(panel_directory.rglob("*.parquet"))) + if not panel_paths: + raise FileNotFoundError("NYC full zone-time panel is unavailable") + declared: dict[Path, dict[str, Any]] = {} + for entry in source_manifest.get("files", []): + if not isinstance(entry, dict) or not isinstance(entry.get("path"), str): + raise ValueError("NYC data manifest contains an invalid file entry") + declared_path = Path(entry["path"]) + if declared_path.is_absolute(): + raise ValueError("NYC data manifest file paths must be project-relative") + if ".." in declared_path.parts: + raise ValueError("NYC data manifest file paths must not contain '..'") + resolved = (project_root / declared_path).resolve() + if not resolved.is_relative_to(project_root): + raise ValueError("NYC data manifest file path resolves outside project_root") + if resolved in declared: + raise ValueError("NYC data manifest declares a duplicate file path") + declared[resolved] = entry + declared_panel = {path for path in declared if path.is_relative_to(panel_directory)} + if set(panel_paths) != declared_panel: + raise ValueError("NYC income panel file set differs from the source manifest") + for path in panel_paths: + entry = declared[path] + if path.stat().st_size != entry.get("bytes") or sha256_file(path) != entry.get("sha256"): + raise ValueError(f"NYC income panel lineage mismatch: {path}") + expected_trips = int( + source_manifest["metadata"]["full_month_processing"]["row_conservation"][ + "zone_time_trip_sum" + ] + ) + return panel_paths, source_manifest, expected_trips + + +def _manifest_entry( + path: Path, + root: Path, + role: str, + **metadata: Any, +) -> dict[str, Any]: + return { + "role": role, + "path": _portable(path, root), + "bytes": path.stat().st_size, + "sha256": sha256_file(path), + **metadata, + } + + +def _entry_set_digest(entries: Sequence[Mapping[str, Any]]) -> str: + return hashlib.sha256( + json.dumps(list(entries), sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + + +def write_nyc_income_bundle( + taxi_zone_zip_path: str | Path, + nta_geojson_path: str | Path, + tract_to_nta_path: str | Path, + acs_b19001_path: str | Path, + panel_directory: str | Path, + data_manifest_path: str | Path, + output_directory: str | Path, + *, + project_root: str | Path, + config: NYCIncomeConfig | None = None, +) -> NYCIncomeArtifacts: + """Publish an atomic, fail-closed, hash-manifested NYC income bundle.""" + + cfg = config or NYCIncomeConfig() + root = Path(project_root).resolve() + taxi_path = Path(taxi_zone_zip_path).resolve() + nta_path = Path(nta_geojson_path).resolve() + tract_path = Path(tract_to_nta_path).resolve() + acs_path = Path(acs_b19001_path).resolve() + panel_root = Path(panel_directory).resolve() + source_manifest_path = Path(data_manifest_path).resolve() + output = Path(output_directory).resolve() + for path in (taxi_path, nta_path, tract_path, acs_path, panel_root, source_manifest_path, output): + _portable(path, root) + output.mkdir(parents=True, exist_ok=True) + marker = output / "NYC_INCOME_INCOMPLETE.json" + manifest_path = output / "manifest.json" + manifest_path.unlink(missing_ok=True) + _atomic_json( + { + "status": "incomplete", + "evidence_label": INCOME_EVIDENCE_LABEL, + "causal_claim": False, + "interpretation": "No NYC income artifact is valid while this marker exists.", + }, + marker, + ) + + _require_pinned_file(taxi_path, cfg.expected_taxi_sha256, "TLC Taxi Zone source") + _require_pinned_file(nta_path, cfg.expected_nta_sha256, "NYC NTA source") + _require_pinned_file(tract_path, cfg.expected_tract_to_nta_sha256, "NYC tract-to-NTA source") + _require_pinned_file(acs_path, cfg.expected_acs_sha256, "Census ACS B19001 source") + if not source_manifest_path.is_file(): + raise FileNotFoundError(source_manifest_path) + panel_paths, _source_manifest, expected_trips = _verified_panel_inputs( + panel_root, + source_manifest_path, + root, + ) + + crosswalk, geometry_checks = build_taxi_zone_nta_crosswalk(taxi_path, nta_path, cfg) + nta_codes = [ + str(feature["properties"]["nta2020"]) + for feature in json.loads(nta_path.read_text(encoding="utf-8"))["features"] + ] + nta_income, acs_checks = aggregate_acs_b19001_to_nta( + tract_path, + acs_path, + nta_codes, + cfg, + ) + zone_income, allocation_checks = allocate_nta_income_to_taxi_zones( + crosswalk, + nta_income, + float(acs_checks["citywide_grouped_median_household_income_usd"]), + cfg, + ) + zone_summary, daily, monthly, summary = income_trip_descriptions( + panel_paths, + zone_income, + cfg, + ) + if summary["conservation"]["zone_trip_sum"] != expected_trips: + raise ValueError("NYC income descriptions do not conserve source-manifest trips") + summary["spatial_mapping"] = geometry_checks + summary["acs_aggregation"] = acs_checks + summary["zone_allocation"] = allocation_checks + summary["provenance"] = { + "tlc_taxi_zone_url": TAXI_ZONES_URL, + "tlc_taxi_zone_path": _portable(taxi_path, root), + "tlc_taxi_zone_sha256": sha256_file(taxi_path), + "nyc_nta2020_url": NTA2020_URL, + "nyc_nta2020_path": _portable(nta_path, root), + "nyc_nta2020_sha256": sha256_file(nta_path), + "nyc_tract_to_nta_url": TRACT_TO_NTA_URL, + "nyc_tract_to_nta_path": _portable(tract_path, root), + "nyc_tract_to_nta_sha256": sha256_file(tract_path), + "acs_b19001_parent_url": ACS_B19001_PARENT_URL, + "acs_b19001_parent_bytes": ACS_B19001_PARENT_BYTES, + "acs_b19001_parent_sha256": ACS_B19001_PARENT_SHA256, + "acs_nyc_slice_path": _portable(acs_path, root), + "acs_nyc_slice_sha256": sha256_file(acs_path), + "acs_nyc_slice_derivation": ( + "header plus GEO_ID rows matching NYC state/county tract prefixes " + "36005, 36047, 36061, 36081, or 36085; bytes otherwise unchanged" + ), + "nyc_data_manifest_path": _portable(source_manifest_path, root), + "nyc_data_manifest_sha256": sha256_file(source_manifest_path), + "panel_files_verified": len(panel_paths), + "hashes_recomputed": True, + } + zone_summary = zone_summary.rename( + columns={column: f"area_allocated_{column}" for column in ESTIMATE_COLUMNS} + ) + + with tempfile.TemporaryDirectory(prefix=".nyc-income-", dir=output.parent) as temporary_dir: + stage = Path(temporary_dir) + staged_crosswalk = _atomic_csv(crosswalk, stage / "taxi_zone_nta_crosswalk.csv") + staged_nta = _atomic_csv(nta_income, stage / "nta_income_summary.csv") + staged_zone = _atomic_csv(zone_summary, stage / "zone_income_summary.csv") + staged_daily = _atomic_csv(daily, stage / "income_group_daily.csv") + staged_monthly = _atomic_csv(monthly, stage / "income_group_monthly.csv") + staged_summary = _atomic_json(summary, stage / "income_associations.json") + output_specs = ( + (staged_crosswalk, output / staged_crosswalk.name, "taxi_zone_nta_crosswalk"), + (staged_nta, output / staged_nta.name, "nta_b19001_distribution_summary"), + (staged_zone, output / staged_zone.name, "taxi_zone_income_and_trip_summary"), + (staged_daily, output / staged_daily.name, "daily_income_group_description"), + (staged_monthly, output / staged_monthly.name, "monthly_income_group_description"), + (staged_summary, output / staged_summary.name, "income_association_summary"), + ) + file_entries = [ + { + "role": role, + "path": _portable(destination, root), + "bytes": staged.stat().st_size, + "sha256": sha256_file(staged), + "evidence_label": INCOME_EVIDENCE_LABEL, + "causal_claim": False, + } + for staged, destination, role in output_specs + ] + input_entries = [ + _manifest_entry( + taxi_path, + root, + "official_tlc_taxi_zone_geometry", + source_url=TAXI_ZONES_URL, + source_type="official_observed_geometry", + ), + _manifest_entry( + nta_path, + root, + "official_nyc_nta2020_geometry", + source_url=NTA2020_URL, + source_type="official_observed_geometry", + ), + _manifest_entry( + tract_path, + root, + "official_nyc_tract2020_to_nta2020_mapping", + source_url=TRACT_TO_NTA_URL, + source_type="official_observed_crosswalk", + ), + _manifest_entry( + acs_path, + root, + "official_census_acs_2022_5yr_b19001_nyc_tract_slice", + source_url=ACS_B19001_PARENT_URL, + source_type="official_observed_estimates", + parent_bytes=ACS_B19001_PARENT_BYTES, + parent_sha256=ACS_B19001_PARENT_SHA256, + ), + _manifest_entry( + source_manifest_path, + root, + "verified_nyc_full_data_manifest", + source_type="descriptive_real_data_lineage", + ), + ] + input_entries.extend( + _manifest_entry( + panel_path, + root, + "nyc_full_zone_time_panel", + source_type="descriptive_real_data_panel", + ) + for panel_path in panel_paths + ) + staged_manifest = _atomic_json( + { + "schema_version": INCOME_SCHEMA_VERSION, + "artifact_type": "nyc_income_descriptive_bundle", + "evidence_label": INCOME_EVIDENCE_LABEL, + "causal_claim": False, + "portable_paths": True, + "files": file_entries, + "inputs": input_entries, + "declared_file_set_sha256": _entry_set_digest(file_entries), + "declared_input_set_sha256": _entry_set_digest(input_entries), + "checks": { + "official_source_hashes_match": True, + "taxi_location_ids_unique_and_complete": True, + "tract_b19001_totals_equal_sixteen_bins": True, + "median_of_medians_used": False, + "equal_area_crs": cfg.equal_area_crs, + "household_distribution_conserved": True, + "published_trip_conservation": True, + "panel_files_verified": len(panel_paths), + "classified_trip_coverage": summary["coverage"]["classified_trip_coverage"], + "residential_nta_type_codes": list( + cfg.residential_nta_type_codes + ), + "minimum_allocated_households": cfg.minimum_allocated_households, + "minimum_residential_taxi_zone_area_share": ( + cfg.minimum_residential_taxi_zone_area_share + ), + "dominant_nonresidential_primary_classified_zones": summary[ + "conservation" + ]["primary_nonresidential_classified_zones"], + "dominant_nonresidential_primary_unclassified": ( + summary["conservation"][ + "primary_nonresidential_classified_zones" + ] + == 0 + ), + "all_zone_classification_is_sensitivity_only": True, + "zone_grouped_medians_are_point_estimates": True, + "zone_level_margin_of_error_propagated": False, + "ecological_noncausal_contract": True, + }, + }, + stage / "manifest.json", + ) + for staged, destination, _role in output_specs: + staged.replace(destination) + staged_manifest.replace(manifest_path) + + if not manifest_path.is_file(): + raise RuntimeError("NYC income bundle completed without a manifest") + marker.unlink(missing_ok=True) + return NYCIncomeArtifacts( + crosswalk_path=output / "taxi_zone_nta_crosswalk.csv", + nta_income_path=output / "nta_income_summary.csv", + zone_income_path=output / "zone_income_summary.csv", + daily_path=output / "income_group_daily.csv", + monthly_path=output / "income_group_monthly.csv", + summary_path=output / "income_associations.json", + manifest_path=manifest_path, + ) + + +__all__ = [ + "ACS_B19001_NYC_SLICE_SHA256", + "ACS_B19001_PARENT_SHA256", + "ACS_B19001_PARENT_URL", + "INCOME_EVIDENCE_LABEL", + "NYCIncomeArtifacts", + "NYCIncomeConfig", + "NTA2020_SHA256", + "NTA2020_URL", + "TAXI_ZONES_SHA256", + "TAXI_ZONES_URL", + "TRACT_TO_NTA_SHA256", + "TRACT_TO_NTA_URL", + "aggregate_acs_b19001_to_nta", + "allocate_nta_income_to_taxi_zones", + "build_taxi_zone_nta_crosswalk", + "income_trip_descriptions", + "write_nyc_income_bundle", +] diff --git a/CasualLab/src/casuallab/nyc_simulation.py b/CasualLab/src/casuallab/nyc_simulation.py new file mode 100644 index 0000000000000000000000000000000000000000..a96e9681607a39e5062897ed81ed7c4febaa4390 --- /dev/null +++ b/CasualLab/src/casuallab/nyc_simulation.py @@ -0,0 +1,1184 @@ +"""Fail-closed NYC descriptive anchors for semi-synthetic simulations. + +This module does not fit a causal or structural model. It verifies a published +NYC calibration bundle and its source-data lineage, then translates a small set +of observable completed-trip moments into transparent simulator initializers. +Every response, interference, persistence, supply, substitution, and welfare +quantity remains an explicit assumption supplied by a :class:`SimulationConfig` +template. +""" + +from __future__ import annotations + +import calendar +import csv +import hashlib +import json +import math +import re +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, replace +from datetime import datetime +from pathlib import Path +from typing import Any + +import numpy as np + +from casuallab.config import SimulationConfig +from casuallab.data import sha256_file + +DESCRIPTIVE_EVIDENCE_LABEL = "descriptive_real_data" +ANCHOR_EVIDENCE_LABEL = "semi_synthetic_descriptive_anchor" +ANCHOR_SCHEMA_VERSION = "1.0.0" + +CAUSAL_ASSUMPTION_FIELDS = ( + "treatment_version", + "discount_rate", + "incentive_per_driver", + "reference_incentive_per_driver", + "direct_demand_effect", + "direct_supply_effect", + "spillover_strength", + "persistence", + "rider_substitution", + "driver_mobility", + "capacity_per_driver", + "matching_efficiency", + "rider_value", + "operating_cost_per_trip", + "wait_disutility_per_minute", +) + +NO_CAUSAL_CLAIM = ( + "NYC published completed trips identify neither latent demand nor available supply " + "and do not identify treatment response, supply response, spillovers, persistence, " + "substitution, or welfare. Those quantities remain explicit simulation assumptions." +) + +_REQUIRED_CALIBRATION_CHECKS = frozenset( + { + "graph_conserves_od", + "od_conserves_clean", + "od_counts_positive", + "od_keys_unique", + "raw_equals_clean", + "raw_rows_declared", + "source_manifest_valid", + "variance_trip_sum_conserves", + "zone_conserves_clean", + "zone_keys_unique", + } +) +_HASH_PATTERN = re.compile(r"[0-9a-f]{64}") + + +@dataclass(frozen=True, slots=True) +class NYCSimulationAnchorSettings: + """Deterministic target geometry for a semi-synthetic NYC proposal. + + ``None`` preserves the complete observed zone or hourly dimension. Smaller + values declare a simulation-size choice; the builder does not claim that it + selected a representative subset of observed zones or hours. + """ + + target_n_zones: int | None = None + target_n_periods: int | None = None + seed: int = 202503 + + def __post_init__(self) -> None: + for name in ("target_n_zones", "target_n_periods"): + value = getattr(self, name) + if value is not None and ( + isinstance(value, bool) or not isinstance(value, int) or value < 1 + ): + raise ValueError(f"{name} must be a positive integer when supplied") + if isinstance(self.seed, bool) or not isinstance(self.seed, int): + raise ValueError("seed must be an integer") + + def to_dict(self) -> dict[str, int | None]: + return { + "target_n_zones": self.target_n_zones, + "target_n_periods": self.target_n_periods, + "seed": self.seed, + } + + +def _object(value: Any, label: str) -> dict[str, Any]: + if not isinstance(value, Mapping): + raise ValueError(f"{label} must be a JSON object") + return dict(value) + + +def _load_object(path: Path, label: str) -> dict[str, Any]: + if not path.is_file(): + raise FileNotFoundError(path) + try: + return _object(json.loads(path.read_text(encoding="utf-8")), label) + except json.JSONDecodeError as exc: + raise ValueError(f"{label} is not valid JSON: {path}") from exc + + +def _integer(payload: Mapping[str, Any], key: str, label: str, *, positive: bool = False) -> int: + value = payload.get(key) + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError(f"{label}.{key} must be an integer") + if positive and value < 1: + raise ValueError(f"{label}.{key} must be positive") + return value + + +def _number( + payload: Mapping[str, Any], + key: str, + label: str, + *, + positive: bool = False, + nonnegative: bool = False, +) -> float: + value = payload.get(key) + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError(f"{label}.{key} must be numeric") + result = float(value) + if not math.isfinite(result): + raise ValueError(f"{label}.{key} must be finite") + if positive and result <= 0: + raise ValueError(f"{label}.{key} must be positive") + if nonnegative and result < 0: + raise ValueError(f"{label}.{key} cannot be negative") + return result + + +def _relative_path(value: Any, label: str) -> Path: + if not isinstance(value, str) or not value.strip(): + raise ValueError(f"{label} must be a non-empty relative path") + path = Path(value) + if path.is_absolute() or ".." in path.parts: + raise ValueError(f"{label} must be portable and cannot escape its manifest root") + return path + + +def _resolve_within(root: Path, relative: Path, label: str) -> Path: + base = root.resolve() + resolved = (base / relative).resolve() + try: + resolved.relative_to(base) + except ValueError as exc: + raise ValueError(f"{label} escapes its manifest root") from exc + return resolved + + +def _expected_hash(value: Any, label: str) -> str: + if not isinstance(value, str) or _HASH_PATTERN.fullmatch(value) is None: + raise ValueError(f"{label} must be a lowercase SHA-256 digest") + return value + + +def _manifest_entries(payload: Mapping[str, Any], root: Path, label: str) -> dict[Path, dict[str, Any]]: + entries = payload.get("files") + if not isinstance(entries, list) or not entries: + raise ValueError(f"{label}.files must be a non-empty list") + verified: dict[Path, dict[str, Any]] = {} + for index, raw_entry in enumerate(entries): + entry = _object(raw_entry, f"{label}.files[{index}]") + relative = _relative_path(entry.get("path"), f"{label}.files[{index}].path") + resolved = _resolve_within(root, relative, f"{label}.files[{index}].path") + if resolved in verified: + raise ValueError(f"{label} contains a duplicate file path: {relative}") + expected_bytes = _integer(entry, "bytes", f"{label}.files[{index}]") + if expected_bytes < 0: + raise ValueError(f"{label}.files[{index}].bytes cannot be negative") + expected_sha = _expected_hash( + entry.get("sha256"), f"{label}.files[{index}].sha256" + ) + if not resolved.is_file(): + raise FileNotFoundError(f"{label} file is missing: {resolved}") + if resolved.stat().st_size != expected_bytes: + raise ValueError(f"{label} byte mismatch: {relative}") + if sha256_file(resolved) != expected_sha: + raise ValueError(f"{label} SHA-256 mismatch: {relative}") + verified[resolved] = entry + return verified + + +def _declared_file_set_sha256(entries: Sequence[Mapping[str, Any]]) -> str: + canonical = json.dumps( + [ + { + "path": str(entry.get("path")), + "bytes": int(entry.get("bytes", -1)), + "sha256": str(entry.get("sha256")), + } + for entry in entries + ], + sort_keys=True, + separators=(",", ":"), + ).encode() + return hashlib.sha256(canonical).hexdigest() + + +def _require_descriptive_scope(payload: Mapping[str, Any], label: str) -> None: + if payload.get("evidence_label") != DESCRIPTIVE_EVIDENCE_LABEL: + raise ValueError(f"{label} must be labeled {DESCRIPTIVE_EVIDENCE_LABEL}") + if payload.get("causal_claim") is not False: + raise ValueError(f"{label} must declare causal_claim=false") + + +def _validate_source_record(record: Mapping[str, Any], label: str) -> None: + required_true = ( + "all_valid", + "hashes_recomputed", + "queried_files_listed", + "scope_is_full_nyc_descriptive", + ) + invalid = [key for key in required_true if record.get(key) is not True] + if invalid: + raise ValueError(f"{label} has invalid lineage flags: {invalid}") + if record.get("mismatches") != []: + raise ValueError(f"{label}.mismatches must be empty") + _relative_path(record.get("path"), f"{label}.path") + _expected_hash(record.get("sha256"), f"{label}.sha256") + _expected_hash( + record.get("declared_file_set_sha256"), + f"{label}.declared_file_set_sha256", + ) + _integer(record, "entries", label, positive=True) + + +def _source_project_root( + calibration_path: Path, + source_manifest_relative: Path, + project_root: str | Path | None, +) -> tuple[Path, str]: + if project_root is not None: + root = Path(project_root).resolve() + if not root.is_dir(): + raise FileNotFoundError(root) + return root, "explicit" + + candidates = (calibration_path.parent, *calibration_path.parents) + for candidate in candidates: + root = candidate.resolve() + resolved = _resolve_within(root, source_manifest_relative, "source manifest path") + if resolved.is_file(): + return root, "inferred_from_portable_source_manifest_path" + raise FileNotFoundError( + "could not infer project_root from the portable source-data manifest path; " + "supply project_root explicitly" + ) + + +def _verify_integrity( + calibration_path: Path, + manifest_path: Path, + project_root: str | Path | None, +) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any], dict[str, Any]]: + calibration = _load_object(calibration_path, "NYC calibration") + bundle_manifest = _load_object(manifest_path, "NYC calibration manifest") + + for payload, label in ( + (calibration, "NYC calibration"), + (bundle_manifest, "NYC calibration manifest"), + ): + if payload.get("schema_version") != ANCHOR_SCHEMA_VERSION: + raise ValueError(f"{label} has an unsupported schema_version") + _require_descriptive_scope(payload, label) + if bundle_manifest.get("portable_paths") is not True: + raise ValueError("NYC calibration manifest must declare portable_paths=true") + if calibration.get("bundle_valid") is not True: + raise ValueError("NYC calibration bundle_valid is not true") + + incomplete_marker = calibration_path.parent.with_name( + f"{calibration_path.parent.name}_INCOMPLETE.json" + ) + if incomplete_marker.exists(): + raise RuntimeError("NYC calibration bundle is marked incomplete") + + bundle_files = _manifest_entries( + bundle_manifest, manifest_path.parent, "NYC calibration manifest" + ) + if calibration_path.resolve() not in bundle_files: + raise ValueError("NYC calibration is not covered by its bundle manifest") + + calibration_provenance = _object( + calibration.get("provenance"), "NYC calibration.provenance" + ) + calibration_source = _object( + calibration_provenance.get("source_data_manifest"), + "NYC calibration.provenance.source_data_manifest", + ) + manifest_source = _object( + bundle_manifest.get("source_data_manifest"), + "NYC calibration manifest.source_data_manifest", + ) + _validate_source_record(calibration_source, "NYC calibration source lineage") + _validate_source_record(manifest_source, "NYC calibration manifest source lineage") + if calibration_source != manifest_source: + raise ValueError("calibration and bundle manifest source lineage records disagree") + + source_relative = _relative_path( + calibration_source["path"], "NYC calibration source lineage.path" + ) + root, root_resolution = _source_project_root( + calibration_path, source_relative, project_root + ) + source_manifest_path = _resolve_within(root, source_relative, "source manifest path") + if source_manifest_path.parent.joinpath("NYC_FULL_INCOMPLETE.json").exists(): + raise RuntimeError("NYC source-data pipeline is marked incomplete") + actual_source_manifest_sha = sha256_file(source_manifest_path) + if actual_source_manifest_sha != calibration_source["sha256"]: + raise ValueError("NYC source-data manifest SHA-256 disagrees with calibration lineage") + + source_manifest = _load_object(source_manifest_path, "NYC source-data manifest") + if source_manifest.get("schema_version") != ANCHOR_SCHEMA_VERSION: + raise ValueError("NYC source-data manifest has an unsupported schema_version") + source_config = _object(source_manifest.get("config"), "NYC source-data manifest.config") + source_metadata = _object( + source_manifest.get("metadata"), "NYC source-data manifest.metadata" + ) + if source_config.get("source") != "nyc_hvfhv" or source_config.get("mode") != "full": + raise ValueError("NYC source-data manifest must declare source=nyc_hvfhv and mode=full") + if source_metadata.get("evidence_label") != DESCRIPTIVE_EVIDENCE_LABEL: + raise ValueError("NYC source-data manifest has an incompatible evidence label") + if source_metadata.get("causal_claim") is not False: + raise ValueError("NYC source-data manifest must declare causal_claim=false") + + source_entries = source_manifest.get("files") + if not isinstance(source_entries, list): + raise ValueError("NYC source-data manifest.files must be a list") + declared_digest = _declared_file_set_sha256( + [_object(item, "NYC source-data manifest file entry") for item in source_entries] + ) + if declared_digest != calibration_source["declared_file_set_sha256"]: + raise ValueError("NYC source-data declared file-set SHA-256 disagrees with lineage") + if len(source_entries) != calibration_source["entries"]: + raise ValueError("NYC source-data manifest entry count disagrees with lineage") + source_files = _manifest_entries(source_manifest, root, "NYC source-data manifest") + + integrity = { + "all_valid": True, + "bundle_manifest_sha256": sha256_file(manifest_path), + "calibration_sha256": sha256_file(calibration_path), + "bundle_files_verified": len(bundle_files), + "source_data_manifest_sha256": actual_source_manifest_sha, + "source_declared_file_set_sha256": declared_digest, + "source_files_verified": len(source_files), + "project_root_resolution": root_resolution, + "hashes_recomputed": True, + } + return calibration, source_manifest, integrity, bundle_files + + +def _validate_full_month_scope( + calibration: Mapping[str, Any], source_manifest: Mapping[str, Any] +) -> tuple[int, int, int, int]: + scope = _object(calibration.get("scope"), "NYC calibration.scope") + if scope.get("source") != "nyc_hvfhv" or scope.get("population_claim") is not False: + raise ValueError("NYC calibration scope is not full descriptive HVFHV evidence") + if scope.get("unit") != "published_completed_trip_record_and_pickup_zone_hour": + raise ValueError("NYC calibration has an incompatible unit of observation") + try: + pickup_min = datetime.fromisoformat(str(scope["pickup_min"])) + pickup_max = datetime.fromisoformat(str(scope["pickup_max"])) + except (KeyError, ValueError) as exc: + raise ValueError("NYC calibration pickup coverage is malformed") from exc + final_day = calendar.monthrange(pickup_min.year, pickup_min.month)[1] + full_calendar_month = ( + pickup_min.year == pickup_max.year + and pickup_min.month == pickup_max.month + and pickup_min.day == 1 + and pickup_min.hour == pickup_min.minute == pickup_min.second == 0 + and pickup_max.day == final_day + and pickup_max.hour == 23 + and pickup_max.minute == pickup_max.second == 59 + ) + if not full_calendar_month: + raise ValueError("NYC calibration does not cover one complete calendar month") + calendar_hours = final_day * 24 + + checks = _object(calibration.get("checks"), "NYC calibration.checks") + missing_checks = sorted(_REQUIRED_CALIBRATION_CHECKS.difference(checks)) + if missing_checks: + raise ValueError(f"NYC calibration checks are incomplete: {missing_checks}") + failed_checks = sorted(key for key, value in checks.items() if value is not True) + if failed_checks: + raise ValueError(f"NYC calibration checks failed: {failed_checks}") + + conservation = _object( + calibration.get("conservation"), "NYC calibration.conservation" + ) + zones = _integer(conservation, "zones", "NYC calibration.conservation", positive=True) + periods = _integer( + conservation, "periods", "NYC calibration.conservation", positive=True + ) + panel_cells = _integer( + conservation, "zone_rows", "NYC calibration.conservation", positive=True + ) + clean_rows = _integer( + conservation, "clean_rows", "NYC calibration.conservation", positive=True + ) + if periods != calendar_hours or panel_cells != zones * periods: + raise ValueError("NYC calibration panel geometry is inconsistent with calendar coverage") + conserved = ( + _integer(conservation, "raw_rows_declared", "NYC calibration.conservation") + == clean_rows + == _integer(conservation, "zone_trip_sum", "NYC calibration.conservation") + == _integer(conservation, "od_trip_sum", "NYC calibration.conservation") + ) + if not conserved: + raise ValueError("NYC calibration row conservation is inconsistent") + + source_config = _object(source_manifest.get("config"), "NYC source-data manifest.config") + source_metadata = _object( + source_manifest.get("metadata"), "NYC source-data manifest.metadata" + ) + full_month = _object( + source_metadata.get("full_month_processing"), + "NYC source-data manifest.metadata.full_month_processing", + ) + row_conservation = _object( + full_month.get("row_conservation"), + "NYC source-data manifest full-month row_conservation", + ) + if ( + source_config.get("panel_frequency") != "1h" + or source_config.get("complete_panel_grid") is not True + or source_config.get("nyc_year") != pickup_min.year + or source_config.get("nyc_months") != [pickup_min.month] + or full_month.get("complete_calendar_coverage") is not True + or full_month.get("configured_date_hours") != periods + or full_month.get("observed_date_hours") != periods + or row_conservation.get("passes") is not True + ): + raise ValueError("NYC source-data manifest does not certify complete hourly-month scope") + return zones, periods, panel_cells, clean_rows + + +def _temporal_diagnostics( + calibration: Mapping[str, Any], + calibration_path: Path, + bundle_files: Mapping[Path, Mapping[str, Any]], +) -> list[dict[str, Any]]: + associations = _object( + calibration.get("temporal_associations"), "NYC calibration.temporal_associations" + ) + if associations.get("evidence_label") != DESCRIPTIVE_EVIDENCE_LABEL: + raise ValueError("NYC temporal associations have an incompatible evidence label") + relative = _relative_path( + associations.get("file"), "NYC calibration.temporal_associations.file" + ) + source = _resolve_within( + calibration_path.parent, relative, "NYC temporal associations file" + ) + if source not in bundle_files: + raise ValueError("NYC temporal associations are not covered by the bundle manifest") + declared_lags = associations.get("lags_hours") + if not isinstance(declared_lags, list) or not declared_lags: + raise ValueError("NYC temporal association lags_hours must be a non-empty list") + + required = { + "lag_hours", + "exact_lag_support_pairs", + "support_share", + "pooled_trip_count_correlation", + "within_zone_centered_correlation", + "evidence_label", + "interpretation_warning", + } + diagnostics: list[dict[str, Any]] = [] + with source.open(encoding="utf-8", newline="") as handle: + reader = csv.DictReader(handle) + if reader.fieldnames is None or not required.issubset(reader.fieldnames): + raise ValueError("NYC temporal association CSV has an incompatible schema") + for row in reader: + if row["evidence_label"] != DESCRIPTIVE_EVIDENCE_LABEL: + raise ValueError("NYC temporal association row has an incompatible evidence label") + try: + lag = int(row["lag_hours"]) + support = int(row["exact_lag_support_pairs"]) + support_share = float(row["support_share"]) + pooled = float(row["pooled_trip_count_correlation"]) + within_zone = float(row["within_zone_centered_correlation"]) + except (TypeError, ValueError) as exc: + raise ValueError("NYC temporal association row contains malformed numbers") from exc + values = (support_share, pooled, within_zone) + if ( + lag < 1 + or support < 1 + or not all(math.isfinite(value) for value in values) + or not 0 <= support_share <= 1 + or not -1 <= pooled <= 1 + or not -1 <= within_zone <= 1 + ): + raise ValueError("NYC temporal association row contains invalid values") + diagnostics.append( + { + "lag_hours": lag, + "exact_lag_support_pairs": support, + "support_share": support_share, + "pooled_trip_count_correlation": pooled, + "within_zone_centered_correlation": within_zone, + "evidence_label": DESCRIPTIVE_EVIDENCE_LABEL, + "interpretation": row["interpretation_warning"], + "assigned_to_simulator_persistence": False, + } + ) + if sorted(item["lag_hours"] for item in diagnostics) != sorted(declared_lags): + raise ValueError("NYC temporal association rows disagree with declared lags") + return sorted(diagnostics, key=lambda item: item["lag_hours"]) + + +def _anchor_moments( + calibration: Mapping[str, Any], zones: int, periods: int, panel_cells: int, trips: int +) -> dict[str, float | int]: + moments = _object( + calibration.get("trip_level_descriptive_moments"), + "NYC calibration.trip_level_descriptive_moments", + ) + if _integer(moments, "trip_rows", "NYC calibration trip moments") != trips: + raise ValueError("NYC trip moments disagree with conserved trip rows") + fare = _object(moments.get("fare"), "NYC calibration fare moments") + wait = _object( + moments.get("request_to_pickup_wait_minutes"), "NYC calibration wait moments" + ) + if ( + fare.get("evidence_label") != DESCRIPTIVE_EVIDENCE_LABEL + or wait.get("evidence_label") != DESCRIPTIVE_EVIDENCE_LABEL + or wait.get("available") is not True + ): + raise ValueError("NYC fare or wait moments have incompatible evidence metadata") + base_fare = _number(fare, "mean", "NYC calibration fare moments", positive=True) + wait_mean = _number(wait, "mean", "NYC calibration wait moments", positive=True) + wait_median = _number(wait, "p50", "NYC calibration wait moments", positive=True) + + variance = _object( + calibration.get("zone_hour_variance_decomposition"), + "NYC calibration.zone_hour_variance_decomposition", + ) + if variance.get("evidence_label") != DESCRIPTIVE_EVIDENCE_LABEL: + raise ValueError("NYC variance decomposition has an incompatible evidence label") + if ( + _integer(variance, "zones", "NYC variance decomposition") != zones + or _integer(variance, "periods", "NYC variance decomposition") != periods + or _integer(variance, "panel_cells", "NYC variance decomposition") != panel_cells + or _integer(variance, "total_completed_trips", "NYC variance decomposition") != trips + ): + raise ValueError("NYC variance decomposition disagrees with panel conservation") + occupied = _integer(variance, "occupied_cells", "NYC variance decomposition") + if not 0 < occupied <= panel_cells: + raise ValueError("NYC occupied-cell count is invalid") + mean_trips = _number( + variance, + "mean_completed_trips_per_zone_hour", + "NYC variance decomposition", + positive=True, + ) + between_zone = _number( + variance, + "between_zone_component", + "NYC variance decomposition", + nonnegative=True, + ) + between_hour = _number( + variance, + "between_hour_of_day_component", + "NYC variance decomposition", + nonnegative=True, + ) + total_variance = _number( + variance, "total_cell_variance", "NYC variance decomposition", nonnegative=True + ) + zone_share = _number( + variance, + "icc_like_between_zone_share", + "NYC variance decomposition", + nonnegative=True, + ) + hour_share = _number( + variance, + "between_hour_of_day_share", + "NYC variance decomposition", + nonnegative=True, + ) + if zone_share > 1 or hour_share > 1: + raise ValueError("NYC descriptive variance shares must lie in [0, 1]") + if not math.isclose(mean_trips * panel_cells, trips, rel_tol=1e-10, abs_tol=1e-6): + raise ValueError("NYC mean completed-trip scale does not conserve monthly trips") + if total_variance > 0 and ( + not math.isclose(between_zone / total_variance, zone_share, rel_tol=1e-8) + or not math.isclose(between_hour / total_variance, hour_share, rel_tol=1e-8) + ): + raise ValueError("NYC descriptive variance components and shares disagree") + + zone_relative_sd = math.sqrt(between_zone) / mean_trips + zone_lognormal_sd_proxy = math.sqrt(math.log1p(zone_relative_sd**2)) + return { + "base_demand_completed_trip_proxy": mean_trips, + "base_fare_published_mean": base_fare, + "base_wait_published_mean": wait_mean, + "base_wait_published_median": wait_median, + "zone_relative_completed_trip_sd": zone_relative_sd, + "zone_lognormal_sd_initialization_proxy": zone_lognormal_sd_proxy, + "hour_of_day_relative_completed_trip_sd": math.sqrt(between_hour) / mean_trips, + "total_cell_relative_completed_trip_sd": math.sqrt(total_variance) / mean_trips, + "icc_like_between_zone_share": zone_share, + "between_hour_of_day_share": hour_share, + "occupied_cells": occupied, + } + + +def _simulated_control_moments(config: SimulationConfig) -> dict[str, float]: + """Return deterministic zero-treatment scale and variance shares. + + This is the zero-treatment specialization of the simulator equations. It + intentionally avoids constructing randomized assignments and the many + treatment counterfactuals produced by ``simulate_market``: none of those can + affect the control path, and doing so makes the full 262 x 744 NYC geometry + unnecessarily expensive. + """ + + from casuallab.simulator import _make_exogenous_state + + frame = _make_exogenous_state(config) + latent_demand = frame["baseline_demand"].to_numpy(dtype=float) + available_drivers = frame["baseline_supply"].to_numpy(dtype=float) + service_capacity = ( + available_drivers * config.capacity_per_driver * config.matching_efficiency + ) + capacity_ratio = service_capacity / np.maximum(latent_demand, 1e-12) + trips = latent_demand * -np.expm1(-capacity_ratio) + wait_minutes = config.base_wait_minutes * np.power( + latent_demand / np.maximum(service_capacity, 1e-12), 0.70 + ) + wait_minutes = np.clip(wait_minutes, 0.25, 120.0) + grand_mean = float(np.mean(trips)) + total_variance = float(np.var(trips, ddof=0)) + + def between_share(group: str) -> float: + grouped = frame.assign(_trips=trips).groupby(group, observed=True)["_trips"].agg( + ["size", "mean"] + ) + component = float( + (grouped["size"] * (grouped["mean"] - grand_mean) ** 2).sum() + / len(frame) + ) + return component / total_variance if total_variance > 0 else 0.0 + + return { + "mean_completed_trips": grand_mean, + "mean_wait_minutes": float(np.mean(wait_minutes)), + "between_zone_share": between_share("zone_id"), + "between_hour_of_day_share": between_share("hour"), + } + + +def _match_control_variance_share( + config: SimulationConfig, + *, + field: str, + target: float, + moment: str, + iterations: int = 10, +) -> tuple[SimulationConfig, float, str]: + """Tune one noncausal dispersion initializer to a descriptive share.""" + + low = 0.0 + high = 2.0 + + def evaluate(value: float) -> float: + return _simulated_control_moments(replace(config, **{field: value}))[moment] + + low_value = evaluate(low) + high_value = evaluate(high) + while high_value < target and high < 8.0: + high *= 2.0 + high_value = evaluate(high) + if target <= low_value: + return replace(config, **{field: low}), low_value, "lower_boundary" + if target >= high_value: + return replace(config, **{field: high}), high_value, "upper_boundary" + for _ in range(iterations): + midpoint = 0.5 * (low + high) + midpoint_value = evaluate(midpoint) + if midpoint_value < target: + low = midpoint + else: + high = midpoint + value = 0.5 * (low + high) + configured = replace(config, **{field: value}) + return configured, _simulated_control_moments(configured)[moment], "interior_solution" + + +def _coerce_template( + assumption_template: SimulationConfig | Mapping[str, Any] | None, +) -> SimulationConfig: + if assumption_template is None: + return SimulationConfig() + if isinstance(assumption_template, SimulationConfig): + return assumption_template + if isinstance(assumption_template, Mapping): + return SimulationConfig.from_dict(assumption_template) + raise TypeError("assumption_template must be SimulationConfig, a mapping, or None") + + +def _field_record( + value: Any, source: str, evidence_label: str, interpretation: str +) -> dict[str, Any]: + return { + "value": value, + "source": source, + "evidence_label": evidence_label, + "causal_claim": False, + "interpretation": interpretation, + } + + +def build_nyc_simulation_anchor( + calibration_path: str | Path, + *, + project_root: str | Path | None = None, + manifest_path: str | Path | None = None, + settings: NYCSimulationAnchorSettings | None = None, + assumption_template: SimulationConfig | Mapping[str, Any] | None = None, +) -> dict[str, Any]: + """Build a serializable, non-causal NYC simulation initialization proposal. + + Integrity validation is intentionally not optional: every bundle file and every + file declared by the source-data manifest has its byte count and SHA-256 + recomputed before a proposal is returned. + """ + + calibration_file = Path(calibration_path).resolve() + manifest_file = ( + Path(manifest_path).resolve() + if manifest_path is not None + else calibration_file.with_name("manifest.json") + ) + runtime = settings or NYCSimulationAnchorSettings() + template = _coerce_template(assumption_template) + calibration, source_manifest, integrity, bundle_files = _verify_integrity( + calibration_file, manifest_file, project_root + ) + observed_zones, observed_periods, observed_cells, observed_trips = ( + _validate_full_month_scope(calibration, source_manifest) + ) + moments = _anchor_moments( + calibration, + observed_zones, + observed_periods, + observed_cells, + observed_trips, + ) + temporal = _temporal_diagnostics(calibration, calibration_file, bundle_files) + + target_zones = runtime.target_n_zones or observed_zones + target_periods = runtime.target_n_periods or observed_periods + if target_zones > observed_zones or target_periods > observed_periods: + raise ValueError("target panel geometry cannot exceed the observed NYC panel") + target_cells = target_zones * target_periods + periods_per_day = 24 + supply_ratio_assumption = template.base_supply / template.base_demand + design = replace( + template.design, + seed=template.design.seed if template.design.seed is not None else runtime.seed + 1, + ) + config = replace( + template, + n_zones=target_zones, + n_periods=target_periods, + periods_per_day=periods_per_day, + base_demand=float(moments["base_demand_completed_trip_proxy"]), + base_supply=( + float(moments["base_demand_completed_trip_proxy"]) + * supply_ratio_assumption + ), + base_fare=float(moments["base_fare_published_mean"]), + base_wait_minutes=float(moments["base_wait_published_mean"]), + zone_heterogeneity_sd=float( + moments["zone_lognormal_sd_initialization_proxy"] + ), + seed=runtime.seed, + design=design, + ) + target_zone_share = float(moments["icc_like_between_zone_share"]) + target_hour_share = float(moments["between_hour_of_day_share"]) + zone_tuning_status = "not_attempted_insufficient_target_geometry" + hour_tuning_status = "not_attempted_insufficient_target_geometry" + initial_variance_moments = _simulated_control_moments(config) + achieved_zone_share = initial_variance_moments["between_zone_share"] + achieved_hour_share = initial_variance_moments["between_hour_of_day_share"] + # Coordinate the two descriptive dispersion matches because geographic and + # hourly components share the same total cell variance denominator. + for _ in range(3): + if target_zones >= 2: + config, achieved_zone_share, zone_tuning_status = ( + _match_control_variance_share( + config, + field="zone_heterogeneity_sd", + target=target_zone_share, + moment="between_zone_share", + ) + ) + if target_periods >= periods_per_day: + config, achieved_hour_share, hour_tuning_status = ( + _match_control_variance_share( + config, + field="time_pattern_strength", + target=target_hour_share, + moment="between_hour_of_day_share", + ) + ) + # Completed trips are an equilibrium-path output of the reduced-form simulator, + # not latent demand. Match the observed completed-trip scale on the deterministic + # control path by jointly rescaling demand and the explicitly assumed supply ratio. + # This is a semi-synthetic initialization step, never an estimate of either side + # of the market. + control_target = float(moments["base_demand_completed_trip_proxy"]) + pre_scale_moments = _simulated_control_moments(config) + initial_control_mean = pre_scale_moments["mean_completed_trips"] + if not math.isfinite(initial_control_mean) or initial_control_mean <= 0: + raise ValueError("NYC anchor simulator control path has non-positive completed trips") + control_scale = control_target / initial_control_mean + config = replace( + config, + base_demand=config.base_demand * control_scale, + base_supply=config.base_supply * control_scale, + ) + post_scale_moments = _simulated_control_moments(config) + observed_wait_target = float(moments["base_wait_published_mean"]) + if post_scale_moments["mean_wait_minutes"] <= 0: + raise ValueError("NYC anchor control path has non-positive mean wait") + wait_scale = observed_wait_target / post_scale_moments["mean_wait_minutes"] + config = replace(config, base_wait_minutes=config.base_wait_minutes * wait_scale) + final_control_moments = _simulated_control_moments(config) + achieved_control_mean = final_control_moments["mean_completed_trips"] + if not math.isfinite(achieved_control_mean) or achieved_control_mean <= 0: + raise ValueError("NYC anchor rescaled control path has non-positive completed trips") + control_calibration_error = achieved_control_mean - control_target + achieved_wait_mean = final_control_moments["mean_wait_minutes"] + wait_calibration_error = achieved_wait_mean - observed_wait_target + achieved_zone_share = final_control_moments["between_zone_share"] + achieved_hour_share = final_control_moments["between_hour_of_day_share"] + variance_share_tolerance = 0.01 + broad_moment_match_passed = ( + abs(control_calibration_error) <= 1e-8 + and abs(wait_calibration_error) <= 1e-8 + and abs(achieved_zone_share - target_zone_share) <= variance_share_tolerance + and abs(achieved_hour_share - target_hour_share) <= variance_share_tolerance + ) + if not broad_moment_match_passed: + raise ValueError( + "NYC anchor control-path broad-moment gate failed: " + f"completed_trip_error={control_calibration_error:.12g}, " + f"wait_error={wait_calibration_error:.12g}, " + f"between_zone_share_error={achieved_zone_share - target_zone_share:.12g}, " + f"between_hour_share_error={achieved_hour_share - target_hour_share:.12g}, " + f"variance_share_tolerance={variance_share_tolerance:.12g}" + ) + config_payload = config.to_dict() + + derived: dict[str, dict[str, Any]] = { + "periods_per_day": _field_record( + periods_per_day, + "complete hourly calendar panel", + DESCRIPTIVE_EVIDENCE_LABEL, + "Exact panel timing geometry; not a persistence estimate.", + ), + "base_demand": _field_record( + config.base_demand, + "joint demand/supply rescaling to the observed completed-trip control target", + ANCHOR_EVIDENCE_LABEL, + ( + "Semi-synthetic control-path scale parameter; completed trips are not " + "latent rider requests and this value is not an empirical demand estimate." + ), + ), + "base_fare": _field_record( + config.base_fare, + "mean published base passenger fare per completed trip", + ANCHOR_EVIDENCE_LABEL, + "Nominal fare-scale initializer; not total rider payment or platform revenue.", + ), + "base_wait_minutes": _field_record( + config.base_wait_minutes, + "control-path rescaling to mean nonnegative request-to-pickup elapsed time", + ANCHOR_EVIDENCE_LABEL, + ( + "Semi-synthetic service-process scale; not a randomized wait outcome " + "or rider-utility estimate." + ), + ), + "zone_heterogeneity_sd": _field_record( + config.zone_heterogeneity_sd, + "deterministic control-path match to the descriptive between-zone variance share", + ANCHOR_EVIDENCE_LABEL, + ( + "Reduced-form dispersion initializer that does not identify latent demand " + "or supply heterogeneity." + ), + ), + "time_pattern_strength": _field_record( + config.time_pattern_strength, + "deterministic control-path match to the descriptive hour-of-day variance share", + ANCHOR_EVIDENCE_LABEL, + ( + "Harmonic timing initializer; it is neither causal persistence nor a " + "seasonality estimate beyond the observed month." + ), + ), + } + assumptions: dict[str, dict[str, Any]] = {} + if target_zones == observed_zones: + derived["n_zones"] = _field_record( + target_zones, + "complete observed pickup-zone panel", + DESCRIPTIVE_EVIDENCE_LABEL, + "Observed TLC LocationID count represented in the complete panel.", + ) + else: + assumptions["n_zones"] = _field_record( + target_zones, + "NYCSimulationAnchorSettings.target_n_zones", + "explicit_sample_design_assumption", + "Simulation-size choice; no representative zone subset is selected here.", + ) + if target_periods == observed_periods: + derived["n_periods"] = _field_record( + target_periods, + "complete observed hourly month", + DESCRIPTIVE_EVIDENCE_LABEL, + "Observed complete hourly calendar geometry.", + ) + else: + assumptions["n_periods"] = _field_record( + target_periods, + "NYCSimulationAnchorSettings.target_n_periods", + "explicit_sample_design_assumption", + "Simulation-size choice; no representative time subset is selected here.", + ) + + assumption_interpretations = { + "base_supply": ( + "Scaled by the template baseline supply-to-demand ratio; available drivers " + "are not observed in completed-trip records." + ), + "time_pattern_strength": ( + "Simulator harmonic amplitude is not inferred from the observed hourly profile." + ), + "demand_noise_sd": "Latent demand shock dispersion is not observed.", + "supply_noise_sd": "Latent supply shock dispersion is not observed.", + "individuals_per_cell": "Simulation population size is a design choice.", + "budget": "Experiment budget is a policy/design assumption.", + "seed": "Deterministic simulation seed chosen by the caller.", + "design": ( + "Assignment mechanism is a template assumption; when its seed is absent, " + "the deterministic assignment seed is the anchor seed plus one." + ), + } + for field, value in config_payload.items(): + if field in derived or field in assumptions: + continue + interpretation = assumption_interpretations.get( + field, + ( + "Explicit structural or policy assumption; it is not estimated from " + "the NYC completed-trip records." + ), + ) + source = { + "base_supply": "assumption_template baseline_supply/base_demand ratio", + "seed": "NYCSimulationAnchorSettings.seed", + "design": ( + "assumption_template.design with deterministic assignment-seed fallback " + "from NYCSimulationAnchorSettings.seed" + ), + }.get(field, "assumption_template") + assumptions[field] = _field_record( + value, source, "explicit_assumption", interpretation + ) + + causal_groups = { + "intervention_version_and_dose": [ + "treatment_version", + "discount_rate", + "incentive_per_driver", + "reference_incentive_per_driver", + ], + "treatment_and_supply_response": [ + "direct_demand_effect", + "direct_supply_effect", + ], + "interference_and_substitution": [ + "spillover_strength", + "rider_substitution", + "driver_mobility", + ], + "temporal_carryover": ["persistence"], + "latent_supply_and_matching": [ + "base_supply", + "capacity_per_driver", + "matching_efficiency", + "supply_noise_sd", + ], + "welfare_accounting": [ + "rider_value", + "operating_cost_per_trip", + "wait_disutility_per_minute", + ], + } + if not set(CAUSAL_ASSUMPTION_FIELDS).issubset(assumptions): + raise RuntimeError("causal fields escaped explicit-assumption provenance") + + return { + "schema_version": ANCHOR_SCHEMA_VERSION, + "evidence_label": ANCHOR_EVIDENCE_LABEL, + "causal_claim": False, + "status": "descriptive_control_path_anchor_validated_not_fitted_structural_model", + "city": "New York City", + "source_scope": { + "dataset": "NYC TLC High Volume For-Hire Vehicle published trip records", + "pickup_min": calibration["scope"]["pickup_min"], + "pickup_max": calibration["scope"]["pickup_max"], + "evidence_label": DESCRIPTIVE_EVIDENCE_LABEL, + "causal_claim": False, + "published_completed_trips": observed_trips, + }, + "integrity": integrity, + "target_panel": { + "observed": { + "n_zones": observed_zones, + "n_periods": observed_periods, + "periods_per_day": periods_per_day, + "panel_cells": observed_cells, + }, + "simulation": { + "n_zones": target_zones, + "n_periods": target_periods, + "periods_per_day": periods_per_day, + "panel_cells": target_cells, + "seed": runtime.seed, + "assignment_seed": design.seed, + }, + "sample_scaling": { + "zone_fraction": target_zones / observed_zones, + "period_fraction": target_periods / observed_periods, + "cell_fraction": target_cells / observed_cells, + "completed_trip_volume_proxy": ( + float(moments["base_demand_completed_trip_proxy"]) * target_cells + ), + "selection_performed": False, + "interpretation": ( + "Geometry scaling is a simulation-size decision. The builder does " + "not select or claim a representative observed subsample." + ), + }, + }, + "observable_anchor": { + "evidence_label": DESCRIPTIVE_EVIDENCE_LABEL, + "causal_claim": False, + "scale_and_heterogeneity": moments, + "temporal_associations": temporal, + "interpretation": ( + "Observable completed-trip scale, timing, and dispersion only; temporal " + "correlations are not mapped to persistence." + ), + }, + "control_path_scale_validation": { + "evidence_label": ANCHOR_EVIDENCE_LABEL, + "causal_claim": False, + "target_mean_published_completed_trips_per_zone_hour": control_target, + "initial_simulated_control_completed_trips": initial_control_mean, + "joint_demand_supply_scale_factor": control_scale, + "achieved_simulated_control_completed_trips": achieved_control_mean, + "calibration_error": control_calibration_error, + "target_mean_nonnegative_request_to_pickup_minutes": observed_wait_target, + "achieved_simulated_control_mean_wait_minutes": achieved_wait_mean, + "wait_scale_factor": wait_scale, + "wait_calibration_error": wait_calibration_error, + "target_between_zone_variance_share": target_zone_share, + "achieved_between_zone_variance_share": achieved_zone_share, + "zone_dispersion_tuning_status": zone_tuning_status, + "target_between_hour_of_day_variance_share": target_hour_share, + "achieved_between_hour_of_day_variance_share": achieved_hour_share, + "hour_pattern_tuning_status": hour_tuning_status, + "variance_share_absolute_tolerance": variance_share_tolerance, + "broad_moment_match_passed": broad_moment_match_passed, + "preserved_assumed_supply_to_demand_ratio": supply_ratio_assumption, + "simulation_seed": runtime.seed, + "interpretation": ( + "Matches one descriptive control-path scale under the declared reduced-form " + "simulator assumptions; it does not identify latent demand or supply." + ), + }, + "simulation_config": config_payload, + "field_provenance": { + "derived_initializers": derived, + "explicit_assumptions": assumptions, + "partition_complete": ( + set(config_payload) == set(derived).union(assumptions) + and not set(derived).intersection(assumptions) + ), + }, + "causal_parameter_assumptions": { + "status": "explicit_assumptions_not_estimated_from_nyc_trip_records", + "groups": causal_groups, + "fields": list(CAUSAL_ASSUMPTION_FIELDS), + "calibration_embedded_template_assumptions_used": False, + }, + "required_validation_before_design_use": [ + "fit or stress-test the simulated control path against held-out descriptive cells", + "check zone and hourly distributions, not only the grand mean", + "run sensitivity grids over every structural and causal assumption", + "do not treat temporal correlation as causal persistence", + "do not treat OD connectivity as spillover strength or substitution", + ], + "warnings": [ + NO_CAUSAL_CLAIM, + ( + "The base_demand, base_wait_minutes, zone_heterogeneity_sd, and " + "time_pattern_strength values are semi-synthetic initialization proxies, " + "not structural estimates." + ), + ( + "A reduced target geometry is not an empirical sample until an explicit " + "pre-treatment-only selection rule and representativeness audit are applied." + ), + ( + "One observed month does not establish seasonality or transportability " + "to other months, products, or cities." + ), + ], + } + + +def validate_nyc_simulation_anchor_integrity( + calibration_path: str | Path, + *, + project_root: str | Path | None = None, + manifest_path: str | Path | None = None, +) -> dict[str, Any]: + """Recompute the complete calibration-bundle and source-data hash chain.""" + + calibration_file = Path(calibration_path).resolve() + manifest_file = ( + Path(manifest_path).resolve() + if manifest_path is not None + else calibration_file.with_name("manifest.json") + ) + _, _, integrity, _ = _verify_integrity( + calibration_file, + manifest_file, + project_root, + ) + return integrity + + +__all__ = [ + "ANCHOR_EVIDENCE_LABEL", + "ANCHOR_SCHEMA_VERSION", + "CAUSAL_ASSUMPTION_FIELDS", + "DESCRIPTIVE_EVIDENCE_LABEL", + "NO_CAUSAL_CLAIM", + "NYCSimulationAnchorSettings", + "build_nyc_simulation_anchor", + "validate_nyc_simulation_anchor_integrity", +] diff --git a/CasualLab/src/casuallab/nyc_weather.py b/CasualLab/src/casuallab/nyc_weather.py new file mode 100644 index 0000000000000000000000000000000000000000..e04435bbbea0386381a15bf82da546931e41d544 --- /dev/null +++ b/CasualLab/src/casuallab/nyc_weather.py @@ -0,0 +1,548 @@ +"""Verified NOAA weather enrichment for the NYC full-month descriptive panel. + +The weather layer is deliberately descriptive. A citywide station observation can +describe which published trip records occurred on wet, snowy, or cold days; it does +not create exogenous price variation and it does not identify a causal weather shock. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import tempfile +import urllib.request +from collections.abc import Sequence +from dataclasses import dataclass +from datetime import date +from pathlib import Path +from typing import Any + +import duckdb +import numpy as np +import pandas as pd + +from casuallab.data import sha256_file + +NOAA_DAILY_SUMMARIES_URL = ( + "https://www.ncei.noaa.gov/access/services/data/v1?dataset=daily-summaries" + "&stations=USW00094728&startDate=2024-01-01&endDate=2024-01-31" + "&format=csv&units=metric&includeAttributes=true" + "&dataTypes=PRCP,SNOW,SNWD,TMAX,TMIN,AWND,WT01,WT02,WT03,WT08,WT16,WT18" +) +NOAA_RAW_SHA256 = "fa9a5486dfa37e1ab61ad853d1811369f25e8c71ebf9dd0d56217f8231a0ee04" +WEATHER_EVIDENCE_LABEL = "descriptive_observed_external_weather" +WEATHER_SCHEMA_VERSION = "1.0.0" + + +@dataclass(frozen=True, slots=True) +class NYCWeatherConfig: + """Pinned Central Park daily-weather contract for January 2024.""" + + station_id: str = "USW00094728" + station_name: str = "NY CITY CENTRAL PARK, NY US" + start_date: date = date(2024, 1, 1) + end_date: date = date(2024, 1, 31) + expected_rows: int = 31 + expected_sha256: str = NOAA_RAW_SHA256 + wet_day_threshold_mm: float = 1.0 + heavy_precipitation_threshold_mm: float = 10.0 + freezing_threshold_c: float = 0.0 + + def __post_init__(self) -> None: + if self.start_date > self.end_date: + raise ValueError("weather start_date must not exceed end_date") + if self.expected_rows < 1: + raise ValueError("expected_rows must be positive") + if len(self.expected_sha256) != 64 or any( + character not in "0123456789abcdef" for character in self.expected_sha256 + ): + raise ValueError("expected_sha256 must be a lowercase SHA-256 digest") + for name in ( + "wet_day_threshold_mm", + "heavy_precipitation_threshold_mm", + ): + value = float(getattr(self, name)) + if not math.isfinite(value) or value < 0: + raise ValueError(f"{name} must be finite and nonnegative") + if self.heavy_precipitation_threshold_mm < self.wet_day_threshold_mm: + raise ValueError("heavy precipitation threshold must be at least wet threshold") + + @property + def source_url(self) -> str: + return NOAA_DAILY_SUMMARIES_URL + + +@dataclass(frozen=True, slots=True) +class NYCWeatherArtifacts: + normalized_weather_path: Path + daily_panel_path: Path + hourly_contrast_path: Path + summary_path: Path + manifest_path: Path + + def paths(self) -> tuple[Path, ...]: + return ( + self.normalized_weather_path, + self.daily_panel_path, + self.hourly_contrast_path, + self.summary_path, + self.manifest_path, + ) + + +def _atomic_json(payload: dict[str, Any], path: Path) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + prefix=f".{path.stem}-", + suffix=path.suffix, + dir=path.parent, + delete=False, + ) as handle: + temporary = Path(handle.name) + json.dump(payload, handle, indent=2, sort_keys=True, allow_nan=False) + handle.write("\n") + temporary.replace(path) + return path + + +def _atomic_csv(frame: pd.DataFrame, path: Path) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="", + prefix=f".{path.stem}-", + suffix=path.suffix, + dir=path.parent, + delete=False, + ) as handle: + temporary = Path(handle.name) + frame.to_csv(handle, index=False) + temporary.replace(path) + return path + + +def download_noaa_daily_weather( + destination: str | Path, + config: NYCWeatherConfig | None = None, + *, + refresh: bool = False, +) -> Path: + """Atomically download and verify the pinned 31-row NOAA response.""" + + cfg = config or NYCWeatherConfig() + target = Path(destination) + target.parent.mkdir(parents=True, exist_ok=True) + if target.is_file() and not refresh: + if sha256_file(target) != cfg.expected_sha256: + raise ValueError("cached NOAA weather SHA-256 does not match the pinned response") + return target + with tempfile.NamedTemporaryFile( + prefix=f".{target.stem}-", + suffix=target.suffix, + dir=target.parent, + delete=False, + ) as handle: + temporary = Path(handle.name) + request = urllib.request.Request( + cfg.source_url, + headers={"User-Agent": "CausalMarketplaceLab/0.1 descriptive research"}, + ) + try: + with urllib.request.urlopen(request, timeout=120) as response, temporary.open( + "wb" + ) as stream: + while block := response.read(1024 * 1024): + stream.write(block) + if sha256_file(temporary) != cfg.expected_sha256: + raise ValueError("downloaded NOAA weather SHA-256 does not match the pin") + temporary.replace(target) + except Exception: + temporary.unlink(missing_ok=True) + raise + return target + + +def normalize_noaa_daily_weather( + raw_path: str | Path, + config: NYCWeatherConfig | None = None, +) -> pd.DataFrame: + """Validate and normalize the pinned NOAA daily summaries response.""" + + cfg = config or NYCWeatherConfig() + source = Path(raw_path) + if not source.is_file(): + raise FileNotFoundError(source) + if sha256_file(source) != cfg.expected_sha256: + raise ValueError("NOAA weather raw SHA-256 does not match the configured pin") + raw = pd.read_csv(source, dtype={"STATION": "string", "DATE": "string"}) + required = { + "STATION", + "DATE", + "AWND", + "PRCP", + "SNOW", + "SNWD", + "TMAX", + "TMIN", + } + missing = required.difference(raw.columns) + if missing: + raise ValueError(f"NOAA weather response missing fields: {sorted(missing)}") + if len(raw) != cfg.expected_rows: + raise ValueError("NOAA weather response has an unexpected row count") + if set(raw["STATION"].dropna().astype(str)) != {cfg.station_id}: + raise ValueError("NOAA weather response contains an unexpected station") + service_date = pd.to_datetime(raw["DATE"], errors="raise").dt.date + expected_dates = pd.date_range(cfg.start_date, cfg.end_date, freq="D").date + if raw["DATE"].duplicated().any() or list(service_date) != list(expected_dates): + raise ValueError("NOAA weather dates must be unique, sorted, and calendar-complete") + + numeric_columns = ("AWND", "PRCP", "SNOW", "SNWD", "TMAX", "TMIN") + numeric = raw[list(numeric_columns)].apply(pd.to_numeric, errors="coerce") + if numeric[["PRCP", "SNOW", "SNWD", "TMAX", "TMIN"]].isna().any().any(): + raise ValueError("NOAA weather response is missing required daily measurements") + if (numeric[["PRCP", "SNOW", "SNWD"]] < 0).any().any(): + raise ValueError("NOAA precipitation and snow measurements cannot be negative") + if (numeric["TMAX"] < numeric["TMIN"]).any(): + raise ValueError("NOAA daily maximum temperature is below minimum temperature") + + normalized = pd.DataFrame( + { + "service_date": pd.Series(service_date, dtype="object"), + "station_id": cfg.station_id, + "station_name": cfg.station_name, + "temperature_max_c": numeric["TMAX"], + "temperature_min_c": numeric["TMIN"], + "temperature_midrange_c": (numeric["TMAX"] + numeric["TMIN"]) / 2.0, + "precipitation_mm": numeric["PRCP"], + "snowfall_mm": numeric["SNOW"], + "snow_depth_mm": numeric["SNWD"], + "average_wind_mps": numeric["AWND"], + } + ) + normalized["wet_day"] = normalized["precipitation_mm"] >= cfg.wet_day_threshold_mm + normalized["heavy_precipitation_day"] = ( + normalized["precipitation_mm"] >= cfg.heavy_precipitation_threshold_mm + ) + normalized["snow_day"] = normalized["snowfall_mm"] > 0 + normalized["freezing_day"] = ( + normalized["temperature_min_c"] <= cfg.freezing_threshold_c + ) + normalized["wet_or_snow_day"] = normalized["wet_day"] | normalized["snow_day"] + for field in ("AWND", "PRCP", "SNOW", "SNWD", "TMAX", "TMIN"): + attributes = f"{field}_ATTRIBUTES" + if attributes in raw: + normalized[f"{field.lower()}_measurement_attributes"] = raw[attributes].fillna("") + normalized["evidence_label"] = WEATHER_EVIDENCE_LABEL + normalized["causal_claim"] = False + normalized["source_url"] = cfg.source_url + normalized["raw_sha256"] = cfg.expected_sha256 + return normalized + + +def _sql_string(value: str) -> str: + return "'" + value.replace("'", "''") + "'" + + +def _scan_sql(paths: Sequence[Path]) -> str: + if not paths: + raise FileNotFoundError("NYC weather analysis requires zone-time Parquet files") + rendered = ", ".join(_sql_string(str(path.resolve())) for path in paths) + return f"read_parquet([{rendered}], hive_partitioning=false)" + + +def _finite_correlation(left: pd.Series, right: pd.Series) -> float | None: + valid = left.notna() & right.notna() + if valid.sum() < 3 or left.loc[valid].nunique() < 2 or right.loc[valid].nunique() < 2: + return None + value = float(left.loc[valid].corr(right.loc[valid])) + return value if math.isfinite(value) else None + + +def weather_demand_associations( + zone_time_paths: Sequence[str | Path], + weather: pd.DataFrame, + config: NYCWeatherConfig | None = None, +) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]: + """Join weather to daily/hourly completed trips and compute descriptive contrasts.""" + + cfg = config or NYCWeatherConfig() + paths = tuple(Path(path) for path in zone_time_paths) + scan = _scan_sql(paths) + connection = duckdb.connect(database=":memory:") + try: + daily = connection.execute( + f""" + SELECT CAST(service_date AS DATE) AS service_date, + SUM(CAST(trip_count AS BIGINT)) AS published_completed_trips, + COUNT(DISTINCT zone_id) AS panel_zones, + SUM(CASE WHEN trip_count > 0 THEN 1 ELSE 0 END) AS occupied_zone_hours + FROM {scan} + GROUP BY 1 + ORDER BY 1 + """ + ).fetchdf() + hourly = connection.execute( + f""" + SELECT CAST(service_date AS DATE) AS service_date, + CAST(hour AS INTEGER) AS hour, + SUM(CAST(trip_count AS BIGINT)) AS published_completed_trips + FROM {scan} + GROUP BY 1, 2 + ORDER BY 1, 2 + """ + ).fetchdf() + finally: + connection.close() + daily["service_date"] = pd.to_datetime(daily["service_date"]).dt.date + hourly["service_date"] = pd.to_datetime(hourly["service_date"]).dt.date + expected_dates = set(pd.date_range(cfg.start_date, cfg.end_date, freq="D").date) + if set(daily["service_date"]) != expected_dates or len(daily) != cfg.expected_rows: + raise ValueError("NYC zone-time panel does not cover the configured weather month") + if len(hourly) != cfg.expected_rows * 24: + raise ValueError("NYC zone-time panel does not contain every configured date-hour") + + weather_frame = weather.copy() + weather_frame["service_date"] = pd.to_datetime( + weather_frame["service_date"], errors="raise" + ).dt.date + daily = daily.merge(weather_frame, on="service_date", how="left", validate="1:1") + if daily["evidence_label"].isna().any(): + raise ValueError("weather coverage is incomplete after joining the NYC panel") + daily["iso_weekday"] = pd.to_datetime(daily["service_date"]).dt.isocalendar().day.astype(int) + daily["day_index"] = np.arange(len(daily), dtype=int) + hourly = hourly.merge( + weather_frame[["service_date", "wet_day", "snow_day", "freezing_day"]], + on="service_date", + how="left", + validate="m:1", + ) + hourly_contrast = ( + hourly.groupby(["hour", "wet_day"], observed=True)["published_completed_trips"] + .agg(["count", "mean"]) + .reset_index() + .pivot(index="hour", columns="wet_day", values=["count", "mean"]) + ) + hourly_contrast.columns = [ + f"{'days' if measure == 'count' else 'mean_published_completed_trips'}_" + f"{'wet' if wet else 'dry'}" + for measure, wet in hourly_contrast.columns + ] + hourly_contrast = hourly_contrast.reset_index() + for column in ( + "days_wet", + "days_dry", + "mean_published_completed_trips_wet", + "mean_published_completed_trips_dry", + ): + if column not in hourly_contrast: + hourly_contrast[column] = np.nan + hourly_contrast["wet_minus_dry_mean_published_completed_trips"] = ( + hourly_contrast["mean_published_completed_trips_wet"] + - hourly_contrast["mean_published_completed_trips_dry"] + ) + hourly_contrast["evidence_label"] = WEATHER_EVIDENCE_LABEL + hourly_contrast["causal_claim"] = False + + wet = daily["wet_day"].astype(bool) + wet_mean = float(daily.loc[wet, "published_completed_trips"].mean()) + dry_mean = float(daily.loc[~wet, "published_completed_trips"].mean()) + summary = { + "schema_version": WEATHER_SCHEMA_VERSION, + "evidence_label": WEATHER_EVIDENCE_LABEL, + "causal_claim": False, + "scope": { + "city": "New York City", + "pickup_month": "2024-01", + "weather_station_id": cfg.station_id, + "weather_station_name": cfg.station_name, + "published_completed_trip_days": len(daily), + "population_claim": False, + }, + "definitions": { + "wet_day": f"NOAA daily precipitation >= {cfg.wet_day_threshold_mm:g} mm", + "heavy_precipitation_day": ( + "NOAA daily precipitation >= " + f"{cfg.heavy_precipitation_threshold_mm:g} mm" + ), + "snow_day": "NOAA daily snowfall > 0 mm", + "freezing_day": ( + f"NOAA daily minimum temperature <= {cfg.freezing_threshold_c:g} C" + ), + "temperature_midrange_c": "(daily TMAX + daily TMIN) / 2; not TAVG", + }, + "coverage": { + "weather_rows": len(weather_frame), + "joined_days": len(daily), + "joined_date_hours": len(hourly), + "wet_days": int(wet.sum()), + "dry_days": int((~wet).sum()), + "heavy_precipitation_days": int(daily["heavy_precipitation_day"].sum()), + "snow_days": int(daily["snow_day"].sum()), + "freezing_days": int(daily["freezing_day"].sum()), + }, + "associations": { + "mean_daily_published_completed_trips_wet": wet_mean, + "mean_daily_published_completed_trips_dry": dry_mean, + "wet_minus_dry_mean_daily_published_completed_trips": wet_mean - dry_mean, + "wet_minus_dry_relative_to_dry": ( + (wet_mean - dry_mean) / dry_mean if dry_mean else None + ), + "precipitation_daily_trip_correlation": _finite_correlation( + daily["precipitation_mm"], daily["published_completed_trips"] + ), + "temperature_midrange_daily_trip_correlation": _finite_correlation( + daily["temperature_midrange_c"], daily["published_completed_trips"] + ), + }, + "conservation": { + "zone_time_trip_sum": int(daily["published_completed_trips"].sum()), + "daily_trip_sum": int(daily["published_completed_trips"].sum()), + "passes": True, + }, + "limitations": [ + "The Central Park station is a citywide proxy and does not measure zone-level weather.", + "Wet-versus-dry and temperature contrasts are observational associations confounded by seasonality, weekday composition, and other shocks.", + "Published completed trips exclude latent requests, unserved demand, and available drivers.", + "Weather is not an instrument for fare or treatment, and no causal elasticity or weather effect is identified.", + "One January month does not establish seasonal or annual transportability.", + ], + } + return daily, hourly_contrast, summary + + +def _portable(path: Path, root: Path) -> str: + try: + return str(path.resolve().relative_to(root.resolve())) + except ValueError as exc: + raise ValueError(f"weather artifact path is outside project_root: {path}") from exc + + +def write_nyc_weather_bundle( + raw_path: str | Path, + panel_directory: str | Path, + data_manifest_path: str | Path, + output_directory: str | Path, + *, + project_root: str | Path, + config: NYCWeatherConfig | None = None, +) -> NYCWeatherArtifacts: + """Create an atomic, hash-manifested NYC weather association bundle.""" + + cfg = config or NYCWeatherConfig() + root = Path(project_root).resolve() + raw = Path(raw_path).resolve() + panel_root = Path(panel_directory).resolve() + source_manifest_path = Path(data_manifest_path).resolve() + output = Path(output_directory).resolve() + output.mkdir(parents=True, exist_ok=True) + marker = output / "NYC_WEATHER_INCOMPLETE.json" + manifest_path = output / "manifest.json" + manifest_path.unlink(missing_ok=True) + _atomic_json({"status": "incomplete"}, marker) + + source_manifest = json.loads(source_manifest_path.read_text(encoding="utf-8")) + if ( + source_manifest.get("config", {}).get("source") != "nyc_hvfhv" + or source_manifest.get("config", {}).get("mode") != "full" + or source_manifest.get("metadata", {}).get("evidence_label") + != "descriptive_real_data" + or source_manifest.get("metadata", {}).get("causal_claim") is not False + ): + raise ValueError("weather analysis requires the verified NYC full-data manifest") + panel_paths = tuple(sorted(panel_root.rglob("*.parquet"))) + if not panel_paths: + raise FileNotFoundError("NYC full zone-time panel is unavailable") + declared = { + (root / entry["path"]).resolve(): entry + for entry in source_manifest.get("files", []) + if isinstance(entry, dict) and isinstance(entry.get("path"), str) + } + if set(panel_paths).difference(declared): + raise ValueError("NYC weather panel files are not all declared in the source manifest") + for path in panel_paths: + entry = declared[path] + if path.stat().st_size != entry.get("bytes") or sha256_file(path) != entry.get( + "sha256" + ): + raise ValueError(f"NYC weather panel lineage mismatch: {path}") + + normalized = normalize_noaa_daily_weather(raw, cfg) + daily, hourly, summary = weather_demand_associations(panel_paths, normalized, cfg) + expected_trips = int( + source_manifest["metadata"]["full_month_processing"]["row_conservation"][ + "zone_time_trip_sum" + ] + ) + if summary["conservation"]["daily_trip_sum"] != expected_trips: + raise ValueError("NYC weather daily panel does not conserve published trips") + summary["provenance"] = { + "noaa_url": cfg.source_url, + "noaa_raw_path": _portable(raw, root), + "noaa_raw_sha256": sha256_file(raw), + "nyc_data_manifest_path": _portable(source_manifest_path, root), + "nyc_data_manifest_sha256": sha256_file(source_manifest_path), + "panel_files_verified": len(panel_paths), + "hashes_recomputed": True, + } + normalized_path = _atomic_csv(normalized, output / "weather_daily.csv") + daily_path = _atomic_csv(daily, output / "weather_trip_daily.csv") + hourly_path = _atomic_csv(hourly, output / "weather_hourly_contrasts.csv") + summary_path = _atomic_json(summary, output / "weather_associations.json") + files = [raw, source_manifest_path, normalized_path, daily_path, hourly_path, summary_path] + entries = [ + { + "path": _portable(path, root), + "bytes": path.stat().st_size, + "sha256": sha256_file(path), + } + for path in files + ] + declared_digest = hashlib.sha256( + json.dumps(entries, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + _atomic_json( + { + "schema_version": WEATHER_SCHEMA_VERSION, + "evidence_label": WEATHER_EVIDENCE_LABEL, + "causal_claim": False, + "portable_paths": True, + "files": entries, + "declared_file_set_sha256": declared_digest, + "checks": { + "noaa_raw_hash_matches": sha256_file(raw) == cfg.expected_sha256, + "calendar_complete": len(normalized) == cfg.expected_rows, + "nyc_source_manifest_valid": True, + "panel_files_verified": len(panel_paths), + "trip_conservation": True, + }, + }, + manifest_path, + ) + if not manifest_path.is_file(): + raise RuntimeError("NYC weather bundle completed without a manifest") + marker.unlink(missing_ok=True) + return NYCWeatherArtifacts( + normalized_weather_path=normalized_path, + daily_panel_path=daily_path, + hourly_contrast_path=hourly_path, + summary_path=summary_path, + manifest_path=manifest_path, + ) + + +__all__ = [ + "NOAA_DAILY_SUMMARIES_URL", + "NOAA_RAW_SHA256", + "NYCWeatherArtifacts", + "NYCWeatherConfig", + "WEATHER_EVIDENCE_LABEL", + "download_noaa_daily_weather", + "normalize_noaa_daily_weather", + "weather_demand_associations", + "write_nyc_weather_bundle", +] diff --git a/CasualLab/src/casuallab/policy.py b/CasualLab/src/casuallab/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..71b34a487b429ed07abf710bd33da0df189d353c --- /dev/null +++ b/CasualLab/src/casuallab/policy.py @@ -0,0 +1,314 @@ +"""Budget-constrained policy learning evaluated on unseen semi-synthetic markets. + +The policy learner never uses holdout treatment effects for fitting or ranking. The +known holdout effects are used only to score policies after allocations are frozen. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Sequence +from dataclasses import dataclass + +import numpy as np +import pandas as pd +from sklearn.ensemble import RandomForestRegressor + +DEFAULT_FEATURES = ( + "baseline_demand", + "market_tightness", + "hour_sin", + "hour_cos", + "adverse_weather", + "neighborhood_income_index", + "event_intensity", +) + + +@dataclass(frozen=True) +class PolicyConfig: + """Configuration for honest policy learning and evaluation.""" + + budget: float = 2_000.0 + incentive_cost: float = 10.0 + instability_penalty: float = 0.25 + model_trees: int = 120 + model_replicates: int = 4 + seed: int = 202503 + + def __post_init__(self) -> None: + if self.budget < 0: + raise ValueError("budget must be non-negative") + if self.incentive_cost <= 0: + raise ValueError("incentive_cost must be positive") + if self.instability_penalty < 0: + raise ValueError("instability_penalty must be non-negative") + if self.model_trees < 10: + raise ValueError("model_trees must be at least 10") + if self.model_replicates < 2: + raise ValueError("model_replicates must be at least 2") + + +def generate_policy_learning_sample( + n_rows: int, + *, + seed: int, + incentive_cost: float = 10.0, +) -> pd.DataFrame: + """Generate a compact policy-learning sample with known unit-level effects. + + This is a semi-synthetic decision surface, not a real-data treatment-effect + estimate. ``effect_signal`` mimics a noisy cross-fitted treatment-effect signal + available to the learner. ``true_incremental_outcome`` is hidden from fitting and + exposed only so an independent holdout can be scored against known truth. + """ + + if n_rows <= 0: + raise ValueError("n_rows must be positive") + if incentive_cost <= 0: + raise ValueError("incentive_cost must be positive") + + rng = np.random.default_rng(seed) + hour = rng.integers(0, 24, size=n_rows) + baseline_demand = rng.lognormal(mean=3.0, sigma=0.45, size=n_rows) + market_tightness = rng.beta(2.4, 2.0, size=n_rows) + adverse_weather = rng.binomial(1, 0.18, size=n_rows) + income_index = np.clip(rng.normal(0.0, 1.0, size=n_rows), -2.5, 2.5) + event_intensity = np.where(rng.random(n_rows) < 0.12, rng.gamma(2.0, 0.7, n_rows), 0.0) + + # Known causal response surface. It intentionally contains interaction and + # saturation so a learned policy has something real to discover in simulation. + rush = ((hour >= 7) & (hour <= 9)) | ((hour >= 16) & (hour <= 19)) + true_increment = ( + 0.18 + + 0.025 * np.sqrt(baseline_demand) + + 0.55 * market_tightness + + 0.20 * rush.astype(float) + + 0.16 * adverse_weather * market_tightness + + 0.10 * event_intensity + - 0.04 * np.maximum(income_index, 0.0) + - 0.16 * np.square(market_tightness - 0.72) + ) + true_increment = np.clip(true_increment, 0.02, None) + effect_signal = true_increment + rng.normal(0.0, 0.28, size=n_rows) + + return pd.DataFrame( + { + "market_unit_id": np.arange(n_rows, dtype=int), + "baseline_demand": baseline_demand, + "market_tightness": market_tightness, + "hour_sin": np.sin(2.0 * np.pi * hour / 24.0), + "hour_cos": np.cos(2.0 * np.pi * hour / 24.0), + "adverse_weather": adverse_weather.astype(float), + "neighborhood_income_index": income_index, + "event_intensity": event_intensity, + "effect_signal": effect_signal, + "true_incremental_outcome": true_increment, + "treatment_cost": np.full(n_rows, float(incentive_cost)), + "evidence_type": "semi_synthetic", + "generation_seed": seed, + } + ) + + +def _validate_policy_frame(frame: pd.DataFrame, features: Sequence[str], *, training: bool) -> None: + required = set(features) | {"treatment_cost", "true_incremental_outcome"} + if training: + required.add("effect_signal") + missing = required.difference(frame.columns) + if missing: + raise ValueError(f"policy frame missing columns: {sorted(missing)}") + if frame.empty: + raise ValueError("policy frame must not be empty") + if (frame["treatment_cost"] <= 0).any(): + raise ValueError("all treatment costs must be positive") + if not np.isfinite(frame[list(required)].to_numpy(dtype=float)).all(): + raise ValueError("policy inputs must be finite") + + +def _fit_stability_adjusted_scores( + train: pd.DataFrame, + holdout: pd.DataFrame, + *, + features: Sequence[str], + config: PolicyConfig, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + predictions: list[np.ndarray] = [] + for replicate in range(config.model_replicates): + model = RandomForestRegressor( + n_estimators=config.model_trees, + min_samples_leaf=max(5, len(train) // 100), + max_depth=6, + max_features="sqrt", + bootstrap=True, + random_state=config.seed + replicate, + n_jobs=1, + ) + model.fit(train[list(features)], train["effect_signal"]) + predictions.append(model.predict(holdout[list(features)])) + prediction_matrix = np.vstack(predictions) + mean_effect = prediction_matrix.mean(axis=0) + instability = prediction_matrix.std(axis=0, ddof=1) + conservative_effect = mean_effect - config.instability_penalty * instability + return conservative_effect, mean_effect, instability + + +def allocate_ranked( + score: Iterable[float], + cost: Iterable[float], + budget: float, +) -> np.ndarray: + """Greedily allocate binary treatment by value per dollar. + + Deterministic index-based tie breaking makes repeated runs byte-for-byte stable. + Non-positive scores are not funded; an explicit uniform baseline is responsible + for representing diffuse allocations. + """ + + score_array = np.asarray(list(score), dtype=float) + cost_array = np.asarray(list(cost), dtype=float) + if score_array.shape != cost_array.shape: + raise ValueError("score and cost must have the same shape") + if budget < 0: + raise ValueError("budget must be non-negative") + if (cost_array <= 0).any() or not np.isfinite(cost_array).all(): + raise ValueError("cost must be finite and positive") + if not np.isfinite(score_array).all(): + raise ValueError("score must be finite") + + ratios = score_array / cost_array + order = np.lexsort((np.arange(len(ratios)), -ratios)) + allocation = np.zeros(len(ratios), dtype=float) + remaining = float(budget) + for index in order: + if score_array[index] <= 0 or cost_array[index] > remaining + 1e-12: + continue + allocation[index] = 1.0 + remaining -= cost_array[index] + return allocation + + +def _score_allocation( + policy_name: str, + allocation: np.ndarray, + holdout: pd.DataFrame, + *, + budget: float, + instability: np.ndarray | None = None, +) -> dict[str, float | str | int]: + cost = holdout["treatment_cost"].to_numpy(dtype=float) + effect = holdout["true_incremental_outcome"].to_numpy(dtype=float) + spent = float(np.dot(allocation, cost)) + incremental = float(np.dot(allocation, effect)) + if spent > budget + 1e-8: + raise AssertionError(f"{policy_name} allocation exceeds budget") + mean_instability = ( + float(np.average(instability, weights=allocation)) + if instability is not None and allocation.sum() > 0 + else 0.0 + ) + return { + "policy": policy_name, + "expected_incremental_outcome": incremental, + "budget_spent": spent, + "budget": float(budget), + "budget_efficiency": incremental / spent if spent > 0 else 0.0, + "selected_equivalent_units": float(allocation.sum()), + "selected_share": float(allocation.mean()), + "mean_model_instability": mean_instability, + "holdout_rows": int(len(holdout)), + "evidence_type": "semi_synthetic_causal_holdout", + } + + +def evaluate_budget_policies( + train: pd.DataFrame, + holdout: pd.DataFrame, + config: PolicyConfig, + *, + features: Sequence[str] = DEFAULT_FEATURES, +) -> pd.DataFrame: + """Compare no/random/uniform/rule/model policies on an honest holdout. + + ``train`` and ``holdout`` must be generated from independent draws. The function + rejects overlapping ``generation_seed`` values when that provenance is present. + """ + + _validate_policy_frame(train, features, training=True) + _validate_policy_frame(holdout, features, training=False) + if "generation_seed" in train and "generation_seed" in holdout: + train_seeds = set(train["generation_seed"].unique()) + holdout_seeds = set(holdout["generation_seed"].unique()) + if train_seeds.intersection(holdout_seeds): + raise ValueError("training and holdout generation seeds must be disjoint") + + costs = holdout["treatment_cost"].to_numpy(dtype=float) + n_rows = len(holdout) + no_treatment = np.zeros(n_rows, dtype=float) + + random_rng = np.random.default_rng(config.seed + 50_000) + random_score = random_rng.random(n_rows) + random_allocation = allocate_ranked(random_score, costs, config.budget) + + total_cost = float(costs.sum()) + uniform_intensity = min(1.0, config.budget / total_cost) if total_cost else 0.0 + uniform_allocation = np.full(n_rows, uniform_intensity, dtype=float) + + rule_score = ( + holdout["baseline_demand"].to_numpy(dtype=float) + * holdout["market_tightness"].to_numpy(dtype=float) + ) + rule_allocation = allocate_ranked(rule_score, costs, config.budget) + + conservative, raw_prediction, instability = _fit_stability_adjusted_scores( + train, + holdout, + features=features, + config=config, + ) + model_allocation = allocate_ranked(conservative, costs, config.budget) + + rows = [ + _score_allocation("no_treatment", no_treatment, holdout, budget=config.budget), + _score_allocation("random", random_allocation, holdout, budget=config.budget), + _score_allocation("uniform", uniform_allocation, holdout, budget=config.budget), + _score_allocation("rule_based", rule_allocation, holdout, budget=config.budget), + _score_allocation( + "model_based", + model_allocation, + holdout, + budget=config.budget, + instability=instability, + ), + ] + result = pd.DataFrame(rows) + result["model_mean_predicted_effect"] = np.nan + result.loc[result["policy"] == "model_based", "model_mean_predicted_effect"] = float( + np.mean(raw_prediction[model_allocation > 0]) if model_allocation.sum() else 0.0 + ) + random_value = float( + result.loc[result["policy"] == "random", "expected_incremental_outcome"].iloc[0] + ) + result["incremental_outcome_vs_random"] = result["expected_incremental_outcome"] - random_value + return result.sort_values("policy").reset_index(drop=True) + + +def run_policy_benchmark( + config: PolicyConfig, + *, + n_train: int = 2_000, + n_holdout: int = 1_000, +) -> pd.DataFrame: + """Convenience wrapper using disjoint deterministic simulation seeds.""" + + train = generate_policy_learning_sample( + n_train, + seed=config.seed, + incentive_cost=config.incentive_cost, + ) + holdout = generate_policy_learning_sample( + n_holdout, + seed=config.seed + 1, + incentive_cost=config.incentive_cost, + ) + return evaluate_budget_policies(train, holdout, config) + diff --git a/CasualLab/src/casuallab/reporting.py b/CasualLab/src/casuallab/reporting.py new file mode 100644 index 0000000000000000000000000000000000000000..e3fb485e4d87ba4323083509c1437eb738dc4b62 --- /dev/null +++ b/CasualLab/src/casuallab/reporting.py @@ -0,0 +1,514 @@ +"""Generate auditable Markdown decision artifacts from computed outputs.""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Iterable +from pathlib import Path + +import numpy as np +import pandas as pd + +from casuallab.estimands import get_estimand + +_EXPECTED_POLICY_NAMES = frozenset( + {"no_treatment", "random", "uniform", "rule_based", "model_based"} +) + + +def _strict_boolean(series: pd.Series, name: str) -> pd.Series: + if pd.api.types.is_bool_dtype(series): + if series.isna().any(): + raise ValueError(f"{name} contains missing values") + return series.astype(bool) + normalized = series.astype(str).str.strip().str.lower() + mapping = {"true": True, "false": False, "1": True, "0": False} + invalid = ~normalized.isin(mapping) + if invalid.any(): + raise ValueError(f"{name} must contain explicit booleans") + return normalized.map(mapping).astype(bool) + + +def _validate_policy_provenance(policy: pd.DataFrame) -> tuple[set[int], set[int]]: + """Fail closed when policy rows cannot be shown to share one holdout contract.""" + + required = { + "policy", + "training_markets", + "holdout_markets", + "training_market_seeds", + "holdout_market_seeds", + "target_estimand", + "target_population_id", + "n_zones", + "n_periods", + "weighting", + "simulation_config", + "policy_config", + } + missing = required.difference(policy.columns) + if missing: + raise ValueError(f"policy provenance missing columns: {sorted(missing)}") + names = policy["policy"].astype(str) + if names.duplicated().any() or set(names) != _EXPECTED_POLICY_NAMES: + raise ValueError( + "policy artifact must contain exactly one row for every predeclared baseline " + "and learned policy" + ) + consistent = required.difference({"policy"}) + inconsistent = [ + column for column in sorted(consistent) if policy[column].nunique(dropna=False) != 1 + ] + if inconsistent: + raise ValueError(f"policy provenance differs across rows: {inconsistent}") + try: + train_seeds = set(json.loads(str(policy["training_market_seeds"].iloc[0]))) + holdout_seeds = set(json.loads(str(policy["holdout_market_seeds"].iloc[0]))) + training_markets = int(policy["training_markets"].iloc[0]) + holdout_markets = int(policy["holdout_markets"].iloc[0]) + except (TypeError, ValueError, json.JSONDecodeError) as exc: + raise ValueError("policy seed/count provenance is malformed") from exc + if len(train_seeds) != training_markets or len(holdout_seeds) != holdout_markets: + raise ValueError("policy seed counts do not match declared market counts") + if train_seeds.intersection(holdout_seeds): + raise ValueError("policy training and holdout seeds overlap") + if policy["target_estimand"].iloc[0] != "full_horizon_incremental_trips": + raise ValueError("policy artifact has an unsupported target estimand") + return train_seeds, holdout_seeds + + +def sha256_file(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def _format_value(value: object) -> str: + if value is None or (isinstance(value, float) and np.isnan(value)): + return "—" + if isinstance(value, (float, np.floating)): + return f"{float(value):.4f}" + return str(value).replace("|", "\\|").replace("\n", " ") + + +def markdown_table(frame: pd.DataFrame, columns: Iterable[str]) -> str: + selected = list(columns) + missing = set(selected).difference(frame.columns) + if missing: + raise ValueError(f"table columns missing: {sorted(missing)}") + header = "| " + " | ".join(selected) + " |" + separator = "|" + "|".join(["---"] * len(selected)) + "|" + rows = [ + "| " + " | ".join(_format_value(value) for value in row) + " |" + for row in frame[selected].itertuples(index=False, name=None) + ] + return "\n".join([header, separator, *rows]) + + +def choose_recommendation( + benchmark: pd.DataFrame, + target_estimand: str, + *, + require_declared_scenarios: bool = True, +) -> pd.Series: + """Choose a safe design, optionally within an already matched scenario subset. + + Reports use the strict default and require every declared sensitivity scenario. + A decision interface may set ``require_declared_scenarios=False`` only after it + has independently validated the complete artifact and exactly matched all + causally relevant controls for the displayed scenario. + """ + required = { + "design", + "estimator", + "target_estimand", + "rmse", + "coverage", + "power", + "bias", + "identified", + "inference_valid", + "fit_complete", + "applicable", + "attempted_fits", + "successful_fits", + } + missing = required.difference(benchmark.columns) + if missing: + raise ValueError(f"benchmark results missing columns: {sorted(missing)}") + relevant = benchmark.loc[benchmark["target_estimand"] == target_estimand].copy() + if relevant.empty: + raise ValueError(f"no generated result targets {target_estimand!r}") + compatible_designs = set(get_estimand(target_estimand).compatible_designs) + relevant = relevant.loc[relevant["design"].isin(compatible_designs)] + if relevant.empty: + raise ValueError( + f"no benchmark rows use a design compatible with {target_estimand!r}" + ) + + for column in ("identified", "inference_valid", "fit_complete", "applicable"): + relevant[column] = _strict_boolean(relevant[column], column) + scenario_column = "scenario" if "scenario" in relevant else None + observed_scenarios = ( + set(relevant[scenario_column].dropna().astype(str)) + if scenario_column is not None + else {"single_scenario"} + ) + if "declared_scenario_set" in relevant: + declarations = relevant["declared_scenario_set"].dropna().astype(str).unique() + if len(declarations) != 1: + raise ValueError("benchmark rows do not share one declared scenario set") + try: + parsed_scenarios = json.loads(declarations[0]) + except json.JSONDecodeError as exc: + raise ValueError("declared scenario set is malformed JSON") from exc + if not isinstance(parsed_scenarios, list) or not all( + isinstance(item, str) and item for item in parsed_scenarios + ): + raise ValueError("declared scenario set must be a nonempty JSON string list") + declared_scenarios = set(parsed_scenarios) + if not declared_scenarios or not observed_scenarios.issubset(declared_scenarios): + raise ValueError("observed benchmark rows are outside the declared scenario set") + if require_declared_scenarios and observed_scenarios != declared_scenarios: + raise ValueError("observed benchmark rows do not cover the declared scenario set") + if "declared_scenario_count" in relevant: + counts = pd.to_numeric(relevant["declared_scenario_count"], errors="coerce") + if counts.isna().any() or not counts.eq(len(declared_scenarios)).all(): + raise ValueError("declared scenario count is inconsistent") + else: + declared_scenarios = observed_scenarios + evaluated_scenarios = ( + declared_scenarios if require_declared_scenarios else observed_scenarios + ) + eligible_groups: list[pd.DataFrame] = [] + for _, group in relevant.groupby(["design", "estimator"], dropna=False, sort=True): + present_scenarios = ( + set(group[scenario_column].dropna().astype(str)) + if scenario_column is not None + else {"single_scenario"} + ) + identified_everywhere = bool(group["identified"].all()) + valid_inference_everywhere = bool(group["inference_valid"].all()) + complete_everywhere = bool( + group["applicable"].all() + and (group["attempted_fits"] > 0).all() + and group["fit_complete"].all() + and (group["attempted_fits"] == group["successful_fits"]).all() + ) + nominal = ( + group["confidence_level"] + if "confidence_level" in group + else pd.Series(0.95, index=group.index) + ) + coverage_mcse = ( + group["coverage_mcse"].fillna(0.0) + if "coverage_mcse" in group + else pd.Series(0.0, index=group.index) + ) + # Coverage must be plausibly within ten percentage points of nominal after + # allowing two Monte Carlo standard errors. Precision cannot compensate for + # catastrophically invalid uncertainty. + coverage_valid_everywhere = bool( + (group["coverage"] + 2.0 * coverage_mcse >= nominal - 0.10).all() + ) + if ( + present_scenarios == evaluated_scenarios + and identified_everywhere + and valid_inference_everywhere + and complete_everywhere + and coverage_valid_everywhere + ): + eligible_groups.append(group) + if not eligible_groups: + scenario_scope = ( + "the full declared scenario set" + if require_declared_scenarios + else "the exact matched scenario subset" + ) + raise ValueError( + "no design-estimator pair has complete fits and is identified with valid " + f"inference across {scenario_scope}" + ) + eligible = pd.concat(eligible_groups, ignore_index=False) + eligible = eligible.loc[ + np.isfinite(eligible["bias"]) + & np.isfinite(eligible["rmse"]) + & np.isfinite(eligible["coverage"]) + & np.isfinite(eligible["power"]) + ].copy() + if eligible.empty: + raise ValueError("no robust candidate has finite decision metrics") + finite_scenarios = ( + set(eligible[scenario_column].dropna().astype(str)) + if scenario_column is not None + else {"single_scenario"} + ) + if finite_scenarios != evaluated_scenarios: + raise ValueError("finite decision metrics do not cover the evaluated scenario set") + + nominal = ( + eligible["confidence_level"] if "confidence_level" in eligible else pd.Series(0.95, index=eligible.index) + ) + eligible["coverage_gap"] = (eligible["coverage"] - nominal).abs() + # RMSE is primary; a large coverage failure is explicitly penalized rather than + # hidden behind a single precision statistic. When the file contains a + # sensitivity grid, choose on each pair's worst configured scenario instead of + # opportunistically selecting the easiest row. + eligible["decision_score"] = eligible["rmse"] * (1.0 + 2.0 * eligible["coverage_gap"]) + pair_columns = ["design", "estimator"] + worst_indices = eligible.groupby(pair_columns, dropna=False)["decision_score"].idxmax() + robust_candidates = eligible.loc[worst_indices].copy() + robust_candidates["selection_rule"] = ( + "among complete identified fits passing the coverage gate, minimize " + "worst-scenario RMSE with coverage penalty" + if require_declared_scenarios + else "within the exact matched scenario subset, among complete identified fits " + "passing the coverage gate, minimize worst-scenario RMSE with coverage penalty" + ) + robust_candidates["declared_scenarios"] = len(declared_scenarios) + robust_candidates["evaluated_scenarios"] = len(evaluated_scenarios) + robust_candidates["recommendation_scope"] = ( + "declared_sensitivity_set" + if require_declared_scenarios + else "selected_scenario_conditional" + ) + robust_candidates["unmatched_declared_scenarios"] = json.dumps( + sorted(declared_scenarios.difference(evaluated_scenarios)), + separators=(",", ":"), + ) + return robust_candidates.sort_values( + ["decision_score", "coverage_gap", "power", "design", "estimator"], + ascending=[True, True, False, True, True], + ).iloc[0] + + +def design_limitations(design: str) -> str: + """Return the operational and identification caveat for a design family.""" + + limitations = { + "individual": ( + "Requires negligible cross-unit interference or a correct exposure model; " + "market reallocation can make the individual contrast differ from total marketplace impact." + ), + "geo_cluster": ( + "Needs enough independent geographic clusters and limited leakage across boundaries; " + "cluster-level uncertainty is unreliable with very few treated clusters." + ), + "time_block": ( + "Vulnerable to time shocks and persistence across block boundaries; use predeclared blocks, " + "time controls, and a washout supported by sensitivity analysis." + ), + "switchback": ( + "Relies on a credible washout and stable time pattern; carryover or anticipatory behavior can " + "contaminate subsequent periods." + ), + "geo_time": ( + "Needs two-way cluster-aware inference and explicit spatial/temporal exposure mapping; " + "operational complexity may reduce compliance." + ), + "geo_time_clustered": ( + "Needs two-way cluster-aware inference and explicit spatial/temporal exposure mapping; " + "operational complexity may reduce compliance." + ), + } + return limitations.get( + design, + "Validate assignment integrity, exposure mapping, effective sample size, and interference sensitivity.", + ) + + +def generate_decision_appendix( + benchmark_path: str | Path, + *, + output_path: str | Path, + policy_path: str | Path | None = None, + target_estimand: str | None = None, +) -> Path: + """Generate a Markdown appendix using only computed CSV quantities.""" + + benchmark_file = Path(benchmark_path) + benchmark = pd.read_csv(benchmark_file) + if benchmark.empty: + raise ValueError("benchmark results are empty") + if "evidence_type" not in benchmark: + raise ValueError("benchmark results must label evidence_type") + if not benchmark["evidence_type"].astype(str).str.startswith("semi_synthetic").all(): + raise ValueError("benchmark results contain unlabeled or non-simulation causal claims") + + available_estimands = sorted(benchmark["target_estimand"].dropna().astype(str).unique()) + selected_estimand = target_estimand or available_estimands[0] + recommendation_error: str | None = None + try: + recommendation = choose_recommendation(benchmark, selected_estimand) + except ValueError as exc: + recommendation = None + recommendation_error = str(exc) + relevant = benchmark.loc[benchmark["target_estimand"] == selected_estimand].copy() + table_columns = [ + column + for column in ( + "scenario", + "spillover_strength", + "persistence", + "treatment_duration", + "washout_periods", + "configured_geo_clusters", + "effective_randomization_clusters", + "cluster_semantics", + "budget_scope", + "design", + "estimator", + "comparison_status", + "bias", + "rmse", + "coverage", + "power", + "mean_std_error", + "normalized_precision_cost", + "identified", + "inference_valid", + "attempted_fits", + "successful_fits", + "failed_fits", + "fit_complete", + ) + if column in relevant + ] + + policy_section = ( + "Policy results were not supplied. Run the policy benchmark before making an allocation recommendation." + ) + policy_hash_line = "" + if policy_path is not None: + policy_file = Path(policy_path) + policy = pd.read_csv(policy_file) + required_policy = { + "policy", + "expected_incremental_outcome", + "incremental_outcome_se", + "incremental_outcome_p10", + "budget_spent", + "budget_efficiency", + "budget_feasible", + "evaluation_complete", + "policy_eligible", + "decision_instability", + "training_market_seeds", + "holdout_market_seeds", + "training_signal", + "evaluation_engine", + "planning_cost_basis", + "target_estimand", + "evidence_type", + "training_markets", + "holdout_markets", + "target_population_id", + "n_zones", + "n_periods", + "weighting", + "simulation_config", + "policy_config", + } + missing = required_policy.difference(policy.columns) + if missing: + raise ValueError(f"policy results missing columns: {sorted(missing)}") + if not policy["evidence_type"].astype(str).str.startswith("semi_synthetic").all(): + raise ValueError("policy results must be labeled semi-synthetic") + for column in ("budget_feasible", "evaluation_complete", "policy_eligible"): + policy[column] = _strict_boolean(policy[column], column) + if not policy["training_signal"].astype(str).str.contains( + "no structural truth" + ).all(): + raise ValueError("policy artifact does not establish truth-free training") + if not policy["evaluation_engine"].astype(str).str.contains("simulator rerun").all(): + raise ValueError("policy artifact does not establish simulator evaluation") + if not policy["planning_cost_basis"].astype(str).str.contains( + "no treated holdout" + ).all(): + raise ValueError("policy artifact uses an unsafe holdout cost basis") + _validate_policy_provenance(policy) + display = policy.loc[ + policy["budget_feasible"] + & policy["evaluation_complete"] + & policy["policy_eligible"] + ].sort_values( + ["incremental_outcome_p10", "decision_instability", "policy"], + ascending=[False, True, True], + ) + policy_section = markdown_table( + display, + [ + "policy", + "expected_incremental_outcome", + "incremental_outcome_se", + "incremental_outcome_p10", + "budget_spent", + "budget_efficiency", + "mean_model_instability", + "decision_instability", + ], + ) + policy_hash_line = f"- Policy SHA-256: `{sha256_file(policy_file)}`\n" + + if recommendation is None: + recommendation_section = ( + "No design-estimator pair is recommended because none has complete fits and " + "remains identified with valid inference across every declared sensitivity " + "scenario. This is an " + f"informative design gap, not a tie: {_format_value(recommendation_error)}." + ) + else: + recommendation_section = ( + "Among the simulated candidates for this estimand, the predeclared selection " + f"rule—{recommendation['selection_rule']}—chooses **{recommendation['design']}** " + f"assignment with **{recommendation['estimator']}** estimation. The displayed " + "selection row is that pair's adverse configured scenario: generated bias " + f"{_format_value(recommendation['bias'])}, RMSE {_format_value(recommendation['rmse'])}, " + f"interval coverage {_format_value(recommendation['coverage'])}, and power " + f"{_format_value(recommendation['power'])}.\n\n" + "This is conditional on the configured data-generating process and the selection " + "score documented in `src/casuallab/reporting.py`. It is not a universal design " + f"recommendation.\n\nPrimary limitation: " + f"{design_limitations(str(recommendation['design']))}" + ) + + text = f"""# Generated Decision Appendix + +> Evidence type: **semi-synthetic causal benchmark**. Numerical values below are generated by code against known simulator truth. They are not treatment effects estimated from public trip records and are not a promise of production impact. + +## Selected estimand + +`{selected_estimand}` + +## Design and estimator comparison + +{markdown_table(relevant.sort_values(["design", "estimator"]), table_columns)} + +## Conditional recommendation + +{recommendation_section} + +## Honest-holdout budget policy comparison + +{policy_section} + +## Reproducibility metadata + +- Benchmark SHA-256: `{sha256_file(benchmark_file)}` +{policy_hash_line}- Generated from machine-readable outputs; no numerical result is embedded in this template. + +## Required operational checks + +- Confirm the assignment unit can be enforced and noncompliance is measured. +- Predeclare the exposure mapping, primary estimand, metric, inference unit, and stopping rule. +- Run spillover, persistence, washout, and cluster-count sensitivity analyses. +- Check budget delivery, displacement across untreated zones/times, rider welfare, driver welfare, and service quality. +- Re-estimate only after validating randomization and logging integrity. +""" + destination = Path(output_path) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(text, encoding="utf-8") + return destination diff --git a/CasualLab/src/casuallab/simulator.py b/CasualLab/src/casuallab/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..cd4b1bf0f18d6c04a1f54a310c81c5ded5923c58 --- /dev/null +++ b/CasualLab/src/casuallab/simulator.py @@ -0,0 +1,698 @@ +"""Deterministic semi-synthetic two-sided marketplace simulator. + +The simulator is structural rather than a table of canned effects. A seed creates a +fixed set of zone heterogeneity and demand/supply shocks. Observed and +counterfactual assignment schedules are evaluated against those same shocks, so the +returned ground truth is known for each generated market. +""" + +from __future__ import annotations + +from collections.abc import Iterator, Mapping +from dataclasses import dataclass, replace +from typing import Any + +import numpy as np +import pandas as pd +from scipy.optimize import brentq + +from .config import DesignConfig, DesignName, SimulationConfig, TreatmentVersion +from .designs import generate_assignment +from .estimands import GroundTruth, compute_ground_truth + + +@dataclass(frozen=True) +class SimulationResult: + """A simulated panel, assignment record, counterfactual truth, and provenance.""" + + panel: pd.DataFrame + ground_truth: GroundTruth + assignment: pd.DataFrame + metadata: Mapping[str, Any] + counterfactuals: Mapping[str, pd.DataFrame] + + @property + def data(self) -> pd.DataFrame: + """Alias used by estimator and benchmark callers.""" + + return self.panel + + @property + def truth(self) -> GroundTruth: + return self.ground_truth + + def __iter__(self) -> Iterator[pd.DataFrame | GroundTruth]: + """Allow ``panel, truth = simulate_market(...)`` without hiding metadata.""" + + yield self.panel + yield self.ground_truth + + +def _coerce_config(config: SimulationConfig | Mapping[str, Any] | None) -> SimulationConfig: + if config is None: + return SimulationConfig() + if isinstance(config, SimulationConfig): + return config + if isinstance(config, Mapping): + return SimulationConfig.from_dict(config) + raise TypeError("config must be SimulationConfig, a mapping, or None") + + +def _adjacency(n_zones: int) -> np.ndarray: + """Row-normalized ring adjacency used as the declared exposure mapping.""" + + weights = np.zeros((n_zones, n_zones), dtype=float) + if n_zones == 1: + return weights + if n_zones == 2: + weights[0, 1] = weights[1, 0] = 1.0 + return weights + for zone in range(n_zones): + weights[zone, (zone - 1) % n_zones] = 0.5 + weights[zone, (zone + 1) % n_zones] = 0.5 + return weights + + +def _make_exogenous_state(config: SimulationConfig) -> pd.DataFrame: + rng = np.random.default_rng(config.seed) + n_zones, n_periods = config.n_zones, config.n_periods + + zone_demand_log = rng.normal( + -0.5 * config.zone_heterogeneity_sd**2, + config.zone_heterogeneity_sd, + size=n_zones, + ) + zone_supply_log = ( + 0.35 * zone_demand_log + + rng.normal( + -0.5 * config.zone_heterogeneity_sd**2, + config.zone_heterogeneity_sd, + size=n_zones, + ) + ) + zone_demand_factor = np.exp(zone_demand_log) + zone_supply_factor = np.exp(zone_supply_log) + + periods = np.arange(n_periods) + hour = periods % config.periods_per_day + angle = 2.0 * np.pi * hour / config.periods_per_day + # A deterministic two-harmonic cycle creates peaks without using observed + # outcomes to decide treatment. + demand_cycle = np.exp( + config.time_pattern_strength * (0.75 * np.sin(angle - 0.8) - 0.35 * np.cos(2 * angle)) + ) + supply_cycle = np.exp(0.45 * config.time_pattern_strength * np.sin(angle - 1.1)) + demand_shock = np.exp( + rng.normal( + -0.5 * config.demand_noise_sd**2, + config.demand_noise_sd, + size=(n_periods, n_zones), + ) + ) + supply_shock = np.exp( + rng.normal( + -0.5 * config.supply_noise_sd**2, + config.supply_noise_sd, + size=(n_periods, n_zones), + ) + ) + + baseline_demand = ( + config.base_demand + * demand_cycle[:, None] + * zone_demand_factor[None, :] + * demand_shock + ) + baseline_supply = ( + config.base_supply + * supply_cycle[:, None] + * zone_supply_factor[None, :] + * supply_shock + ) + + grid = pd.MultiIndex.from_product( + [range(n_periods), range(n_zones)], names=["period_id", "zone_id"] + ).to_frame(index=False) + grid["unit_id"] = np.arange(len(grid), dtype=int) + grid["hour"] = np.repeat(hour, n_zones) + grid["day"] = grid["period_id"] // config.periods_per_day + grid["hour_sin"] = np.sin(2.0 * np.pi * grid["hour"] / config.periods_per_day) + grid["hour_cos"] = np.cos(2.0 * np.pi * grid["hour"] / config.periods_per_day) + grid["baseline_demand"] = baseline_demand.reshape(-1) + grid["baseline_supply"] = baseline_supply.reshape(-1) + grid["market_tightness"] = grid["baseline_demand"] / ( + config.capacity_per_driver * grid["baseline_supply"] + ) + grid["zone_demand_factor"] = np.tile(zone_demand_factor, n_periods) + grid["zone_supply_factor"] = np.tile(zone_supply_factor, n_periods) + return grid + + +def _validate_assignment( + assignment: pd.DataFrame, + base: pd.DataFrame, + config: SimulationConfig, +) -> pd.DataFrame: + frame = assignment.copy() + rename: dict[str, str] = {} + if "zone_id" not in frame and "zone" in frame: + rename["zone"] = "zone_id" + if "period_id" not in frame and "period" in frame: + rename["period"] = "period_id" + frame = frame.rename(columns=rename) + missing_keys = {"zone_id", "period_id"}.difference(frame.columns) + if missing_keys: + raise ValueError(f"assignments missing columns: {sorted(missing_keys)}") + if frame.duplicated(["zone_id", "period_id"]).any(): + raise ValueError("assignments must contain one row per zone-period") + if "treatment" not in frame: + for candidate in ("treatment_intensity", "assigned_treatment", "assignment"): + if candidate in frame: + frame["treatment"] = frame[candidate] + break + else: + raise ValueError("assignments require treatment or assigned_treatment") + if "assigned_treatment" not in frame: + frame["assigned_treatment"] = frame["treatment"] + + keys = base[["zone_id", "period_id", "unit_id"]] + frame = keys.merge(frame.drop(columns="unit_id", errors="ignore"), on=["zone_id", "period_id"], how="left") + if frame["treatment"].isna().any(): + raise ValueError("assignments do not cover every configured zone-period") + for column in ("treatment", "assigned_treatment"): + values = frame[column].to_numpy(dtype=float) + if not np.isfinite(values).all() or ((values < 0) | (values > 1)).any(): + raise ValueError(f"{column} must be finite and lie in [0, 1]") + + defaults: dict[str, Any] = { + "design": config.design.name.value, + "cluster_id": frame["zone_id"], + "time_block": frame["period_id"], + "randomization_cluster": frame["zone_id"].astype(str), + "treatment_probability": config.design.treatment_probability, + "analysis_eligible": 1, + "washout": 0, + "assignment_seed": config.design.seed if config.design.seed is not None else config.seed + 1, + } + for column, value in defaults.items(): + if column not in frame: + frame[column] = value + frame["planned_treatment"] = frame["treatment"].astype(float) + return frame.sort_values(["period_id", "zone_id"]).reset_index(drop=True) + + +def _persistent_state(treatment: np.ndarray, persistence: float) -> np.ndarray: + state = np.zeros_like(treatment, dtype=float) + carry = np.zeros(treatment.shape[1], dtype=float) + for period in range(treatment.shape[0]): + carry = treatment[period] + persistence * carry + state[period] = carry + return state + + +def _evaluate_path( + base: pd.DataFrame, + treatment: np.ndarray, + config: SimulationConfig, + *, + cross_zone: bool = True, + persistence: float | None = None, +) -> pd.DataFrame: + n_periods, n_zones = config.n_periods, config.n_zones + schedule = np.asarray(treatment, dtype=float).reshape(n_periods, n_zones) + persistence_value = config.persistence if persistence is None else persistence + state = _persistent_state(schedule, persistence_value) + weights = _adjacency(n_zones) + neighbor_treatment = schedule @ weights.T + neighbor_state = state @ weights.T + rider_active = config.treatment_version in { + TreatmentVersion.RIDER_DISCOUNT, + TreatmentVersion.BUNDLED, + } + driver_active = config.treatment_version in { + TreatmentVersion.DRIVER_INCENTIVE, + TreatmentVersion.BUNDLED, + } + driver_dose_scale = ( + config.incentive_per_driver / config.reference_incentive_per_driver + if driver_active + else 0.0 + ) + + if cross_zone: + demand_cross = ( + config.spillover_strength * neighbor_state + if rider_active + else np.zeros_like(state) + ) + supply_cross = ( + 0.5 * config.spillover_strength * driver_dose_scale * neighbor_state + if driver_active + else np.zeros_like(state) + ) + rider_reallocation_signal = ( + config.rider_substitution * (state - neighbor_state) + if rider_active + else np.zeros_like(state) + ) + driver_reallocation_signal = ( + config.driver_mobility * driver_dose_scale * (state - neighbor_state) + if driver_active + else np.zeros_like(state) + ) + else: + demand_cross = np.zeros_like(state) + supply_cross = np.zeros_like(state) + rider_reallocation_signal = np.zeros_like(state) + driver_reallocation_signal = np.zeros_like(state) + + demand_log_change = ( + config.direct_demand_effect * state if rider_active else np.zeros_like(state) + ) + demand_cross + supply_log_change = ( + config.direct_supply_effect * driver_dose_scale * state + if driver_active + else np.zeros_like(state) + ) + supply_cross + # This numerical guard is intentionally far outside ordinary configurations; it + # prevents accidental overflow in stress tests without changing default paths. + demand_multiplier = np.exp(np.clip(demand_log_change, -10.0, 10.0)) + supply_multiplier = np.exp(np.clip(supply_log_change, -10.0, 10.0)) + baseline_demand = base["baseline_demand"].to_numpy().reshape(n_periods, n_zones) + baseline_supply = base["baseline_supply"].to_numpy().reshape(n_periods, n_zones) + demand_before_substitution = baseline_demand * demand_multiplier + supply_before_movement = baseline_supply * supply_multiplier + latent_demand = demand_before_substitution * np.exp( + np.clip(rider_reallocation_signal, -10.0, 10.0) + ) + available_drivers = supply_before_movement * np.exp( + np.clip(driver_reallocation_signal, -10.0, 10.0) + ) + # Substitution and movement redistribute mass within a period. Direct response + # and spillover parameters may expand/contract totals, but the relocation + # channels themselves do not create riders or drivers. + latent_demand *= ( + demand_before_substitution.sum(axis=1) / np.maximum(latent_demand.sum(axis=1), 1e-12) + )[:, None] + available_drivers *= ( + supply_before_movement.sum(axis=1) / np.maximum(available_drivers.sum(axis=1), 1e-12) + )[:, None] + service_capacity = ( + available_drivers * config.capacity_per_driver * config.matching_efficiency + ) + capacity_ratio = service_capacity / np.maximum(latent_demand, 1e-12) + service_probability = -np.expm1(-capacity_ratio) + trips = latent_demand * service_probability + wait_minutes = config.base_wait_minutes * np.power( + latent_demand / np.maximum(service_capacity, 1e-12), 0.70 + ) + wait_minutes = np.clip(wait_minutes, 0.25, 120.0) + rider_schedule = schedule if rider_active else np.zeros_like(schedule) + driver_schedule = schedule if driver_active else np.zeros_like(schedule) + fare = config.base_fare * (1.0 - config.discount_rate * rider_schedule) + rider_discount_cost = trips * config.base_fare * config.discount_rate * rider_schedule + driver_incentive_cost = ( + available_drivers * config.incentive_per_driver * driver_schedule + ) + treatment_cost = rider_discount_cost + driver_incentive_cost + gross_bookings = trips * fare + platform_net_revenue = gross_bookings - driver_incentive_cost + welfare = ( + trips * (config.rider_value - config.operating_cost_per_trip) + - latent_demand * wait_minutes * config.wait_disutility_per_minute + ) + + result = base.copy() + result["treatment_version"] = config.treatment_version.value + result["treatment"] = schedule.reshape(-1) + result["treatment_intensity"] = result["treatment"] + result["neighbor_treatment"] = neighbor_treatment.reshape(-1) + result["persistent_treatment"] = state.reshape(-1) + result["neighbor_persistent_treatment"] = neighbor_state.reshape(-1) + result["latent_demand"] = latent_demand.reshape(-1) + result["available_drivers"] = available_drivers.reshape(-1) + result["demand_before_substitution"] = demand_before_substitution.reshape(-1) + result["supply_before_movement"] = supply_before_movement.reshape(-1) + result["rider_reallocation_signal"] = rider_reallocation_signal.reshape(-1) + result["driver_reallocation_signal"] = driver_reallocation_signal.reshape(-1) + result["service_capacity"] = service_capacity.reshape(-1) + result["service_probability"] = service_probability.reshape(-1) + result["trips"] = trips.reshape(-1) + result["outcome"] = result["trips"] + result["wait_minutes"] = wait_minutes.reshape(-1) + result["fare"] = fare.reshape(-1) + result["rider_discount_cost"] = rider_discount_cost.reshape(-1) + result["driver_incentive_cost"] = driver_incentive_cost.reshape(-1) + result["treatment_cost"] = treatment_cost.reshape(-1) + result["gross_bookings"] = gross_bookings.reshape(-1) + result["platform_net_revenue"] = platform_net_revenue.reshape(-1) + result["welfare"] = welfare.reshape(-1) + return result + + +def _apply_realized_budget( + base: pd.DataFrame, + planned_treatment: np.ndarray, + config: SimulationConfig, + budget: float | None, +) -> tuple[np.ndarray, float, pd.DataFrame]: + planned = np.asarray(planned_treatment, dtype=float) + full_path = _evaluate_path(base, planned, config) + if budget is None or float(full_path["treatment_cost"].sum()) <= budget: + return planned, 1.0, full_path + if budget == 0 or np.allclose(planned, 0): + zero = np.zeros_like(planned) + return zero, 0.0, _evaluate_path(base, zero, config) + + def excess_spend(scale: float) -> float: + path = _evaluate_path(base, planned * scale, config) + return float(path["treatment_cost"].sum() - budget) + + root = float(brentq(excess_spend, 0.0, 1.0, xtol=1e-10, rtol=1e-10, maxiter=60)) + low = max(0.0, root - 1e-10) + realized = planned * low + feasible_path = _evaluate_path(base, realized, config) + # Protect against floating-point pennies above the declared constraint. + spend = float(feasible_path["treatment_cost"].sum()) + if spend > budget + 1e-8: + low *= budget / spend + realized = planned * low + feasible_path = _evaluate_path(base, realized, config) + return realized, float(low), feasible_path + + +def _controlled_zone_contrasts( + base: pd.DataFrame, + control: pd.DataFrame, + config: SimulationConfig, + saturation: float, +) -> tuple[np.ndarray, np.ndarray]: + """Compute own-only and neighbor-only controlled exposure contrasts. + + For each focal zone, the direct schedule treats that zone at the configured + saturation over the policy horizon while holding mapped neighbors at zero. The + spillover schedule leaves the focal zone untreated while treating its ring + neighbors. These controlled exposure contrasts deliberately do not apply the + shared market budget: applying it separately to each focal schedule would change + the treatment version across zones. Effects are extracted only for the focal zone. + """ + + shape = (config.n_periods, config.n_zones) + controlled_direct = np.zeros(len(base), dtype=float) + controlled_spillover = np.zeros(len(base), dtype=float) + y0 = control["trips"].to_numpy(dtype=float) + neighbors = _adjacency(config.n_zones) + for focal_zone in range(config.n_zones): + focal_rows = base["zone_id"].to_numpy(dtype=int) == focal_zone + + own_schedule = np.zeros(shape, dtype=float) + own_schedule[:, focal_zone] = saturation + own_path = _evaluate_path(base, own_schedule.reshape(-1), config) + controlled_direct[focal_rows] = ( + own_path["trips"].to_numpy(dtype=float)[focal_rows] - y0[focal_rows] + ) + + neighbor_schedule = np.zeros(shape, dtype=float) + neighbor_zones = np.flatnonzero(neighbors[focal_zone] > 0) + neighbor_schedule[:, neighbor_zones] = saturation + neighbor_path = _evaluate_path(base, neighbor_schedule.reshape(-1), config) + controlled_spillover[focal_rows] = ( + neighbor_path["trips"].to_numpy(dtype=float)[focal_rows] - y0[focal_rows] + ) + return controlled_direct, controlled_spillover + + +def simulate_market( + config: SimulationConfig | Mapping[str, Any] | None = None, + design: DesignConfig | DesignName | str | pd.DataFrame | None = None, + assignments: pd.DataFrame | None = None, +) -> SimulationResult: + """Simulate a randomized market and matching structural counterfactuals. + + Parameters + ---------- + config: + Typed config or a compatible mapping. + design: + Optional design override or, for convenience, an assignment frame. + assignments: + Optional caller-supplied zone-period schedule. Assignment values are + validated and never generated from outcomes. + """ + + cfg = _coerce_config(config) + if isinstance(design, pd.DataFrame): + if assignments is not None: + raise ValueError("provide assignments either as design or assignments, not both") + assignments = design + design = None + if isinstance(design, DesignConfig): + cfg = replace(cfg, design=design) + elif design is not None: + cfg = replace(cfg, design=replace(cfg.design, name=DesignName.parse(design))) + + base = _make_exogenous_state(cfg) + if assignments is None: + assignment_seed = cfg.design.seed if cfg.design.seed is not None else cfg.seed + 1 + generated = generate_assignment( + cfg.n_zones, + cfg.n_periods, + cfg.design, + seed=assignment_seed, + individuals_per_cell=cfg.individuals_per_cell, + ) + else: + generated = assignments + assignment = _validate_assignment(generated, base, cfg) + + planned = assignment["planned_treatment"].to_numpy(dtype=float) + realized, budget_scale, observed = _apply_realized_budget( + base, planned, cfg, cfg.effective_budget + ) + assignment["treatment"] = realized + assignment["treatment_intensity"] = realized + assignment["budget_scale"] = budget_scale + + zero = np.zeros_like(realized) + control = _evaluate_path(base, zero, cfg) + direct_only = _evaluate_path(base, realized, cfg, cross_zone=False) + short_run = _evaluate_path(base, realized, cfg, persistence=0.0) + full_market_schedule = np.full_like( + realized, cfg.design.treatment_saturation, dtype=float + ) + all_treated_schedule, all_treated_budget_scale, all_treated = _apply_realized_budget( + base, full_market_schedule, cfg, cfg.effective_budget + ) + all_treated_short_run = _evaluate_path( + base, all_treated_schedule, cfg, persistence=0.0 + ) + controlled_direct, controlled_spillover = _controlled_zone_contrasts( + base, + control, + cfg, + cfg.design.treatment_saturation, + ) + no_cross_zone_interference = cfg.n_zones == 1 or all( + value == 0 + for value in ( + cfg.spillover_strength, + cfg.rider_substitution, + cfg.driver_mobility, + ) + ) + itt_available = ( + cfg.design.name is not DesignName.INDIVIDUAL + and no_cross_zone_interference + and cfg.persistence == 0 + and cfg.effective_budget is None + ) + assignment_itt_effects = ( + all_treated["trips"].to_numpy(dtype=float) + - control["trips"].to_numpy(dtype=float) + if itt_available + else None + ) + + truth = compute_ground_truth( + observed, + control, + direct_only=direct_only, + short_run=short_run, + all_treated=all_treated, + all_treated_short_run=all_treated_short_run, + controlled_direct_effects=controlled_direct, + controlled_spillover_effects=controlled_spillover, + all_treated_received=all_treated_schedule, + analysis_eligible=assignment["analysis_eligible"].to_numpy(dtype=bool), + assignment_itt_effects=assignment_itt_effects, + assignment_first_stage=( + cfg.design.treatment_saturation if itt_available else None + ), + assigned_treatment=assignment["assigned_treatment"].to_numpy(dtype=float), + received_treatment=realized, + ) + + assignment_columns = [ + column + for column in assignment.columns + if column not in {"unit_id", "zone_id", "period_id", "treatment", "treatment_intensity"} + ] + panel = observed.merge( + assignment[["unit_id", *assignment_columns]], on="unit_id", how="left", validate="one_to_one" + ) + panel["assigned"] = panel["assigned_treatment"] + panel["zone"] = panel["zone_id"] + panel["period"] = panel["period_id"] + panel["cluster"] = panel["cluster_id"] + panel["y0"] = control["trips"].to_numpy(dtype=float) + panel["y_observed"] = panel["trips"] + panel["true_effect"] = truth.unit_effects["realized_schedule_effect"].to_numpy(dtype=float) + panel["true_full_policy_effect"] = truth.unit_effects[ + "full_policy_total_effect" + ].to_numpy(dtype=float) + panel["true_direct_effect"] = truth.unit_effects["individual_direct_effect"].to_numpy( + dtype=float + ) + panel["true_controlled_zone_direct_effect"] = truth.unit_effects[ + "controlled_direct_effect" + ].to_numpy(dtype=float) + panel["true_spillover_effect"] = truth.unit_effects[ + "controlled_spillover_effect" + ].to_numpy(dtype=float) + panel["true_short_run_effect"] = truth.unit_effects[ + "full_policy_short_run_effect" + ].to_numpy(dtype=float) + panel["true_persistent_effect"] = truth.unit_effects[ + "full_policy_persistent_effect" + ].to_numpy(dtype=float) + panel["evidence_type"] = "semi_synthetic_causal" + panel["simulation_seed"] = cfg.seed + + spend = float(panel["treatment_cost"].sum()) + full_policy_spend = float(all_treated["treatment_cost"].sum()) + budget = cfg.effective_budget + metadata: dict[str, Any] = { + "evidence_type": "semi_synthetic_known_ground_truth", + "simulation_seed": cfg.seed, + "assignment_seed": int(assignment["assignment_seed"].iloc[0]), + "design": cfg.design.name.value, + "n_zones": cfg.n_zones, + "n_periods": cfg.n_periods, + "exposure_mapping": "row-normalized ring adjacency", + "budget": budget, + "realized_spend": spend, + "full_policy_spend": full_policy_spend, + "budget_scale": budget_scale, + "all_treated_budget_scale": all_treated_budget_scale, + "budget_feasible": budget is None or spend <= budget + 1e-8, + "treatment_version": cfg.treatment_version.value, + "treatment_version_description": { + TreatmentVersion.RIDER_DISCOUNT: ( + "rider discount with demand response; driver incentive and supply response disabled" + ), + TreatmentVersion.DRIVER_INCENTIVE: ( + "driver incentive with supply response; rider discount and demand response disabled" + ), + TreatmentVersion.BUNDLED: ( + "rider discount and driver incentive delivered at one common intensity" + ), + }[cfg.treatment_version], + "driver_incentive_response_scale": ( + cfg.incentive_per_driver / cfg.reference_incentive_per_driver + if cfg.treatment_version + in {TreatmentVersion.DRIVER_INCENTIVE, TreatmentVersion.BUNDLED} + else 0.0 + ), + "reference_incentive_per_driver": cfg.reference_incentive_per_driver, + "treatment_version_limitation": ( + "each experiment has one selected treatment version; simultaneous factorial " + "rider-versus-driver arms require separate randomized assignments" + ), + "ground_truth": truth.to_json_dict(), + "ground_truth_definitions": { + "market_total_effect": ( + "all-zone treatment policy versus all-zero, averaged per zone-period " + "over the fixed configured horizon" + ), + "analysis_population_market_total_effect": ( + "the same policy contrast restricted to assignment-specific analysis_eligible rows" + ), + "direct_effect": ( + "individual rider direct effect is unavailable in this aggregate zone-time simulator" + ), + "controlled_zone_direct_effect": ( + "unconstrained focal-zone saturation policy versus zone control with mapped " + "neighbors at zero; the shared market budget is not re-scaled separately " + "for each focal contrast" + ), + "spillover_effect": ( + "untreated focal zone with mapped neighbors treated at configured saturation " + "versus all-zero; the shared market budget is not applied to this controlled " + "exposure contrast" + ), + "short_run_effect": "all-zone policy with persistence disabled versus all-zero", + "persistent_effect": "all-zone total effect minus its no-persistence path", + "intent_to_treat": ( + "randomized-arm assignment contrast when no interference, carryover, or " + "shared-budget coupling is configured; unavailable (NaN) otherwise" + ), + "true_effect_panel_column": "realized mixed-schedule effect versus all-zero", + "full_horizon_incremental_trips": ( + "sum of all-zone policy versus zero effects over every configured zone-period" + ), + "full_policy_spend": "treatment spend for the feasible all-zone policy path", + }, + "ground_truth_availability": { + "direct_effect": { + "available": False, + "reason": "individual rider outcomes are not represented in the aggregate panel", + }, + "controlled_zone_direct_effect": {"available": True, "reason": None}, + "intent_to_treat": { + "available": itt_available, + "reason": ( + None + if itt_available + else "assignment contrast differs from the structural full-policy contrast" + ), + }, + }, + "analysis_rows": int(assignment["analysis_eligible"].sum()), + "analysis_share": float(assignment["analysis_eligible"].mean()), + "target_population_id": ( + f"all_{cfg.n_zones}_zones_x_{cfg.n_periods}_periods_equal_cell_weight" + ), + "estimation_population_id": ( + "full_horizon" + if bool(assignment["analysis_eligible"].astype(bool).all()) + else "assignment_specific_washout_exclusions" + ), + "itt_available": itt_available, + "config": cfg.to_dict(), + } + return SimulationResult( + panel=panel, + ground_truth=truth, + assignment=assignment, + metadata=metadata, + counterfactuals={ + "control": control, + "direct_only": direct_only, + "short_run": short_run, + "all_treated": all_treated, + "all_treated_short_run": all_treated_short_run, + }, + ) + + +def simulate_panel( + config: SimulationConfig | Mapping[str, Any] | None = None, + design: DesignConfig | DesignName | str | pd.DataFrame | None = None, + assignments: pd.DataFrame | None = None, +) -> pd.DataFrame: + """Return only the panel for callers that do not need truth metadata.""" + + return simulate_market(config, design, assignments).panel + + +run_simulation = simulate_market diff --git a/CasualLab/tests/test_analysis.py b/CasualLab/tests/test_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..6b9121efc69139ce7870b23f8fd1d62a37bff6b7 --- /dev/null +++ b/CasualLab/tests/test_analysis.py @@ -0,0 +1,55 @@ +import pandas as pd +import pytest + +from casuallab.analysis import ( + compute_descriptive_moments, + descriptive_tables, + origin_destination_summary, +) + + +def _panel() -> pd.DataFrame: + return pd.DataFrame( + { + "zone_id": [1, 2, 1, 2, 1, 2], + "period_start": pd.date_range("2025-01-01", periods=3, freq="h").repeat(2), + "trip_count": [10, 8, 12, 7, 14, 6], + "average_fare": [12.0, 11.0, 13.0, 11.5, 14.0, 12.0], + "pooled_trip_share": [0.1, 0.2, 0.1, 0.2, 0.0, 0.1], + "panel_grain": ["pickup_zone_x_1h"] * 6, + } + ) + + +def test_descriptive_moments_label_correlations_as_associations() -> None: + moments = compute_descriptive_moments(_panel()) + assert moments["evidence_type"] == "empirical_association" + assert moments["total_observed_trips"] == 57.0 + assert moments["mean_observed_fare"] == pytest.approx( + sum(_panel()["trip_count"] * _panel()["average_fare"]) / 57.0 + ) + assert moments["equal_observed_cell_mean_fare"] == pytest.approx( + _panel()["average_fare"].mean() + ) + assert "not a causal elasticity" in moments["price_endogeneity_warning"] + assert moments["zone_exact_lag_support_pairs"] == 4 + assert moments["zone_exact_lag_minutes"] == 60 + + +def test_descriptive_tables_cover_time_zone_and_comovement() -> None: + tables = descriptive_tables(_panel()) + assert set(tables) == {"demand_by_hour", "demand_by_zone", "cross_zone"} + assert set(tables["demand_by_zone"]["evidence_type"]) == {"empirical_association"} + + +def test_origin_destination_flows_are_normalized_within_origin() -> None: + trips = pd.DataFrame( + { + "pickup_zone": [1, 1, 1, 2], + "dropoff_zone": [2, 2, 3, 1], + } + ) + flows = origin_destination_summary(trips) + shares = flows.groupby("origin_zone")["origin_flow_share"].sum() + assert shares.round(10).eq(1.0).all() + assert set(flows["evidence_type"]) == {"empirical_association"} diff --git a/CasualLab/tests/test_benchmark.py b/CasualLab/tests/test_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..73f18514813bbc70aa7eef9b6e1680094e58f035 --- /dev/null +++ b/CasualLab/tests/test_benchmark.py @@ -0,0 +1,85 @@ +import numpy as np +import pandas as pd + +from casuallab.benchmark import BenchmarkConfig, run_replications, summarize_monte_carlo + + +def test_summary_computes_bias_rmse_coverage_and_power() -> None: + records = pd.DataFrame( + { + "design": ["cluster"] * 3, + "estimator": ["dim"] * 3, + "estimate": [1.0, 2.0, 3.0], + "std_error": [1.0, 1.0, 1.0], + "truth": [2.0, 2.0, 2.0], + "target_estimand": ["total"] * 3, + "design_cost": [2.0] * 3, + } + ) + summary = summarize_monte_carlo(records) + assert summary.loc[0, "bias"] == 0.0 + assert np.isclose(summary.loc[0, "rmse"], np.sqrt(2.0 / 3.0)) + assert summary.loc[0, "coverage"] == 1.0 + assert summary.loc[0, "replications"] == 3 + assert summary.loc[0, "evidence_type"] == "semi_synthetic_causal_monte_carlo" + + +def test_replication_runner_is_deterministic() -> None: + config = BenchmarkConfig( + replications=3, + seed=9, + designs=("individual",), + estimators=("difference_in_means",), + ) + + def callback(design: str, estimator: str, seed: int) -> dict[str, float]: + estimate = float(np.random.default_rng(seed).normal(1.0, 0.2)) + return {"estimate": estimate, "std_error": 0.2, "truth": 1.0} + + first_records, first_summary = run_replications(config, callback) + second_records, second_summary = run_replications(config, callback) + pd.testing.assert_frame_equal(first_records, second_records) + pd.testing.assert_frame_equal(first_summary, second_summary) + + +def test_summary_uses_estimator_specific_intervals_and_p_values() -> None: + records = pd.DataFrame( + { + "design": ["geo_cluster", "geo_cluster"], + "estimator": ["cluster_robust", "cluster_robust"], + "estimate": [1.0, 1.0], + "std_error": [0.01, 0.01], + "truth": [0.0, 0.0], + "ci_low": [-1.0, -1.0], + "ci_high": [2.0, 2.0], + "p_value": [0.2, 0.2], + "scenario": ["few_clusters", "few_clusters"], + "design_cost": [5.0, 5.0], + } + ) + summary = summarize_monte_carlo(records) + assert summary.loc[0, "coverage"] == 1.0 + assert summary.loc[0, "power"] == 0.0 + assert summary.loc[0, "coverage_mcse"] > 0.0 + assert summary.loc[0, "power_mcse"] > 0.0 + assert ( + summary.loc[0, "binomial_mcse_method"] + == "jeffreys_posterior_standard_deviation" + ) + assert summary.loc[0, "information_cost"] == 5.0 + + +def test_replication_varying_diagnostics_do_not_fragment_groups() -> None: + records = pd.DataFrame( + { + "design": ["switchback"] * 3, + "estimator": ["difference_in_means"] * 3, + "estimate": [0.9, 1.0, 1.1], + "std_error": [0.1] * 3, + "truth": [1.0] * 3, + "full_policy_spend": [90.0, 100.0, 110.0], + } + ) + summary = summarize_monte_carlo(records) + assert len(summary) == 1 + assert summary.loc[0, "replications"] == 3 diff --git a/CasualLab/tests/test_calibration.py b/CasualLab/tests/test_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..4f34a090823fdaa1d5eb625ca41528b1d9df0017 --- /dev/null +++ b/CasualLab/tests/test_calibration.py @@ -0,0 +1,28 @@ +import pandas as pd +import pytest + +from casuallab.calibration import calibrate_simulation +from casuallab.config import SimulationConfig + + +def test_calibration_updates_observed_moments_not_causal_assumptions() -> None: + panel = pd.DataFrame( + { + "trip_count": [10, 20, 30], + "average_fare": [8.0, 10.0, 12.0], + "average_trip_seconds": [600, 900, 1200], + } + ) + template = SimulationConfig(direct_demand_effect=0.23, spillover_strength=0.4) + result = calibrate_simulation(panel, template) + assert result.config.base_demand > 20.0 + assert result.config.base_fare == pytest.approx(10.6666666667) + assert result.config.base_supply / result.config.base_demand == ( + template.base_supply / template.base_demand + ) + assert result.config.direct_demand_effect == 0.23 + assert result.config.spillover_strength == 0.4 + assert result.empirical_targets["mean_observed_trip_seconds"] == 1000.0 + assert result.empirical_targets["equal_observed_cell_mean_fare"] == 10.0 + assert abs(result.empirical_targets["completed_trip_calibration_error"]) < 1e-10 + assert "direct_demand_effect" in result.unchanged_structural_assumptions diff --git a/CasualLab/tests/test_cli.py b/CasualLab/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..3f96aa98fd6d3038f01eb526f396e350543ff7b1 --- /dev/null +++ b/CasualLab/tests/test_cli.py @@ -0,0 +1,438 @@ +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import pandas as pd +import pytest + +import casuallab.cli as cli_module +from casuallab.cli import ( + _run_reproduce, + _write_hte_artifacts, + build_parser, + main, + write_simulation_outputs, +) +from casuallab.config import DesignConfig, SimulationConfig +from casuallab.simulator import simulate_market + + +def test_cli_exposes_required_workflow_commands() -> None: + parser = build_parser() + actions = [action for action in parser._actions if action.dest == "command"] + assert len(actions) == 1 + commands = set(actions[0].choices) + assert { + "download-sample", + "build-panel", + "validate-nyc-full", + "simulate", + "benchmark", + "interference-benchmark", + "nyc-simulation-anchor", + "nyc-weather", + "nyc-events", + "nyc-income", + "nyc-benchmark", + "nyc-graph-benchmark", + "equilibrium-benchmark", + "report", + "reproduce-sample", + }.issubset(commands) + report_args = parser.parse_args(["report"]) + reproduce_args = parser.parse_args(["reproduce-sample"]) + assert report_args.nyc_full_validation == "artifacts/nyc_full/validation.json" + assert report_args.nyc_full_manifest == "artifacts/nyc_full/manifest.json" + assert ( + report_args.treatment_version_policy + == "artifacts/benchmarks/treatment_version_policy_results.csv" + ) + assert ( + report_args.treatment_version_policy_manifest + == "artifacts/benchmarks/treatment_version_policy_manifest.json" + ) + assert reproduce_args.nyc_full_validation == "artifacts/nyc_full/validation.json" + assert reproduce_args.nyc_full_manifest == "artifacts/nyc_full/manifest.json" + assert report_args.interference_summary.endswith("interference_summary.csv") + assert report_args.interference_manifest.endswith("interference_manifest.json") + assert report_args.nyc_simulation_anchor.endswith("nyc_simulation_anchor.json") + assert report_args.nyc_simulation_anchor_manifest.endswith("manifest.json") + assert report_args.nyc_benchmark_manifest.endswith("nyc_informed/manifest.json") + assert report_args.nyc_graph_benchmark_manifest.endswith("nyc_graph/manifest.json") + assert report_args.equilibrium_manifest.endswith("equilibrium/manifest.json") + assert report_args.nyc_weather_manifest.endswith("weather/manifest.json") + assert report_args.nyc_events_manifest.endswith("events/manifest.json") + assert report_args.nyc_income_manifest.endswith("income/manifest.json") + weather_args = parser.parse_args(["nyc-weather"]) + assert weather_args.raw.endswith("noaa_central_park_2024-01.csv") + assert weather_args.data_manifest == "data/nyc_full/manifest.json" + event_args = parser.parse_args(["nyc-events"]) + assert event_args.events.endswith("nyc_permitted_events_overlap_2024-01.csv") + assert event_args.holidays.endswith("official_holidays_2024-01.csv") + income_args = parser.parse_args(["nyc-income"]) + assert income_args.taxi_zones.endswith("taxi_zones.zip") + assert income_args.acs_b19001.endswith("acs_2022_5yr_b19001_nyc_tracts.dat") + assert parser.parse_args(["nyc-benchmark"]).replications == 6 + assert parser.parse_args(["nyc-graph-benchmark"]).n_zones == 16 + assert parser.parse_args(["equilibrium-benchmark"]).treatment_version == "bundled" + + +def test_nyc_weather_command_reuses_pinned_raw_and_writes_bundle( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + raw = tmp_path / "weather.csv" + raw.write_text("pinned\n", encoding="utf-8") + generated = tuple(tmp_path / f"weather-{index}.csv" for index in range(5)) + for path in generated: + path.write_text("ok\n", encoding="utf-8") + observed: dict[str, object] = {} + + def download(path: str, *, refresh: bool) -> Path: + observed["download"] = (path, refresh) + return raw + + def write_bundle( + raw_path: Path, + panel_dir: str, + data_manifest: str, + output_dir: str, + *, + project_root: Path, + ) -> object: + observed["writer"] = ( + raw_path, + panel_dir, + data_manifest, + output_dir, + project_root, + ) + return argparse.Namespace(paths=lambda: generated) + + monkeypatch.setattr(cli_module, "download_noaa_daily_weather", download) + monkeypatch.setattr(cli_module, "write_nyc_weather_bundle", write_bundle) + outputs = cli_module._run_nyc_weather( + argparse.Namespace( + raw=str(raw), + panel_dir="panel", + data_manifest="data-manifest.json", + output_dir="weather-output", + refresh=False, + ) + ) + + assert outputs == list(generated) + assert observed["download"] == (str(raw), False) + assert observed["writer"][0] == raw + + +def test_nyc_events_and_income_commands_use_pinned_inputs( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + generated = tuple(tmp_path / f"artifact-{index}.csv" for index in range(7)) + for path in generated: + path.write_text("ok\n", encoding="utf-8") + observed: dict[str, object] = {} + + def download(path: str, *, refresh: bool) -> Path: + observed["event_download"] = (path, refresh) + return Path(path) + + def event_writer(*args: object, project_root: Path) -> object: + observed["event_writer"] = (*args, project_root) + return argparse.Namespace(paths=lambda: generated) + + def income_writer(*args: object, project_root: Path) -> object: + observed["income_writer"] = (*args, project_root) + return argparse.Namespace(paths=lambda: generated) + + monkeypatch.setattr(cli_module, "download_nyc_permitted_events_snapshot", download) + monkeypatch.setattr(cli_module, "write_nyc_events_bundle", event_writer) + monkeypatch.setattr(cli_module, "write_nyc_income_bundle", income_writer) + event_outputs = cli_module._run_nyc_events( + argparse.Namespace( + holidays="holidays.csv", + events="events.csv", + panel_dir="panel", + data_manifest="manifest.json", + output_dir="event-output", + refresh=False, + ) + ) + income_outputs = cli_module._run_nyc_income( + argparse.Namespace( + taxi_zones="taxi.zip", + nta="nta.geojson", + tract_to_nta="tract.csv", + acs_b19001="acs.dat", + panel_dir="panel", + data_manifest="manifest.json", + output_dir="income-output", + ) + ) + + assert event_outputs == list(generated) + assert income_outputs == list(generated) + assert observed["event_download"] == ("events.csv", False) + assert observed["event_writer"][:5] == ( + "holidays.csv", + Path("events.csv"), + "panel", + "manifest.json", + "event-output", + ) + assert observed["income_writer"][:7] == ( + "taxi.zip", + "nta.geojson", + "tract.csv", + "acs.dat", + "panel", + "manifest.json", + "income-output", + ) + + +def test_offline_enrichment_gate_distinguishes_absent_partial_and_complete( + tmp_path: Path, +) -> None: + nyc_manifest = tmp_path / "manifest.json" + panel = tmp_path / "panel" + source_a = tmp_path / "source-a.csv" + source_b = tmp_path / "source-b.csv" + + assert ( + cli_module._offline_enrichment_ready( + "fixture", + nyc_dependencies=(nyc_manifest, panel), + external_sources=(source_a, source_b), + ) + is False + ) + nyc_manifest.write_text("{}", encoding="utf-8") + with pytest.raises(ValueError, match="complete NYC dependencies"): + cli_module._offline_enrichment_ready( + "fixture", + nyc_dependencies=(nyc_manifest, panel), + external_sources=(source_a, source_b), + ) + panel.mkdir() + assert ( + cli_module._offline_enrichment_ready( + "fixture", + nyc_dependencies=(nyc_manifest, panel), + external_sources=(source_a, source_b), + ) + is False + ) + source_a.write_text("a", encoding="utf-8") + with pytest.raises(ValueError, match="every pinned external source"): + cli_module._offline_enrichment_ready( + "fixture", + nyc_dependencies=(nyc_manifest, panel), + external_sources=(source_a, source_b), + ) + source_b.write_text("b", encoding="utf-8") + assert cli_module._offline_enrichment_ready( + "fixture", + nyc_dependencies=(nyc_manifest, panel), + external_sources=(source_a, source_b), + ) + + +def test_cli_help_exits_successfully(capsys: pytest.CaptureFixture[str]) -> None: + with pytest.raises(SystemExit) as raised: + main(["--help"]) + assert raised.value.code == 0 + assert "reproduce-sample" in capsys.readouterr().out + + +def test_full_data_requires_explicit_build_opt_in_and_cannot_reproduce( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + config_path = tmp_path / "full.yaml" + config_path.write_text( + "\n".join( + [ + "source: nyc_hvfhv", + "mode: full", + f"project_root: {tmp_path}", + "raw_dir: raw", + "clean_dir: clean", + "panel_dir: panel", + "nyc_months: [1]", + ] + ), + encoding="utf-8", + ) + + def unexpected_pipeline(*_args: object, **_kwargs: object) -> object: + raise AssertionError("full pipeline ran before explicit opt-in") + + monkeypatch.setattr(cli_module, "run_data_pipeline", unexpected_pipeline) + with pytest.raises(ValueError, match="--allow-full-download"): + main(["build-panel", "--config", str(config_path)]) + with pytest.raises(ValueError, match="--allow-full-download"): + main(["validate-nyc-full", "--config", str(config_path)]) + + args = argparse.Namespace( + output_root=str(tmp_path / "artifacts"), + config=str(config_path), + simulation_config="configs/simulation.yaml", + benchmark_config="configs/benchmark.yaml", + policy_config="configs/policy.yaml", + refresh=False, + ) + with pytest.raises(ValueError, match="bounded mode: sample"): + _run_reproduce(args) + assert not (tmp_path / "artifacts/REPRODUCE_INCOMPLETE.json").exists() + + +def test_validate_nyc_full_publishes_empirical_calibration_bundle( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + config = argparse.Namespace( + source="nyc_hvfhv", + mode="full", + raw_dir=tmp_path / "raw", + ) + config.raw_dir.mkdir() + data_manifest = tmp_path / "data-manifest.json" + diagnostics = tmp_path / "diagnostics.json" + analysis_file = tmp_path / "analysis.json" + calibration_file = tmp_path / "calibration.json" + for path in (data_manifest, diagnostics, analysis_file, calibration_file): + path.write_text("{}\n", encoding="utf-8") + data_artifacts = argparse.Namespace( + raw_files=(), + diagnostics_path=diagnostics, + manifest_path=data_manifest, + ) + analysis = argparse.Namespace(paths=lambda: (analysis_file,)) + calibration = argparse.Namespace(paths=lambda: (calibration_file,)) + + monkeypatch.setattr(cli_module, "load_data_config", lambda _path: config) + monkeypatch.setattr(cli_module, "nyc_hvfhv_urls", lambda _config: ()) + monkeypatch.setattr(cli_module, "run_data_pipeline", lambda *_args, **_kwargs: data_artifacts) + monkeypatch.setattr(cli_module, "write_nyc_full_analysis", lambda *_args, **_kwargs: analysis) + observed_output: list[Path] = [] + + def write_calibration(_config: object, output: Path) -> object: + observed_output.append(output) + return calibration + + monkeypatch.setattr(cli_module, "write_nyc_calibration_bundle", write_calibration) + outputs = cli_module._run_validate_nyc_full( + argparse.Namespace( + config="configs/full.yaml", + output_dir=str(tmp_path / "artifacts"), + refresh=False, + allow_full_download=True, + ) + ) + + assert observed_output == [tmp_path / "artifacts/calibration_network"] + assert calibration_file in outputs + + +def test_simulation_writer_uses_strict_json_for_unavailable_truth(tmp_path: Path) -> None: + config = SimulationConfig( + n_zones=3, + n_periods=8, + spillover_strength=0.2, + persistence=0.3, + design=DesignConfig(name="geo_cluster", n_clusters=3, seed=8), + seed=7, + ) + outputs = write_simulation_outputs(simulate_market(config), tmp_path) + metadata_text = outputs["metadata"].read_text(encoding="utf-8") + metadata = json.loads(metadata_text) + assert ": NaN" not in metadata_text + assert metadata["ground_truth"]["direct_effect"] is None + assert metadata["ground_truth"]["intent_to_treat"] is None + assert all(path.is_file() for path in outputs.values()) + + +def test_hte_artifact_uses_cluster_holdout_and_known_matching_truth(tmp_path: Path) -> None: + outputs = _write_hte_artifacts( + SimulationConfig(n_zones=4, n_periods=16, seed=19), + tmp_path, + ) + summary = json.loads(outputs["summary"].read_text(encoding="utf-8")) + assert summary["target_estimand"] == "controlled_zone_direct_effect" + assert summary["crossfit_group"] == "geographic_randomization_cluster" + assert summary["interference"] == 0.0 + assert summary["persistence"] == 0.0 + assert summary["rows"] == 8 * 16 + calibration = pd.read_csv(outputs["calibration"]) + assert { + "mean_predicted_cate", + "mean_known_truth", + "mean_error", + "rmse", + "rows", + }.issubset(calibration.columns) + subgroup = pd.read_csv(outputs["subgroup_recovery"]) + assert {"mean_predicted_cate", "mean_known_truth", "mean_error"}.issubset( + subgroup.columns + ) + stability = pd.read_csv(outputs["fold_stability"]) + assert stability["crossfit_fold"].nunique() == 4 + assert outputs["calibration_chart"].read_text(encoding="utf-8").startswith("") + assert all(path.is_file() for path in outputs.values()) + + +def test_reproduce_marker_invalidates_old_manifest_and_survives_failure( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + output_root = tmp_path / "artifacts" + output_root.mkdir() + old_manifest = output_root / "reproduce_manifest.json" + old_manifest.write_text("{}", encoding="utf-8") + + def fail(_args: argparse.Namespace) -> list[Path]: + raise RuntimeError("synthetic failure") + + monkeypatch.setattr(cli_module, "_run_reproduce_inner", fail) + args = argparse.Namespace( + output_root=str(output_root), + config="configs/sample.yaml", + simulation_config="configs/simulation.yaml", + benchmark_config="configs/benchmark.yaml", + policy_config="configs/policy.yaml", + ) + with pytest.raises(RuntimeError, match="synthetic failure"): + _run_reproduce(args) + assert not old_manifest.exists() + marker = output_root / "REPRODUCE_INCOMPLETE.json" + assert marker.is_file() + assert json.loads(marker.read_text(encoding="utf-8"))["status"] == "incomplete" + + +def test_reproduce_marker_is_removed_only_after_final_manifest( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + output_root = tmp_path / "artifacts" + + def succeed(args: argparse.Namespace) -> list[Path]: + manifest = Path(args.output_root) / "reproduce_manifest.json" + manifest.write_text('{"files": []}', encoding="utf-8") + return [manifest] + + monkeypatch.setattr(cli_module, "_run_reproduce_inner", succeed) + args = argparse.Namespace( + output_root=str(output_root), + config="configs/sample.yaml", + simulation_config="configs/simulation.yaml", + benchmark_config="configs/benchmark.yaml", + policy_config="configs/policy.yaml", + ) + outputs = _run_reproduce(args) + assert outputs == [output_root / "reproduce_manifest.json"] + assert not (output_root / "REPRODUCE_INCOMPLETE.json").exists() diff --git a/CasualLab/tests/test_dashboard.py b/CasualLab/tests/test_dashboard.py new file mode 100644 index 0000000000000000000000000000000000000000..6d7b936d8c8668ad39619eaeee1c3975f178feaa --- /dev/null +++ b/CasualLab/tests/test_dashboard.py @@ -0,0 +1,1474 @@ +import hashlib +import json +from dataclasses import replace +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +from casuallab.benchmark import BenchmarkConfig +from casuallab.config import DesignConfig, DesignName, SimulationConfig, TreatmentVersion +from casuallab.dashboard import ( + DashboardControls, + _recommended_design_caveat, + _source_tree_sha256, + artifact_decision, + build_simulation_config, + evidence_layer_rows, + load_benchmark_artifact, + load_calibration_template, + load_evidence_layers, + match_benchmark_artifact, + run_scenario_benchmark, +) +from casuallab.marketplace_benchmark import SensitivityScenario, run_marketplace_benchmark + + +def _small_controls(**overrides: object) -> DashboardControls: + values: dict[str, object] = { + "experiment_duration": 12, + "n_clusters": 4, + "treatment_duration": 3, + "washout_periods": 1, + "budget": 800.0, + "replications": 2, + "seed": 71, + } + values.update(overrides) + return DashboardControls(**values) + + +def _write_json(path: Path, payload: object) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8") + return path + + +def _hashed_entry(path: Path, rendered_path: str, **extra: object) -> dict[str, object]: + return { + "path": rendered_path, + "bytes": path.stat().st_size, + "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), + **extra, + } + + +def _evidence_layer_fixture(root: Path) -> dict[str, Path]: + source = root / "src/example.py" + source.parent.mkdir(parents=True) + source.write_text("VALUE = 1\n", encoding="utf-8") + manifests: dict[str, Path] = {} + + for key, directory_name, artifact_type, evidence in ( + ( + "nyc_informed", + "nyc_informed", + "nyc_informed_marketplace_benchmark", + "semi_synthetic_nyc_informed_known_truth_monte_carlo", + ), + ( + "nyc_graph", + "nyc_graph", + "nyc_graph_interference_benchmark", + "semi_synthetic_known_truth_on_descriptive_nyc_graph", + ), + ): + directory = root / f"artifacts/benchmarks/{directory_name}" + directory.mkdir(parents=True) + input_directory = root / f"artifacts/upstream/{directory_name}" + input_directory.mkdir(parents=True) + if key == "nyc_informed": + input_specs = ( + ("anchor", "anchor.json", "semi_synthetic_descriptive_anchor"), + ( + "anchor_manifest", + "anchor_manifest.json", + "semi_synthetic_descriptive_anchor", + ), + ) + else: + input_specs = ( + ("calibration_manifest", "manifest.json", "descriptive_real_data"), + ("exposure_mapping", "exposure_mapping_edges.csv", "descriptive_real_data"), + ) + input_entries = [] + for role, filename, input_evidence in input_specs: + input_path = input_directory / filename + input_path.write_text(f"{role}\n", encoding="utf-8") + input_entries.append( + _hashed_entry( + input_path, + str(input_path.relative_to(root)), + role=role, + evidence_types=[input_evidence], + ) + ) + table_paths: dict[str, Path] = {} + for role in ("records", "summary", "fit_ledger", "failures"): + table_evidence = ( + "semi_synthetic_nyc_graph_known_truth_monte_carlo" + if key == "nyc_graph" and role == "summary" + else evidence + ) + table = pd.DataFrame({"evidence_type": [table_evidence], "value": [1.0]}) + table_paths[role] = directory / f"{role}.csv" + table.to_csv(table_paths[role], index=False) + metadata: dict[str, object] = { + "evidence_type": evidence, + "causal_claim_from_nyc_data": False, + "artifact_bundle": { + "schema_version": "1.0.0", + "artifact_type": artifact_type, + "evidence_type": evidence, + "inputs": input_entries, + }, + } + if key == "nyc_informed": + metadata.update( + {"nyc_empirical_causal_effect": False, "simulator_known_truth": True} + ) + else: + metadata["input_graph_evidence_label"] = "descriptive_real_data" + metadata_path = _write_json(directory / "metadata.json", metadata) + entries = [] + for role, path in table_paths.items(): + entry_evidence = ( + "semi_synthetic_nyc_graph_known_truth_monte_carlo" + if key == "nyc_graph" and role == "summary" + else evidence + ) + entries.append( + _hashed_entry( + path, + path.name, + role=role, + evidence_types=[entry_evidence], + rows=1, + ) + ) + entries.append( + _hashed_entry( + metadata_path, + metadata_path.name, + role="metadata", + evidence_types=[evidence], + ) + ) + manifest: dict[str, object] = { + "schema_version": "1.0.0", + "artifact_type": artifact_type, + "evidence_type": evidence, + "causal_claim": False, + "causal_claim_from_nyc_data": False, + "portable_paths": True, + "metadata_file": "metadata.json", + "files": entries, + "inputs": input_entries, + } + if key == "nyc_informed": + manifest["simulator_known_truth"] = True + else: + manifest["input_graph_evidence_label"] = "descriptive_real_data" + manifests[key] = _write_json(directory / "manifest.json", manifest) + + equilibrium_dir = root / "artifacts/benchmarks/equilibrium" + equilibrium_dir.mkdir(parents=True) + equilibrium_summary = _write_json( + equilibrium_dir / "summary.json", + { + "schema_version": 1, + "evidence_type": "theoretical_simulation_known_ground_truth", + "common_random_numbers": True, + "is_nyc_structural_estimate": False, + "equations": { + "rider_demand": "declared", + "driver_supply": "declared", + "wait_fixed_point": "declared", + }, + }, + ) + equilibrium_zone = equilibrium_dir / "zone_effects.csv" + equilibrium_ledger = equilibrium_dir / "ledger.csv" + pd.DataFrame( + {"zone_id": [0], "evidence_type": ["theoretical_simulation_known_ground_truth"]} + ).to_csv(equilibrium_zone, index=False) + pd.DataFrame({"scenario": ["control"], "total_welfare": [1.0]}).to_csv( + equilibrium_ledger, index=False + ) + equilibrium_files = [equilibrium_summary, equilibrium_zone, equilibrium_ledger] + equilibrium_entries = [ + _hashed_entry(path, str(path.relative_to(root))) for path in equilibrium_files + ] + equilibrium_checks = { + "control_equilibrium_converged": True, + "treatment_equilibrium_converged": True, + "residuals_within_tolerance": True, + "sufficient_uniqueness_condition_satisfied": True, + "common_random_numbers_verified": True, + "budget_feasible": True, + "welfare_accounting_balanced": True, + "ground_truth_recomputed": True, + "hashes_recomputed": True, + } + manifests["equilibrium"] = _write_json( + equilibrium_dir / "manifest.json", + { + "schema_version": 1, + "bundle_type": "two_sided_fixed_point_equilibrium_benchmark", + "evidence_type": "theoretical_simulation_known_ground_truth", + "causal_scope": "within_declared_equilibrium_model_only", + "empirical_calibration_status": "not_an_empirical_or_nyc_structural_estimate", + "is_nyc_structural_estimate": False, + "portable_paths": True, + "files": equilibrium_entries, + "declared_file_set_sha256": hashlib.sha256( + json.dumps( + equilibrium_entries, sort_keys=True, separators=(",", ":") + ).encode() + ).hexdigest(), + "checks": equilibrium_checks, + }, + ) + + weather_dir = root / "artifacts/nyc_full/weather" + weather_dir.mkdir(parents=True) + weather_summary = _write_json( + weather_dir / "weather_associations.json", + { + "schema_version": "1.0.0", + "evidence_label": "descriptive_observed_external_weather", + "causal_claim": False, + "scope": { + "city": "New York City", + "pickup_month": "2024-01", + "population_claim": False, + }, + }, + ) + weather_daily = weather_dir / "weather_daily.csv" + weather_hourly = weather_dir / "weather_hourly_contrasts.csv" + pd.DataFrame({"date": ["2024-01-01"]}).to_csv(weather_daily, index=False) + pd.DataFrame({"hour": [0]}).to_csv(weather_hourly, index=False) + weather_files = [weather_summary, weather_daily, weather_hourly] + weather_entries = [ + _hashed_entry(path, str(path.relative_to(root))) for path in weather_files + ] + manifests["weather"] = _write_json( + weather_dir / "manifest.json", + { + "schema_version": "1.0.0", + "evidence_label": "descriptive_observed_external_weather", + "causal_claim": False, + "portable_paths": True, + "files": weather_entries, + "declared_file_set_sha256": hashlib.sha256( + json.dumps( + weather_entries, sort_keys=True, separators=(",", ":") + ).encode() + ).hexdigest(), + "checks": { + "noaa_raw_hash_matches": True, + "calendar_complete": True, + "nyc_source_manifest_valid": True, + "trip_conservation": True, + }, + }, + ) + + panel_path = root / "data/nyc_full/panel/zone_time/part.parquet" + panel_path.parent.mkdir(parents=True) + panel_path.write_bytes(b"verified-panel") + source_manifest = _write_json( + root / "data/nyc_full/manifest.json", + { + "config": {"source": "nyc_hvfhv", "mode": "full"}, + "metadata": { + "evidence_label": "descriptive_real_data", + "causal_claim": False, + "full_month_processing": { + "row_conservation": {"zone_time_trip_sum": 1_000} + }, + }, + "files": [ + _hashed_entry(panel_path, str(panel_path.relative_to(root))) + ], + }, + ) + + events_dir = root / "artifacts/nyc_full/events" + events_dir.mkdir(parents=True) + event_evidence = "descriptive_observed_external_calendar_events" + event_summary = _write_json( + events_dir / "event_associations.json", + { + "schema_version": "1.0.0", + "evidence_label": event_evidence, + "causal_claim": False, + "scope": { + "city": "New York City", + "event_signal_spatial_granularity": "citywide", + "event_signal_temporal_granularity": "service_date", + "population_claim": False, + }, + "coverage": { + "source_permit_rows": 10, + "source_unique_event_ids": 8, + "invalid_interval_rows_retained_but_not_expanded": 1, + "zero_duration_interval_rows_retained_but_not_expanded": 2, + "all_nonpositive_interval_rows_retained_but_not_expanded": 3, + "valid_interval_rows": 7, + "valid_unique_event_ids": 7, + "expanded_unique_event_days": 8, + "weekend_days": 2, + "above_median_permit_intensity_weekend_days": 2, + "at_or_below_median_permit_intensity_weekend_days": 0, + }, + "associations": { + "above_vs_at_or_below_median_permit_intensity_weekdays_only": { + "exposed_days": 2, + "comparison_days": 3, + } + }, + "identification_checks": { + "causal_effect_identified": False, + "major_event_contrast_separately_identifies_event_effect": False, + "all_weekend_days_are_above_median_permit_intensity": True, + }, + "conservation": { + "passes": True, + "daily_trip_sum": 1_000, + "zone_time_trip_sum": 1_000, + }, + }, + ) + event_files: list[dict[str, object]] = [] + for role, filename in ( + ("normalized_daily_calendar", "calendar.csv"), + ("normalized_permit_records", "events.csv"), + ("daily_permit_type_counts", "event_types.csv"), + ("joined_daily_trip_panel", "daily.csv"), + ("descriptive_hourly_profiles", "hourly.csv"), + ): + path = events_dir / filename + pd.DataFrame( + {"evidence_label": [event_evidence], "causal_claim": [False]} + ).to_csv(path, index=False) + event_files.append( + _hashed_entry(path, str(path.relative_to(root)), role=role) + ) + event_files.append( + _hashed_entry( + event_summary, + str(event_summary.relative_to(root)), + role="descriptive_summary", + ) + ) + event_inputs: list[dict[str, object]] = [] + for role, path in ( + ( + "official_holiday_snapshot", + root / "data/nyc_events/raw/holidays.csv", + ), + ( + "official_nyc_permitted_events_snapshot", + root / "data/nyc_events/raw/events.csv", + ), + ("nyc_full_data_manifest", source_manifest), + ("nyc_full_zone_time_panel", panel_path), + ): + if not path.exists(): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(f"{role}\n", encoding="utf-8") + event_inputs.append( + _hashed_entry(path, str(path.relative_to(root)), role=role) + ) + event_checks = { + "holiday_snapshot_hash_matches": True, + "event_snapshot_hash_matches": True, + "calendar_complete": True, + "holiday_schedule_coverage_complete": True, + "event_source_rows_verified": True, + "event_source_unique_ids_verified": True, + "invalid_source_intervals_retained_and_excluded": True, + "zero_duration_source_intervals_retained_and_excluded": True, + "daily_signal_is_citywide_not_zone_exposure": True, + "hourly_profiles_repeat_daily_signal_not_event_hour_exposure": True, + "major_event_is_researcher_defined": True, + "major_event_contrast_separately_identified": False, + "nyc_source_manifest_valid": True, + "trip_conservation": True, + "causal_claim_is_false": True, + "panel_files_verified": 1, + } + manifests["events"] = _write_json( + events_dir / "manifest.json", + { + "schema_version": "1.0.0", + "evidence_label": event_evidence, + "causal_claim": False, + "portable_paths": True, + "files": event_files, + "inputs": event_inputs, + "declared_file_set_sha256": hashlib.sha256( + json.dumps(event_files, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest(), + "declared_input_set_sha256": hashlib.sha256( + json.dumps(event_inputs, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest(), + "checks": event_checks, + }, + ) + + income_dir = root / "artifacts/nyc_full/income" + income_dir.mkdir(parents=True) + income_evidence = "descriptive_observed_external_neighborhood_income" + income_summary = _write_json( + income_dir / "income_associations.json", + { + "schema_version": "1.0.0", + "evidence_label": income_evidence, + "causal_claim": False, + "scope": { + "city": "New York City", + "population_claim": False, + "individual_income_claim": False, + }, + "coverage": { + "published_completed_trips": 1_000, + "classified_published_completed_trips": 990, + "unclassified_published_completed_trips": 10, + "classified_trip_coverage": 0.99, + "classified_panel_zones": 2, + "panel_zone_rows": 3, + }, + "associations": { + "mean_published_completed_trips_per_zone_hour_high_income_area": 11.0, + "mean_published_completed_trips_per_zone_hour_low_income_area": 10.0, + "high_minus_low_mean_published_completed_trips_per_zone_hour": 1.0, + "high_to_low_mean_published_completed_trips_per_zone_hour_ratio": 1.1, + }, + "conservation": { + "passes": True, + "zone_trip_sum": 1_000, + "daily_group_trip_sum": 1_000, + "monthly_group_trip_sum": 1_000, + "primary_classified_plus_unclassified_trip_sum": 1_000, + "primary_nonresidential_classified_zones": 0, + "sensitivity_group_trip_sum": 1_000, + }, + "spatial_mapping": {"equal_area_crs": "EPSG:6933"}, + "acs_aggregation": {"median_of_medians_used": False}, + "zone_allocation": { + "all_sixteen_bins_conserved": True, + "households_conserved": True, + "minimum_allocated_households": 1.0, + "minimum_residential_taxi_zone_area_share": 0.5, + "residential_nta_type_codes": ["0"], + "classified_zone_rows": 2, + "high_income_zone_rows": 1, + "low_income_zone_rows": 1, + }, + "primary_classification": { + "primary_result": True, + "minimum_allocated_households": 1.0, + "minimum_residential_taxi_zone_area_share": 0.5, + "residential_nta_type_codes": ["0"], + "groups": { + "high_income_area": { + "panel_zones": 1, + "published_completed_trips": 550, + "mean_published_completed_trips_per_zone_hour": 11.0, + }, + "low_income_area": { + "panel_zones": 1, + "published_completed_trips": 440, + "mean_published_completed_trips_per_zone_hour": 10.0, + }, + "unclassified": { + "panel_zones": 1, + "published_completed_trips": 10, + "mean_published_completed_trips_per_zone_hour": 1.0, + }, + }, + }, + "classification_uncertainty": { + "nta_b19001_margins_of_error_retained": True, + "zone_grouped_medians_are_point_estimates": True, + "zone_level_margin_of_error_propagated": False, + "interpretation": "Threshold proximity is not a confidence interval", + "threshold_proximity": { + "within_1000_usd": { + "primary_eligible_panel_zones": 0, + "published_completed_trips": 0, + "share_of_primary_classified_trips": 0.0, + }, + "within_2500_usd": { + "primary_eligible_panel_zones": 1, + "published_completed_trips": 100, + "share_of_primary_classified_trips": 100 / 990, + }, + "within_5000_usd": { + "primary_eligible_panel_zones": 1, + "published_completed_trips": 100, + "share_of_primary_classified_trips": 100 / 990, + }, + "within_10000_usd": { + "primary_eligible_panel_zones": 2, + "published_completed_trips": 990, + "share_of_primary_classified_trips": 1.0, + }, + }, + }, + "sensitivity": { + "all_zone_area_allocation": { + "primary_result": False, + "ignored_primary_residential_taxi_zone_area_share_threshold": 0.5, + "classified_panel_zones": 2, + "classified_published_completed_trips": 990, + "classified_trip_coverage": 0.99, + "mean_published_completed_trips_per_zone_hour_high_income_area": 11.0, + "mean_published_completed_trips_per_zone_hour_low_income_area": 10.0, + "high_minus_low_mean_published_completed_trips_per_zone_hour": 1.0, + "high_to_low_mean_published_completed_trips_per_zone_hour_ratio": 1.1, + "groups": { + "high_income_area": { + "panel_zones": 1, + "published_completed_trips": 550, + "mean_published_completed_trips_per_zone_hour": 11.0, + }, + "low_income_area": { + "panel_zones": 1, + "published_completed_trips": 440, + "mean_published_completed_trips_per_zone_hour": 10.0, + }, + "unclassified": { + "panel_zones": 1, + "published_completed_trips": 10, + "mean_published_completed_trips_per_zone_hour": 1.0, + }, + }, + } + }, + }, + ) + income_files: list[dict[str, object]] = [] + for role, filename in ( + ("taxi_zone_nta_crosswalk", "crosswalk.csv"), + ("nta_b19001_distribution_summary", "nta.csv"), + ("taxi_zone_income_and_trip_summary", "zones.csv"), + ("daily_income_group_description", "daily.csv"), + ("monthly_income_group_description", "monthly.csv"), + ): + path = income_dir / filename + pd.DataFrame( + {"evidence_label": [income_evidence], "causal_claim": [False]} + ).to_csv(path, index=False) + income_files.append( + _hashed_entry( + path, + str(path.relative_to(root)), + role=role, + evidence_label=income_evidence, + causal_claim=False, + ) + ) + income_files.append( + _hashed_entry( + income_summary, + str(income_summary.relative_to(root)), + role="income_association_summary", + evidence_label=income_evidence, + causal_claim=False, + ) + ) + income_input_specs = ( + ( + "official_tlc_taxi_zone_geometry", + "official_observed_geometry", + root / "data/nyc_income/raw/taxi.zip", + ), + ( + "official_nyc_nta2020_geometry", + "official_observed_geometry", + root / "data/nyc_income/raw/nta.geojson", + ), + ( + "official_nyc_tract2020_to_nta2020_mapping", + "official_observed_crosswalk", + root / "data/nyc_income/raw/tract.csv", + ), + ( + "official_census_acs_2022_5yr_b19001_nyc_tract_slice", + "official_observed_estimates", + root / "data/nyc_income/raw/acs.dat", + ), + ( + "verified_nyc_full_data_manifest", + "descriptive_real_data_lineage", + source_manifest, + ), + ( + "nyc_full_zone_time_panel", + "descriptive_real_data_panel", + panel_path, + ), + ) + income_inputs: list[dict[str, object]] = [] + for role, source_type, path in income_input_specs: + if not path.exists(): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(f"{role}\n", encoding="utf-8") + income_inputs.append( + _hashed_entry( + path, + str(path.relative_to(root)), + role=role, + source_type=source_type, + ) + ) + manifests["income"] = _write_json( + income_dir / "manifest.json", + { + "schema_version": "1.0.0", + "artifact_type": "nyc_income_descriptive_bundle", + "evidence_label": income_evidence, + "causal_claim": False, + "portable_paths": True, + "files": income_files, + "inputs": income_inputs, + "declared_file_set_sha256": hashlib.sha256( + json.dumps(income_files, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest(), + "declared_input_set_sha256": hashlib.sha256( + json.dumps(income_inputs, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest(), + "checks": { + "official_source_hashes_match": True, + "taxi_location_ids_unique_and_complete": True, + "tract_b19001_totals_equal_sixteen_bins": True, + "household_distribution_conserved": True, + "published_trip_conservation": True, + "ecological_noncausal_contract": True, + "dominant_nonresidential_primary_unclassified": True, + "all_zone_classification_is_sensitivity_only": True, + "median_of_medians_used": False, + "equal_area_crs": "EPSG:6933", + "dominant_nonresidential_primary_classified_zones": 0, + "minimum_allocated_households": 1.0, + "minimum_residential_taxi_zone_area_share": 0.5, + "residential_nta_type_codes": ["0"], + "zone_grouped_medians_are_point_estimates": True, + "zone_level_margin_of_error_propagated": False, + "panel_files_verified": 1, + }, + }, + ) + + reproduce = { + "files": [ + _hashed_entry(path, str(path.relative_to(root))) + for path in manifests.values() + ], + "metadata": {"source_tree_sha256": _source_tree_sha256(root)}, + } + manifests["top"] = _write_json( + root / "artifacts/reproduce_manifest.json", reproduce + ) + manifests["source"] = source + return manifests + + +def _refresh_top_manifest_entry(root: Path, path: Path) -> None: + top = root / "artifacts/reproduce_manifest.json" + payload = json.loads(top.read_text(encoding="utf-8")) + rendered = str(path.relative_to(root)) + for entry in payload["files"]: + if entry["path"] == rendered: + entry.update(_hashed_entry(path, rendered)) + break + _write_json(top, payload) + + +def _rewrite_child_json_role( + root: Path, + manifest_path: Path, + role: str, + payload: dict[str, object], +) -> None: + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + entry = next(item for item in manifest["files"] if item["role"] == role) + child_path = root / entry["path"] + _write_json(child_path, payload) + entry.update( + _hashed_entry( + child_path, + str(child_path.relative_to(root)), + role=role, + **{ + key: entry[key] + for key in ("evidence_label", "causal_claim") + if key in entry + }, + ) + ) + manifest["declared_file_set_sha256"] = hashlib.sha256( + json.dumps(manifest["files"], sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + _write_json(manifest_path, manifest) + _refresh_top_manifest_entry(root, manifest_path) + + +def test_defaults_match_a_precomputed_sensitivity_cell() -> None: + controls = DashboardControls() + assert controls.n_clusters == 8 + assert controls.spillover_strength == 0.0 + assert controls.persistence == 0.0 + assert controls.washout_periods == 0 + assert controls.budget == 10_000.0 + assert controls.replications == 5 + + +def test_controls_map_to_typed_config_and_washout_only_switches() -> None: + controls = _small_controls( + spillover_strength=0.35, + persistence=0.4, + incentive_size=3.25, + treatment_saturation=0.7, + treatment_version="driver_incentive", + ) + static = build_simulation_config(controls, design=DesignName.GEO_CLUSTER, seed=99) + switching = build_simulation_config(controls, design=DesignName.SWITCHBACK, seed=99) + + assert static.n_periods == 12 + assert static.n_zones == 8 + assert static.design.n_clusters == 4 + assert static.spillover_strength == 0.35 + assert static.persistence == 0.4 + assert static.incentive_per_driver == 3.25 + assert static.effective_budget == 800.0 + assert static.design.treatment_saturation == 0.7 + assert static.treatment_version is TreatmentVersion.DRIVER_INCENTIVE + assert static.design.washout_periods == 0 + assert switching.design.washout_periods == 1 + assert switching.seed == 99 + assert switching.design.seed == 100 + + +def test_on_demand_scenario_keeps_structural_truth_separate_from_assignment_diagnostic() -> None: + controls = _small_controls() + first = run_scenario_benchmark(controls) + second = run_scenario_benchmark(controls) + + pd.testing.assert_frame_equal(first.records, second.records) + pd.testing.assert_frame_equal(first.summary, second.summary) + row = first.selected + assert row["target_alignment"] == "target_mismatch_assignment_diagnostic" + assert "bias" not in first.summary.columns + assert "power" not in first.summary.columns + assert np.isclose( + row["budget_efficiency"], + row["expected_incremental_outcome"] / row["mean_full_policy_spend"], + ) + assert np.isclose( + row["modeled_welfare_per_dollar"], + row["modeled_incremental_welfare"] / row["mean_full_policy_spend"], + ) + assert set(first.records["evidence_type"]) == {"semi_synthetic_structural_known_truth"} + assert set(first.records["treatment_version"]) == {"bundled"} + assert (first.records["full_policy_spend"] <= controls.budget + 1e-7).all() + + +def test_artifact_recommendation_excludes_incompatible_low_rmse_row(tmp_path: Path) -> None: + controls = _small_controls() + frame = pd.DataFrame( + { + "design": ["individual", "switchback", "geo_cluster", "time_block"], + "estimator": ["regression_adjustment", "cluster_robust"] * 2, + "target_estimand": ["market_total_effect"] * 4, + "scenario": ["test"] * 4, + "declared_scenario_set": ['["test"]'] * 4, + "declared_scenario_count": [1] * 4, + "treatment_version": [controls.treatment_version] * 4, + "spillover_strength": [controls.spillover_strength] * 4, + "persistence": [controls.persistence] * 4, + "treatment_duration": [controls.treatment_duration] * 4, + "washout_periods": [0, controls.washout_periods, 0, controls.washout_periods], + "treatment_saturation": [controls.treatment_saturation] * 4, + "treatment_probability": [controls.treatment_probability] * 4, + "configured_geo_clusters": [np.nan, np.nan, controls.n_clusters, np.nan], + "n_zones": [max(4, controls.n_clusters * 2)] * 4, + "n_periods": [controls.experiment_duration] * 4, + "budget": [controls.budget] * 4, + "incentive_per_driver": [controls.incentive_size] * 4, + "bias": [0.01, 0.2, 0.01, 0.01], + "bias_mcse": [0.01] * 4, + "rmse": [0.01, 0.3, 0.01, 0.01], + "coverage": [0.95] * 4, + "coverage_mcse": [0.02] * 4, + "power": [0.99, 0.8, 0.99, 0.99], + "mean_std_error": [0.01, 0.2, 0.01, 0.01], + "identified": [True] * 4, + "inference_valid": [True, True, False, True], + "fit_complete": [True, True, True, False], + "applicable": [True] * 4, + "attempted_fits": [40] * 4, + "successful_fits": [40, 40, 40, 39], + "evidence_type": ["semi_synthetic_causal_monte_carlo"] * 4, + } + ) + path = tmp_path / "benchmark_results.csv" + frame.to_csv(path, index=False) + + artifact = load_benchmark_artifact(path) + assert artifact is not None + decision = artifact_decision(artifact, controls) + assert decision is not None + # The low-RMSE individual row is estimand-incompatible, geo inference is invalid, + # and time-block fitting is incomplete. None may outrank the valid switchback. + assert decision.recommendation["design"] == "switchback" + caveat = _recommended_design_caveat(decision) + assert "switchback" in caveat.lower() + assert "washout" in caveat + + artifact.summary["declared_scenario_set"] = '["stress","test"]' + artifact.summary["declared_scenario_count"] = 2 + assert artifact_decision(artifact, controls) is None + artifact.summary["declared_scenario_set"] = '["test"]' + artifact.summary["declared_scenario_count"] = 1 + + artifact.summary.loc[artifact.summary["design"] == "switchback", "power"] = np.nan + assert artifact_decision(artifact, controls) is None + + mismatched = artifact_decision( + artifact, + _small_controls(treatment_probability=0.7), + ) + assert mismatched is None + + +def test_actual_recovery_schema_fails_closed_for_unconstrained_budget(tmp_path: Path) -> None: + controls = _small_controls( + spillover_strength=0.0, + persistence=0.0, + washout_periods=0, + treatment_probability=0.5, + ) + frame = pd.DataFrame( + { + "scenario": ["no_interference"], + "declared_scenario_set": ['["no_interference"]'], + "declared_scenario_count": [1], + "treatment_version": [controls.treatment_version], + "design": ["switchback"], + "estimator": ["cluster_robust"], + "target_estimand": ["market_total_effect"], + "spillover_strength": [0.0], + "persistence": [0.0], + "treatment_duration": [controls.treatment_duration], + "washout_periods": [0], + "treatment_saturation": [1.0], + "treatment_probability": [0.5], + "configured_geo_clusters": [np.nan], + "n_periods": [controls.experiment_duration], + "budget_scope": ["unconstrained estimator-recovery simulation"], + "identified": [True], + "inference_valid": [True], + "fit_complete": [True], + "applicable": [True], + "attempted_fits": [40], + "successful_fits": [40], + "bias": [0.1], + "rmse": [0.2], + "coverage": [0.95], + "power": [0.8], + "evidence_type": ["semi_synthetic_causal_monte_carlo"], + } + ) + path = tmp_path / "benchmark_results.csv" + frame.to_csv(path, index=False) + artifact = load_benchmark_artifact(path) + assert artifact is not None + _, missing = match_benchmark_artifact(artifact, controls) + assert "budget" in missing + assert "incentive_size" in missing + assert artifact_decision(artifact, controls) is None + + +def test_mixed_budget_grid_matches_capped_or_certified_unconstrained_rows( + tmp_path: Path, +) -> None: + controls = _small_controls( + randomization_unit="time_block", + spillover_strength=0.0, + persistence=0.0, + washout_periods=0, + budget=800.0, + ) + declarations = '["baseline","shared_budget_low"]' + frame = pd.DataFrame( + { + "scenario": ["baseline", "shared_budget_low"], + "declared_scenario_set": [declarations] * 2, + "declared_scenario_count": [2] * 2, + "treatment_version": ["bundled"] * 2, + "design": ["time_block"] * 2, + "estimator": ["cluster_robust"] * 2, + "target_estimand": ["market_total_effect"] * 2, + "spillover_strength": [0.0] * 2, + "persistence": [0.0] * 2, + "treatment_duration": [controls.treatment_duration] * 2, + "washout_periods": [0] * 2, + "treatment_saturation": [1.0] * 2, + "treatment_probability": [0.5] * 2, + "configured_geo_clusters": [np.nan] * 2, + "n_zones": [8] * 2, + "n_periods": [12] * 2, + "incentive_per_driver": [1.5] * 2, + "budget": [np.nan, 100.0], + "budget_scope": [ + "unconstrained estimator-recovery simulation", + "shared treatment budget", + ], + "nonbinding_budget_threshold": [700.0] * 2, + "identified": [True, False], + "inference_valid": [True, True], + "fit_complete": [True, True], + "applicable": [True, True], + "attempted_fits": [40, 40], + "successful_fits": [40, 40], + "bias": [0.1, np.nan], + "rmse": [0.2, np.nan], + "coverage": [0.95, np.nan], + "power": [0.8, np.nan], + "evidence_type": ["semi_synthetic_causal_monte_carlo"] * 2, + } + ) + path = tmp_path / "benchmark_results.csv" + frame.to_csv(path, index=False) + artifact = load_benchmark_artifact(path) + assert artifact is not None + + uncapped_rows, missing = match_benchmark_artifact(artifact, controls) + assert missing == () + assert uncapped_rows["scenario"].tolist() == ["baseline"] + # Conditional subset ranking is withheld without top-manifest lineage. + assert artifact_decision(artifact, controls) is None + conditional = artifact_decision(replace(artifact, lineage_validated=True), controls) + assert conditional is not None + assert conditional.recommendation_scope == "selected_scenario_conditional" + assert conditional.matched_scenarios == ("baseline",) + assert conditional.unmatched_scenarios == ("shared_budget_low",) + + capped_rows, capped_missing = match_benchmark_artifact( + artifact, + replace(controls, budget=100.0), + ) + assert capped_missing == () + assert capped_rows["scenario"].tolist() == ["shared_budget_low"] + no_match, no_match_missing = match_benchmark_artifact( + artifact, + replace(controls, budget=650.0), + ) + assert no_match.empty + assert no_match_missing == () + + +def test_generated_recovery_matches_only_above_nonbinding_spend_threshold( + tmp_path: Path, +) -> None: + simulation = SimulationConfig( + n_periods=32, + incentive_per_driver=2.25, + design=DesignConfig( + treatment_duration=4, + washout_periods=0, + treatment_probability=0.5, + treatment_saturation=1.0, + ), + ) + generated = run_marketplace_benchmark( + BenchmarkConfig( + replications=8, + seed=404, + designs=("time_block",), + estimators=("cluster_robust",), + ), + simulation, + scenarios=(SensitivityScenario("no_interference", 0.0, 0.0),), + ) + path = tmp_path / "benchmark_results.csv" + generated.summary.to_csv(path, index=False) + artifact = load_benchmark_artifact(path) + assert artifact is not None + threshold = float(generated.summary["nonbinding_budget_threshold"].iloc[0]) + controls = DashboardControls( + randomization_unit="time_block", + experiment_duration=32, + n_clusters=4, + spillover_strength=0.0, + persistence=0.0, + incentive_size=2.25, + budget=threshold + 1.0, + treatment_duration=4, + washout_periods=0, + treatment_saturation=1.0, + treatment_probability=0.5, + replications=2, + seed=71, + ) + decision = artifact_decision(artifact, controls) + assert decision is not None + assert decision.recommendation["design"] == "time_block" + assert artifact_decision(artifact, replace(controls, budget=threshold - 1.0)) is None + assert artifact_decision(artifact, replace(controls, incentive_size=2.50)) is None + assert ( + artifact_decision( + artifact, + replace(controls, treatment_version="rider_discount"), + ) + is None + ) + + +def test_artifact_rejects_empirical_association_as_causal_benchmark(tmp_path: Path) -> None: + path = tmp_path / "benchmark_results.csv" + pd.DataFrame( + { + "design": ["switchback"], + "scenario": ["test"], + "declared_scenario_set": ['["test"]'], + "declared_scenario_count": [1], + "estimator": ["cluster_robust"], + "target_estimand": ["market_total_effect"], + "bias": [0.0], + "rmse": [0.1], + "coverage": [0.95], + "power": [0.8], + "identified": [True], + "inference_valid": [True], + "fit_complete": [True], + "applicable": [True], + "attempted_fits": [10], + "successful_fits": [10], + "evidence_type": ["empirical_association"], + } + ).to_csv(path, index=False) + with pytest.raises(ValueError, match="semi-synthetic"): + load_benchmark_artifact(path) + + +def test_default_artifact_discovery_requires_complete_manifest_lineage( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + benchmark_dir = tmp_path / "artifacts" / "benchmarks" + benchmark_dir.mkdir(parents=True) + path = benchmark_dir / "benchmark_results.csv" + pd.DataFrame( + { + "design": ["switchback"], + "scenario": ["test"], + "declared_scenario_set": ['["test"]'], + "declared_scenario_count": [1], + "estimator": ["cluster_robust"], + "target_estimand": ["market_total_effect"], + "bias": [0.0], + "rmse": [0.1], + "coverage": [0.95], + "power": [0.8], + "identified": [True], + "inference_valid": [True], + "fit_complete": [True], + "applicable": [True], + "attempted_fits": [10], + "successful_fits": [10], + "evidence_type": ["semi_synthetic_causal_monte_carlo"], + } + ).to_csv(path, index=False) + monkeypatch.setattr("casuallab.dashboard._project_root", lambda: tmp_path) + + with pytest.raises(ValueError, match="reproduce_manifest"): + load_benchmark_artifact() + + source_dir = tmp_path / "src" + source_dir.mkdir() + source_input = source_dir / "example.py" + source_input.write_text("VALUE = 1\n", encoding="utf-8") + payload = { + "files": [ + { + "path": "artifacts/benchmarks/benchmark_results.csv", + "bytes": path.stat().st_size, + "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), + } + ], + "metadata": {"source_tree_sha256": _source_tree_sha256(tmp_path)}, + } + (tmp_path / "artifacts" / "reproduce_manifest.json").write_text( + json.dumps(payload), encoding="utf-8" + ) + assert load_benchmark_artifact() is not None + + (tmp_path / "artifacts" / "REPRODUCE_INCOMPLETE.json").write_text("{}", encoding="utf-8") + with pytest.raises(ValueError, match="marked incomplete"): + load_benchmark_artifact() + (tmp_path / "artifacts" / "REPRODUCE_INCOMPLETE.json").unlink() + + source_input.write_text("VALUE = 2\n", encoding="utf-8") + with pytest.raises(ValueError, match="source/config tree"): + load_benchmark_artifact() + source_input.write_text("VALUE = 1\n", encoding="utf-8") + assert load_benchmark_artifact() is not None + + path.write_text(path.read_text(encoding="utf-8") + "\n", encoding="utf-8") + with pytest.raises(ValueError, match="byte count"): + load_benchmark_artifact() + + +def test_evidence_layers_require_top_and_child_lineage_and_preserve_labels( + tmp_path: Path, +) -> None: + paths = _evidence_layer_fixture(tmp_path) + + statuses = load_evidence_layers(tmp_path) + + assert [status.key for status in statuses] == [ + "nyc_informed", + "nyc_graph", + "equilibrium", + "weather", + "events", + "income", + ] + assert all(status.available for status in statuses) + assert all( + status.manifest_sha256 == hashlib.sha256(path.read_bytes()).hexdigest() + for status, path in zip( + statuses, + ( + paths["nyc_informed"], + paths["nyc_graph"], + paths["equilibrium"], + paths["weather"], + paths["events"], + paths["income"], + ), + strict=True, + ) + ) + rows = evidence_layer_rows(statuses) + assert {row["Status"] for row in rows} == {"Available"} + assert [row["Classification"] for row in rows] == [ + "Semi-synthetic known truth", + "Semi-synthetic known truth", + "Theoretical equilibrium known truth", + "Descriptive observed data — non-causal", + "Descriptive observed data — non-causal", + "Descriptive ecological data — non-causal", + ] + assert "not NYC causal estimates" in rows[0]["Interpretation"] + assert "exposure geometry only" in rows[1]["Interpretation"] + assert "not an NYC structural estimate" in rows[2]["Interpretation"] + assert "descriptive associations only" in rows[3]["Interpretation"] + assert "not attendance" in rows[4]["Interpretation"] + assert "not rider or driver income" in rows[5]["Interpretation"] + + +def test_evidence_layer_is_unavailable_when_child_file_hash_is_stale( + tmp_path: Path, +) -> None: + paths = _evidence_layer_fixture(tmp_path) + summary = paths["nyc_informed"].parent / "summary.csv" + summary.write_text(summary.read_text(encoding="utf-8") + "tamper\n", encoding="utf-8") + + statuses = {status.key: status for status in load_evidence_layers(tmp_path)} + + assert statuses["nyc_informed"].available is False + assert "byte count mismatch" in statuses["nyc_informed"].detail + assert all( + statuses[key].available + for key in ("nyc_graph", "equilibrium", "weather", "events", "income") + ) + + +def test_evidence_layer_is_unavailable_when_upstream_input_is_tampered( + tmp_path: Path, +) -> None: + paths = _evidence_layer_fixture(tmp_path) + manifest = json.loads(paths["nyc_informed"].read_text(encoding="utf-8")) + anchor = tmp_path / manifest["inputs"][0]["path"] + anchor.write_text(anchor.read_text(encoding="utf-8") + "tamper\n", encoding="utf-8") + + statuses = {status.key: status for status in load_evidence_layers(tmp_path)} + + assert statuses["nyc_informed"].available is False + assert "input byte count mismatch" in statuses["nyc_informed"].detail + assert statuses["nyc_graph"].available is True + + +def test_new_enrichment_layers_fail_closed_for_tamper_partial_and_causal_label( + tmp_path: Path, +) -> None: + paths = _evidence_layer_fixture(tmp_path) + event_payload = json.loads(paths["events"].read_text(encoding="utf-8")) + holiday_entry = next( + entry + for entry in event_payload["inputs"] + if entry["role"] == "official_holiday_snapshot" + ) + holiday_path = tmp_path / holiday_entry["path"] + original_holiday = holiday_path.read_bytes() + holiday_path.write_bytes(original_holiday + b"tamper") + + statuses = {status.key: status for status in load_evidence_layers(tmp_path)} + assert statuses["events"].available is False + assert "input byte count mismatch" in statuses["events"].detail + assert statuses["income"].available is True + holiday_path.write_bytes(original_holiday) + + income_payload = json.loads(paths["income"].read_text(encoding="utf-8")) + income_payload["inputs"] = [ + entry + for entry in income_payload["inputs"] + if entry["role"] != "official_nyc_nta2020_geometry" + ] + income_payload["declared_input_set_sha256"] = hashlib.sha256( + json.dumps( + income_payload["inputs"], sort_keys=True, separators=(",", ":") + ).encode() + ).hexdigest() + _write_json(paths["income"], income_payload) + _refresh_top_manifest_entry(tmp_path, paths["income"]) + statuses = {status.key: status for status in load_evidence_layers(tmp_path)} + assert statuses["income"].available is False + assert "incomplete input-role set" in statuses["income"].detail + assert statuses["events"].available is True + + event_payload["causal_claim"] = True + _write_json(paths["events"], event_payload) + _refresh_top_manifest_entry(tmp_path, paths["events"]) + statuses = {status.key: status for status in load_evidence_layers(tmp_path)} + assert statuses["events"].available is False + assert "invalid descriptive evidence schema" in statuses["events"].detail + + +def test_income_layer_rejects_primary_gate_type_code_and_sensitivity_tamper( + tmp_path: Path, +) -> None: + paths = _evidence_layer_fixture(tmp_path) + manifest_path = paths["income"] + original_manifest = manifest_path.read_bytes() + + payload = json.loads(original_manifest) + payload["checks"]["dominant_nonresidential_primary_unclassified"] = False + _write_json(manifest_path, payload) + _refresh_top_manifest_entry(tmp_path, manifest_path) + status = {item.key: item for item in load_evidence_layers(tmp_path)}["income"] + assert status.available is False + assert "invalid ecological evidence schema" in status.detail + + manifest_path.write_bytes(original_manifest) + _refresh_top_manifest_entry(tmp_path, manifest_path) + payload = json.loads(original_manifest) + payload["checks"]["residential_nta_type_codes"] = ["9"] + _write_json(manifest_path, payload) + _refresh_top_manifest_entry(tmp_path, manifest_path) + status = {item.key: item for item in load_evidence_layers(tmp_path)}["income"] + assert status.available is False + assert "invalid ecological evidence schema" in status.detail + + manifest_path.write_bytes(original_manifest) + _refresh_top_manifest_entry(tmp_path, manifest_path) + manifest = json.loads(original_manifest) + summary_entry = next( + entry + for entry in manifest["files"] + if entry["role"] == "income_association_summary" + ) + summary = json.loads((tmp_path / summary_entry["path"]).read_text(encoding="utf-8")) + summary["sensitivity"]["all_zone_area_allocation"]["primary_result"] = True + _rewrite_child_json_role( + tmp_path, + manifest_path, + "income_association_summary", + summary, + ) + status = {item.key: item for item in load_evidence_layers(tmp_path)}["income"] + assert status.available is False + assert "inconsistent sensitivity arithmetic" in status.detail + + +def test_event_layer_rejects_zero_duration_gate_and_count_tamper( + tmp_path: Path, +) -> None: + paths = _evidence_layer_fixture(tmp_path) + manifest_path = paths["events"] + original_manifest = manifest_path.read_bytes() + payload = json.loads(original_manifest) + payload["checks"]["zero_duration_source_intervals_retained_and_excluded"] = False + _write_json(manifest_path, payload) + _refresh_top_manifest_entry(tmp_path, manifest_path) + status = {item.key: item for item in load_evidence_layers(tmp_path)}["events"] + assert status.available is False + assert "invalid descriptive evidence schema" in status.detail + + manifest_path.write_bytes(original_manifest) + _refresh_top_manifest_entry(tmp_path, manifest_path) + manifest = json.loads(original_manifest) + summary_entry = next( + entry for entry in manifest["files"] if entry["role"] == "descriptive_summary" + ) + summary = json.loads((tmp_path / summary_entry["path"]).read_text(encoding="utf-8")) + summary["coverage"][ + "zero_duration_interval_rows_retained_but_not_expanded" + ] += 1 + _rewrite_child_json_role( + tmp_path, + manifest_path, + "descriptive_summary", + summary, + ) + status = {item.key: item for item in load_evidence_layers(tmp_path)}["events"] + assert status.available is False + assert "inconsistent interval counts" in status.detail + + +@pytest.mark.parametrize("invalid_path", ["../anchor.json", "/tmp/anchor.json"]) +def test_evidence_layer_rejects_nonportable_upstream_input_paths( + tmp_path: Path, + invalid_path: str, +) -> None: + paths = _evidence_layer_fixture(tmp_path) + manifest_path = paths["nyc_informed"] + payload = json.loads(manifest_path.read_text(encoding="utf-8")) + payload["inputs"][0]["path"] = invalid_path + _write_json(manifest_path, payload) + _refresh_top_manifest_entry(tmp_path, manifest_path) + + status = {item.key: item for item in load_evidence_layers(tmp_path)}["nyc_informed"] + + assert status.available is False + assert "project-root relative and traversal-free" in status.detail + + +def test_evidence_layer_rejects_duplicate_upstream_inputs(tmp_path: Path) -> None: + paths = _evidence_layer_fixture(tmp_path) + manifest_path = paths["nyc_informed"] + payload = json.loads(manifest_path.read_text(encoding="utf-8")) + payload["inputs"][1]["path"] = payload["inputs"][0]["path"] + _write_json(manifest_path, payload) + _refresh_top_manifest_entry(tmp_path, manifest_path) + + status = {item.key: item for item in load_evidence_layers(tmp_path)}["nyc_informed"] + + assert status.available is False + assert "input paths" in status.detail + + +def test_evidence_layer_is_unavailable_when_scientific_schema_is_mislabeled( + tmp_path: Path, +) -> None: + paths = _evidence_layer_fixture(tmp_path) + equilibrium_manifest = paths["equilibrium"] + payload = json.loads(equilibrium_manifest.read_text(encoding="utf-8")) + payload["is_nyc_structural_estimate"] = True + _write_json(equilibrium_manifest, payload) + _refresh_top_manifest_entry(tmp_path, equilibrium_manifest) + + statuses = {status.key: status for status in load_evidence_layers(tmp_path)} + + assert statuses["equilibrium"].available is False + assert "invalid theoretical evidence schema" in statuses["equilibrium"].detail + assert statuses["nyc_informed"].available is True + + +def test_evidence_layers_fail_closed_for_stale_source_or_top_entry(tmp_path: Path) -> None: + paths = _evidence_layer_fixture(tmp_path) + paths["source"].write_text("VALUE = 2\n", encoding="utf-8") + + stale_source = load_evidence_layers(tmp_path) + assert all(not status.available for status in stale_source) + assert all("source/config tree" in status.detail for status in stale_source) + + paths["source"].write_text("VALUE = 1\n", encoding="utf-8") + paths["weather"].write_text( + paths["weather"].read_text(encoding="utf-8") + "\n", encoding="utf-8" + ) + stale_entry = {status.key: status for status in load_evidence_layers(tmp_path)} + assert stale_entry["weather"].available is False + assert "byte count" in stale_entry["weather"].detail + assert stale_entry["nyc_graph"].available is True + + +def test_absent_evidence_manifests_are_reported_unavailable(tmp_path: Path) -> None: + statuses = load_evidence_layers(tmp_path) + + assert len(statuses) == 6 + assert all(not status.available for status in statuses) + assert all(status.detail == "unavailable: manifest is absent" for status in statuses) + + +def test_loader_accepts_current_descriptive_calibration_label(tmp_path: Path) -> None: + path = tmp_path / "calibration.json" + path.write_text( + json.dumps( + { + "evidence_type": "illustrative_empirical_scale_anchor", + "simulation_config": SimulationConfig().to_dict(), + } + ), + encoding="utf-8", + ) + template = load_calibration_template(path) + assert template is not None + assert template.evidence_type == "illustrative_empirical_scale_anchor" + assert template.config == SimulationConfig() + assert len(template.sha256) == 64 + + +def test_streamlit_renders_six_read_only_evidence_layers() -> None: + streamlit_testing = pytest.importorskip("streamlit.testing.v1") + app_path = Path(__file__).parents[1] / "src" / "casuallab" / "dashboard.py" + app = streamlit_testing.AppTest.from_file(str(app_path), default_timeout=90).run() + + assert not app.exception + assert "Evidence layers" in [item.value for item in app.subheader] + evidence_tables = [ + item.value + for item in app.dataframe + if "Evidence layer" in item.value.columns + ] + assert len(evidence_tables) == 1 + evidence = evidence_tables[0] + assert len(evidence) == 6 + assert set(evidence["Status"]).issubset({"Available", "Unavailable"}) + assert evidence["Classification"].tolist() == [ + "Semi-synthetic known truth", + "Semi-synthetic known truth", + "Theoretical equilibrium known truth", + "Descriptive observed data — non-causal", + "Descriptive observed data — non-causal", + "Descriptive ecological data — non-causal", + ] + assert any("not an NYC structural estimate" in text for text in evidence["Interpretation"]) + assert any("descriptive associations only" in text for text in evidence["Interpretation"]) + assert any("not attendance" in text for text in evidence["Interpretation"]) + assert any("not rider or driver income" in text for text in evidence["Interpretation"]) + + +def test_streamlit_hides_cached_results_after_treatment_control_changes() -> None: + streamlit_testing = pytest.importorskip("streamlit.testing.v1") + app_path = Path(__file__).parents[1] / "src" / "casuallab" / "dashboard.py" + app = streamlit_testing.AppTest.from_file(str(app_path), default_timeout=90).run() + + app.button[0].click().run(timeout=90) + assert not app.exception + assert len(app.metric) > 0 + app.run(timeout=90) + assert len(app.metric) > 0 + app.selectbox[1].select("rider_discount").run(timeout=90) + + assert not app.exception + assert not app.metric + assert any("hidden until you rerun" in warning.value for warning in app.warning) diff --git a/CasualLab/tests/test_data.py b/CasualLab/tests/test_data.py new file mode 100644 index 0000000000000000000000000000000000000000..5bffe705f97ffab458121b9e5b31172322a71cb9 --- /dev/null +++ b/CasualLab/tests/test_data.py @@ -0,0 +1,624 @@ +from __future__ import annotations + +import json +from datetime import datetime +from pathlib import Path +from urllib.parse import parse_qs, urlparse + +import polars as pl +import pytest + +from casuallab.data import ( + CHICAGO_DATASET_ID, + CLEAN_TRIP_SCHEMA, + MISSING_ZONE_ID, + DataConfig, + build_od_flow_panel, + build_zone_time_panel, + chicago_sample_urls, + data_quality_diagnostics, + download_sample, + load_data_config, + materialize_nyc_hvfhv_sample, + normalize_trips, + nyc_hvfhv_urls, + read_partitioned_parquet, + run_data_pipeline, + sha256_file, + validate_clean_schema, + write_manifest, + write_partitioned_parquet, +) + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +CHICAGO_FIXTURE = PROJECT_ROOT / "data/fixtures/chicago_tnp_2022-01-01_300.csv" +CHICAGO_FIXTURE_SHA256 = "84177e5a72548cc4346df99f0a6b671adb50d7762e23abe041f01b2958b85ad7" + + +@pytest.fixture(scope="module") +def chicago_trips() -> pl.DataFrame: + return normalize_trips(CHICAGO_FIXTURE, "chicago_tnp") + + +def test_fixture_is_pinned_authentic_extract() -> None: + assert sha256_file(CHICAGO_FIXTURE) == CHICAGO_FIXTURE_SHA256 + raw = pl.read_csv(CHICAGO_FIXTURE) + assert raw.height == 300 + assert raw.get_column("trip_id").n_unique() == 300 + assert raw.get_column("trip_start_timestamp").n_unique() == 12 + assert raw.get_column("trip_start_timestamp").min().startswith("2022-01-01T00:00") + assert raw.get_column("trip_start_timestamp").max().startswith("2022-01-01T22:00") + + fixture_manifest = json.loads( + (PROJECT_ROOT / "data/fixtures/manifest.json").read_text(encoding="utf-8") + ) + selection = fixture_manifest["selection"] + assert selection["query_predicate"] == ( + "trip_start_timestamp = exact reported hourly timestamp" + ) + assert "%3D" in selection["query_url_template"] + assert "%3E" not in selection["query_url_template"] + + +def test_load_config_resolves_paths_from_project_root(tmp_path: Path) -> None: + config_path = tmp_path / "configs/data.yaml" + config_path.parent.mkdir() + config_path.write_text( + "\n".join( + [ + "project_root: ..", + "source: chicago", + "mode: sample", + "fixture_path: fixtures/trips.csv", + "raw_dir: generated/raw", + "sample_rows: 300", + "nyc_months: [1, 2]", + "partition_by: [source, service_year, service_month]", + ] + ), + encoding="utf-8", + ) + config = load_data_config(config_path) + assert config.source == "chicago_tnp" + assert config.project_root == tmp_path.resolve() + assert config.fixture_path == tmp_path / "fixtures/trips.csv" + assert config.raw_dir == tmp_path / "generated/raw" + assert config.nyc_months == (1, 2) + + +def test_unknown_config_key_fails_fast(tmp_path: Path) -> None: + config_path = tmp_path / "bad.yaml" + config_path.write_text("source: chicago\nsampel_rows: 10\n", encoding="utf-8") + with pytest.raises(ValueError, match="unknown data configuration keys"): + load_data_config(config_path) + + +def test_full_config_rejects_misleading_sample_row_bound(tmp_path: Path) -> None: + config_path = tmp_path / "full.yaml" + config_path.write_text( + "source: nyc_hvfhv\nmode: full\nsample_rows: 1000\n", + encoding="utf-8", + ) + with pytest.raises(ValueError, match="does not bound full mode"): + load_data_config(config_path) + + +def test_chicago_sample_urls_are_stratified_and_deterministic() -> None: + config = DataConfig(sample_rows=300) + urls = chicago_sample_urls(config) + assert len(urls) == 12 + limits = [] + timestamps = [] + for url in urls: + query = parse_qs(urlparse(url).query) + assert query["$order"] == ["trip_id"] + limits.append(int(query["$limit"][0])) + timestamps.append(query["$where"][0]) + assert limits == [25] * 12 + assert timestamps[0].endswith("'2022-01-01T00:00:00'") + assert timestamps[-1].endswith("'2022-01-01T22:00:00'") + + +def test_download_sample_is_offline_by_default(tmp_path: Path) -> None: + def network_must_not_run(*_args: object, **_kwargs: object) -> object: + raise AssertionError("offline sample unexpectedly attempted network access") + + config = DataConfig( + fixture_path=CHICAGO_FIXTURE, + raw_dir=tmp_path / "raw", + sample_rows=300, + ) + downloaded = download_sample(config, opener=network_must_not_run) # type: ignore[arg-type] + assert downloaded == tmp_path / "raw/chicago_tnp_sample.csv" + assert sha256_file(downloaded) == CHICAGO_FIXTURE_SHA256 + + +def test_chicago_normalization_preserves_measurement_flags( + chicago_trips: pl.DataFrame, +) -> None: + validate_clean_schema(chicago_trips) + assert chicago_trips.schema == CLEAN_TRIP_SCHEMA + assert chicago_trips.height == 300 + assert chicago_trips.get_column("source").unique().to_list() == ["chicago_tnp"] + assert chicago_trips.get_column("source_dataset_id").unique().to_list() == [ + CHICAGO_DATASET_ID + ] + assert chicago_trips.get_column("pickup_on_15_minute_grid").all() + assert chicago_trips.get_column("fare_on_declared_grid").all() + assert chicago_trips.get_column("reported_timestamp_rounding_minutes").unique().to_list() == [ + 15 + ] + assert chicago_trips.get_column("reported_fare_rounding_increment").unique().to_list() == [ + 2.5 + ] + assert chicago_trips.get_column("pickup_datetime_utc").null_count() == 0 + assert chicago_trips.get_column("pickup_zone_missing").sum() == 13 + + +def test_diagnostics_distinguish_missingness_from_exact_suppression( + chicago_trips: pl.DataFrame, +) -> None: + diagnostics = data_quality_diagnostics(chicago_trips) + assert diagnostics["row_count"] == 300 + assert diagnostics["suppression_or_nonreporting"]["pickup_census_tract_count"] == 131 + assert diagnostics["suppression_or_nonreporting"]["dropoff_census_tract_count"] == 135 + assert "may be privacy-suppressed or outside Chicago" in diagnostics[ + "suppression_or_nonreporting" + ]["interpretation"] + assert diagnostics["rounding"]["pickup_on_15_minute_grid_rate"] == 1.0 + assert diagnostics["rounding"]["fare_on_declared_grid_rate"] == 1.0 + assert diagnostics["validity"]["duplicate_trip_id_count"] == 0 + + +def test_zone_time_and_od_panels_preserve_trip_totals(chicago_trips: pl.DataFrame) -> None: + panel = build_zone_time_panel(chicago_trips, frequency="15m") + flows = build_od_flow_panel(chicago_trips, frequency="15m") + assert panel.get_column("trip_count").sum() == 300 + assert flows.get_column("trip_count").sum() == 300 + assert panel.get_column("time_bin").n_unique() == 12 + assert MISSING_ZONE_ID in panel.get_column("zone_id").to_list() + assert panel.get_column("evidence_label").unique().to_list() == [ + "descriptive_real_data" + ] + assert {"avg_fare", "avg_trip_miles", "shared_requested_share"}.issubset(panel.columns) + assert {"origin_zone_id", "destination_zone_id", "trip_count"}.issubset(flows.columns) + + +def test_complete_zone_time_grid_adds_explicit_zero_cells(chicago_trips: pl.DataFrame) -> None: + observed = build_zone_time_panel(chicago_trips, frequency="2h") + complete = build_zone_time_panel(chicago_trips, frequency="2h", complete_grid=True) + assert complete.height >= observed.height + assert complete.get_column("trip_count").sum() == observed.get_column("trip_count").sum() + synthetic = complete.filter(pl.col("trip_count") == 0) + assert synthetic.height > 0 + assert synthetic.get_column("distinct_dropoff_zones").eq(0).all() + assert synthetic.get_column("outbound_trip_count").eq(0).all() + assert synthetic.get_column("od_pair_observed_count").eq(0).all() + for column in ( + "service_date", + "year", + "month", + "day_of_week", + "hour", + "minute", + "is_weekend", + "panel_grain", + "evidence_label", + ): + assert synthetic.get_column(column).null_count() == 0 + + +def _nyc_raw_frame() -> pl.DataFrame: + return pl.DataFrame( + { + "hvfhs_license_num": ["HV0003", "HV0005"], + "dispatching_base_num": ["B0001", "B0002"], + "request_datetime": [datetime(2024, 1, 2, 12, 0), datetime(2024, 1, 2, 12, 1)], + "pickup_datetime": [datetime(2024, 1, 2, 12, 5), datetime(2024, 1, 2, 12, 10)], + "dropoff_datetime": [datetime(2024, 1, 2, 12, 15), datetime(2024, 1, 2, 12, 30)], + "PULocationID": [132, 10], + "DOLocationID": [10, 20], + "trip_miles": [5.0, 6.0], + "trip_time": [600, 1_200], + "base_passenger_fare": [20.0, 30.0], + "tips": [2.0, 3.0], + "tolls": [1.0, 0.0], + "bcf": [0.5, 0.5], + "sales_tax": [1.0, 2.0], + "congestion_surcharge": [2.75, 2.75], + "airport_fee": [2.5, 0.0], + "cbd_congestion_fee": [0.75, 0.0], + "driver_pay": [15.0, 20.0], + "shared_request_flag": ["Y", "N"], + "shared_match_flag": ["N", "N"], + } + ) + + +def _nyc_full_calendar_frame() -> pl.DataFrame: + """Small row-count fixture with complete January date-hour coverage.""" + + template = _nyc_raw_frame().row(0, named=True) + second_zone_template = _nyc_raw_frame().row(1, named=True) + rows: list[dict[str, object]] = [] + for day in range(1, 32): + for hour in range(24): + pickup = datetime(2024, 1, day, hour, 5) + row = dict(template) + row["request_datetime"] = pickup.replace(minute=0) + row["pickup_datetime"] = pickup + row["dropoff_datetime"] = pickup.replace(minute=15) + rows.append(row) + for pickup in (datetime(2024, 1, 1, 0, 25), datetime(2024, 1, 31, 23, 25)): + row = dict(second_zone_template) + row["request_datetime"] = pickup.replace(minute=20) + row["pickup_datetime"] = pickup + row["dropoff_datetime"] = pickup.replace(minute=35) + rows.append(row) + # Repeat every business field from the first record after many record batches. + # Only the global source row offset can keep these surrogate IDs distinct. + rows.append(dict(rows[0])) + return pl.DataFrame(rows) + + +def test_nyc_adapter_normalizes_current_and_optional_fields() -> None: + raw = _nyc_raw_frame() + trips = normalize_trips(raw, "nyc_hvfhv") + validate_clean_schema(trips) + assert trips.height == 2 + assert trips.get_column("record_id_is_surrogate").all() + assert trips.get_column("trip_id").to_list() == normalize_trips( + raw, "nyc_hvfhv" + ).get_column("trip_id").to_list() + assert trips.get_column("total_amount").to_list() == pytest.approx([30.5, 38.25]) + assert trips.get_column("airport_trip").to_list() == [True, False] + assert trips.get_column("pickup_datetime_utc")[0].hour == 17 + assert trips.get_column("reported_fare_rounding_increment").null_count() == 2 + assert trips.get_column("pickup_census_tract_missing_or_suppressed").null_count() == 2 + diagnostics = data_quality_diagnostics(trips) + suppression = diagnostics["suppression_or_nonreporting"] + assert suppression["pickup_indicator_status"] == "unavailable" + assert suppression["dropoff_indicator_status"] == "unavailable" + assert suppression["pickup_indicator_known_count"] == 0 + assert suppression["pickup_census_tract_rate"] is None + + +def test_nyc_url_adapter_supports_full_month_sequence() -> None: + config = DataConfig(source="nyc_hvfhv", mode="full", nyc_year=2024, nyc_months=(3, 1)) + assert nyc_hvfhv_urls(config) == ( + "https://d37ci6vzurychx.cloudfront.net/trip-data/fhvhv_tripdata_2024-01.parquet", + "https://d37ci6vzurychx.cloudfront.net/trip-data/fhvhv_tripdata_2024-03.parquet", + ) + + +def test_nyc_sample_adapter_materializes_only_bounded_rows(tmp_path: Path) -> None: + source = tmp_path / "source.parquet" + raw = pl.concat([_nyc_raw_frame(), _nyc_raw_frame()], how="vertical") + raw.write_parquet(source) + config = DataConfig( + source="nyc_hvfhv", + mode="sample", + raw_dir=tmp_path / "raw", + sample_rows=3, + nyc_sample_days=(2,), + nyc_sample_hours=(12,), + ) + sample = materialize_nyc_hvfhv_sample(config, source_url=str(source)) + assert sample.name.startswith("fhvhv_tripdata_2024-01_stratified_3_") + assert pl.read_parquet(sample).height == 3 + + +def test_nyc_sample_is_deterministically_balanced_across_day_hours( + tmp_path: Path, +) -> None: + rows: list[dict[str, object]] = [] + template = _nyc_raw_frame().row(0, named=True) + for day in (1, 8): + for hour in (0, 12): + for minute in range(5): + row = dict(template) + row["request_datetime"] = datetime(2024, 1, day, hour, minute) + row["pickup_datetime"] = datetime(2024, 1, day, hour, minute, 10) + row["dropoff_datetime"] = datetime(2024, 1, day, hour, minute, 40) + row["PULocationID"] = 10 + minute + rows.append(row) + source = tmp_path / "strata.parquet" + pl.DataFrame(rows).write_parquet(source) + config = DataConfig( + source="nyc_hvfhv", + mode="sample", + raw_dir=tmp_path / "raw", + sample_rows=8, + nyc_sample_days=(1, 8), + nyc_sample_hours=(0, 12), + ) + + first = materialize_nyc_hvfhv_sample(config, source_url=str(source)) + second = materialize_nyc_hvfhv_sample( + config, + destination=tmp_path / "second.parquet", + source_url=str(source), + ) + sample = pl.read_parquet(first).with_columns( + pl.col("pickup_datetime").dt.day().alias("day"), + pl.col("pickup_datetime").dt.hour().alias("hour"), + ) + counts = sample.group_by("day", "hour").len().sort("day", "hour") + assert sample.height == 8 + assert counts["len"].to_list() == [2, 2, 2, 2] + assert sha256_file(first) == sha256_file(second) + + +def test_nyc_sample_cache_fails_closed_when_content_is_stale(tmp_path: Path) -> None: + source = tmp_path / "source.parquet" + raw = pl.concat([_nyc_raw_frame(), _nyc_raw_frame()], how="vertical") + raw.write_parquet(source) + config = DataConfig( + source="nyc_hvfhv", + mode="sample", + raw_dir=tmp_path / "raw", + sample_rows=3, + nyc_sample_days=(2,), + nyc_sample_hours=(12,), + ) + cached = materialize_nyc_hvfhv_sample(config, source_url=str(source)) + pl.read_parquet(cached).head(2).write_parquet(cached) + + with pytest.raises(ValueError, match="has 2 rows, expected 3"): + download_sample(config) + + +def test_nyc_sample_configuration_fails_closed_on_ambiguous_scope() -> None: + with pytest.raises(ValueError, match="exactly one configured month"): + DataConfig( + source="nyc_hvfhv", + mode="sample", + nyc_months=(1, 2), + ) + with pytest.raises(ValueError, match="at least the number"): + DataConfig( + source="nyc_hvfhv", + mode="sample", + sample_rows=2, + nyc_sample_days=(1,), + nyc_sample_hours=(0, 1, 2), + ) + with pytest.raises(ValueError, match="only valid in NYC full mode"): + DataConfig(source="nyc_hvfhv", mode="sample", nyc_expected_rows=10) + + +def test_nyc_configs_use_isolated_output_roots() -> None: + sample = load_data_config(PROJECT_ROOT / "configs/nyc_sample.yaml") + full = load_data_config(PROJECT_ROOT / "configs/full.yaml") + chicago = load_data_config(PROJECT_ROOT / "configs/sample.yaml") + assert sample.raw_dir == PROJECT_ROOT / "data/nyc_sample/raw" + assert sample.nyc_sample_days == (1, 10, 19, 28) + assert sample.nyc_sample_hours == tuple(range(24)) + assert full.raw_dir == PROJECT_ROOT / "data/nyc_full/raw" + assert {sample.raw_dir, full.raw_dir}.isdisjoint({chicago.raw_dir}) + + +def test_nyc_full_pipeline_streams_batches_and_preserves_all_trip_totals( + tmp_path: Path, +) -> None: + raw_dir = tmp_path / "raw" + raw_dir.mkdir() + raw_path = raw_dir / "fhvhv_tripdata_2024-01.parquet" + raw = _nyc_full_calendar_frame() + raw.write_parquet(raw_path, row_group_size=80) + config = DataConfig( + source="nyc_hvfhv", + mode="full", + project_root=tmp_path, + raw_dir=raw_dir, + clean_dir=tmp_path / "clean", + panel_dir=tmp_path / "panel", + manifest_path=tmp_path / "manifest.json", + diagnostics_path=tmp_path / "diagnostics.json", + nyc_year=2024, + nyc_months=(1,), + nyc_batch_rows=100, + nyc_expected_rows=raw.height, + nyc_expected_bytes=raw_path.stat().st_size, + nyc_expected_sha256=sha256_file(raw_path), + panel_frequency="1h", + complete_panel_grid=True, + ) + + artifacts = run_data_pipeline(config) + clean = read_partitioned_parquet(tmp_path / "clean/trips") + panel = read_partitioned_parquet(tmp_path / "panel/zone_time") + od_flow = read_partitioned_parquet(tmp_path / "panel/od_flow") + diagnostics = json.loads(artifacts.diagnostics_path.read_text(encoding="utf-8")) + manifest = json.loads(artifacts.manifest_path.read_text(encoding="utf-8")) + processing = manifest["metadata"]["full_month_processing"] + + assert raw.height == 747 + assert artifacts.trip_rows == raw.height == clean.height + assert clean.get_column("trip_id").n_unique() == raw.height + assert len(artifacts.clean_files) == 8 + assert len({path.name for path in artifacts.clean_files}) == 8 + assert panel.get_column("trip_count").sum() == raw.height + assert od_flow.get_column("trip_count").sum() == raw.height + assert artifacts.panel_rows == 2 * 31 * 24 + assert processing["observed_zone_time_rows"] == 746 + assert processing["synthesized_zone_time_rows"] == 742 + assert processing["configured_date_hours"] == 31 * 24 + assert processing["observed_date_hours"] == 31 * 24 + assert processing["normalized_batches"] == 8 + assert processing["raw_row_groups"] == 10 + assert processing["row_conservation"]["passes"] is True + assert diagnostics["row_count"] == raw.height + assert diagnostics["validity"]["duplicate_trip_id_count"] == 0 + assert diagnostics["suppression_or_nonreporting"]["pickup_indicator_status"] == ( + "unavailable" + ) + assert manifest["config"]["sample_rows"] is None + assert manifest["config"]["nyc_sample_days"] is None + assert "sample_selection" not in manifest["source_metadata"]["known_measurement"] + assert not (tmp_path / "NYC_FULL_INCOMPLETE.json").exists() + + second_config = DataConfig( + source="nyc_hvfhv", + mode="full", + project_root=tmp_path, + raw_dir=raw_dir, + clean_dir=tmp_path / "second_clean", + panel_dir=tmp_path / "second_panel", + manifest_path=tmp_path / "second_manifest.json", + diagnostics_path=tmp_path / "second_diagnostics.json", + nyc_year=2024, + nyc_months=(1,), + nyc_batch_rows=137, + panel_frequency="1h", + complete_panel_grid=True, + ) + second = run_data_pipeline(second_config) + second_clean = read_partitioned_parquet(tmp_path / "second_clean/trips") + assert set(second_clean.get_column("trip_id")) == set(clean.get_column("trip_id")) + assert len(second.clean_files) == 6 + + +def test_nyc_full_pipeline_rejects_readable_but_partial_cached_month( + tmp_path: Path, +) -> None: + raw_dir = tmp_path / "raw" + raw_dir.mkdir() + raw_path = raw_dir / "fhvhv_tripdata_2024-01.parquet" + _nyc_raw_frame().head(1).write_parquet(raw_path) + config = DataConfig( + source="nyc_hvfhv", + mode="full", + project_root=tmp_path, + raw_dir=raw_dir, + clean_dir=tmp_path / "clean", + panel_dir=tmp_path / "panel", + manifest_path=tmp_path / "manifest.json", + diagnostics_path=tmp_path / "diagnostics.json", + nyc_year=2024, + nyc_months=(1,), + nyc_batch_rows=1, + panel_frequency="1h", + ) + + with pytest.raises(ValueError, match="configured calendar days"): + run_data_pipeline(config) + assert not config.manifest_path.exists() + assert not (config.clean_dir / "trips").exists() + assert (tmp_path / "NYC_FULL_INCOMPLETE.json").exists() + + +def test_nyc_full_exact_raw_mismatch_invalidates_old_manifest_and_keeps_marker( + tmp_path: Path, +) -> None: + raw_dir = tmp_path / "raw" + raw_dir.mkdir() + raw_path = raw_dir / "fhvhv_tripdata_2024-01.parquet" + _nyc_raw_frame().head(1).write_parquet(raw_path) + manifest_path = tmp_path / "manifest.json" + manifest_path.write_text('{"stale": true}\n', encoding="utf-8") + config = DataConfig( + source="nyc_hvfhv", + mode="full", + project_root=tmp_path, + raw_dir=raw_dir, + clean_dir=tmp_path / "clean", + panel_dir=tmp_path / "panel", + manifest_path=manifest_path, + diagnostics_path=tmp_path / "diagnostics.json", + nyc_year=2024, + nyc_months=(1,), + nyc_expected_rows=2, + nyc_batch_rows=1, + panel_frequency="1h", + ) + + with pytest.raises(ValueError, match="raw row-count mismatch"): + run_data_pipeline(config) + marker = tmp_path / "NYC_FULL_INCOMPLETE.json" + assert marker.is_file() + assert not manifest_path.exists() + assert json.loads(marker.read_text(encoding="utf-8"))["status"] == "incomplete" + + +def test_missing_required_raw_columns_fail_before_normalization() -> None: + with pytest.raises(ValueError, match="missing required columns"): + normalize_trips(pl.DataFrame({"trip_id": ["x"]}), "chicago_tnp") + + +def test_partitioned_parquet_and_manifest_have_reproducible_checksums( + tmp_path: Path, + chicago_trips: pl.DataFrame, +) -> None: + files = write_partitioned_parquet(chicago_trips, tmp_path / "clean") + assert len(files) == 1 + assert "source=chicago_tnp" in str(files[0]) + restored = read_partitioned_parquet(tmp_path / "clean") + assert restored.height == chicago_trips.height + manifest = write_manifest( + files, + tmp_path / "manifest.json", + metadata={"evidence_label": "descriptive_real_data", "causal_claim": False}, + root=tmp_path, + ) + payload = json.loads(manifest.read_text(encoding="utf-8")) + assert payload["files"][0]["sha256"] == sha256_file(files[0]) + assert payload["files"][0]["bytes"] == files[0].stat().st_size + assert payload["metadata"]["causal_claim"] is False + + +def test_offline_pipeline_writes_clean_panel_diagnostics_and_manifest(tmp_path: Path) -> None: + config = DataConfig( + project_root=tmp_path, + fixture_path=CHICAGO_FIXTURE, + raw_dir=tmp_path / "raw", + clean_dir=tmp_path / "clean", + panel_dir=tmp_path / "panel", + manifest_path=tmp_path / "manifest.json", + diagnostics_path=tmp_path / "diagnostics.json", + sample_rows=300, + ) + artifacts = run_data_pipeline(config) + assert artifacts.trip_rows == 300 + assert artifacts.panel_rows > 12 + assert artifacts.raw_files and artifacts.clean_files and artifacts.panel_files + assert artifacts.od_flow_files + assert artifacts.manifest_path.is_file() + diagnostics = json.loads(artifacts.diagnostics_path.read_text(encoding="utf-8")) + manifest = json.loads(artifacts.manifest_path.read_text(encoding="utf-8")) + assert diagnostics["row_count"] == 300 + assert manifest["metadata"]["evidence_label"] == "descriptive_real_data" + assert manifest["metadata"]["causal_claim"] is False + + +def test_unknown_origin_and_destination_are_not_called_intra_zone( + chicago_trips: pl.DataFrame, +) -> None: + unknown_pairs = chicago_trips.filter( + pl.col("pickup_zone_id").is_null() & pl.col("dropoff_zone_id").is_null() + ) + assert unknown_pairs.height > 0 + panel = build_zone_time_panel(unknown_pairs, frequency="1h") + assert panel["intra_zone_share"].null_count() == panel.height + assert panel["outbound_trip_count"].null_count() == panel.height + assert panel["distinct_dropoff_zones"].null_count() == panel.height + assert panel["od_pair_observed_count"].sum() == 0 + assert panel["od_pair_observed_share"].sum() == 0.0 + + complete = build_zone_time_panel(unknown_pairs, frequency="1h", complete_grid=True) + observed_unknown = complete.filter(pl.col("trip_count") > 0) + assert observed_unknown["intra_zone_share"].null_count() == observed_unknown.height + assert observed_unknown["outbound_trip_count"].null_count() == observed_unknown.height + assert observed_unknown["distinct_dropoff_zones"].null_count() == observed_unknown.height + + +def test_partition_writer_removes_stale_parquet_when_overwriting(tmp_path: Path) -> None: + first = pl.DataFrame({"source": ["a", "b"], "value": [1, 2]}) + second = pl.DataFrame({"source": ["a"], "value": [3]}) + root = tmp_path / "dataset" + write_partitioned_parquet(first, root, partition_by=("source",)) + assert len(list(root.rglob("*.parquet"))) == 2 + files = write_partitioned_parquet(second, root, partition_by=("source",)) + assert len(files) == 1 + assert len(list(root.rglob("*.parquet"))) == 1 + assert read_partitioned_parquet(root)["value"].to_list() == [3] diff --git a/CasualLab/tests/test_designs.py b/CasualLab/tests/test_designs.py new file mode 100644 index 0000000000000000000000000000000000000000..570bbcd6933699e935a7462407cebee997058e1c --- /dev/null +++ b/CasualLab/tests/test_designs.py @@ -0,0 +1,136 @@ +from __future__ import annotations + +import numpy as np +import pandas as pd +import pytest + +from casuallab.config import DesignConfig +from casuallab.designs import ASSIGNMENT_COLUMNS, enforce_budget, generate_assignment + + +@pytest.mark.parametrize( + "design", + ["individual", "geo_cluster", "time_block", "switchback", "geo_time"], +) +def test_all_designs_are_deterministic_and_share_a_schema(design: str) -> None: + config = DesignConfig( + name=design, + cluster_size=2, + treatment_duration=3, + washout_periods=1 if design in {"time_block", "switchback", "geo_time"} else 0, + ) + first = generate_assignment(6, 18, config, seed=41, individuals_per_cell=60) + second = generate_assignment(6, 18, config, seed=41, individuals_per_cell=60) + + pd.testing.assert_frame_equal(first, second) + assert set(ASSIGNMENT_COLUMNS).issubset(first.columns) + assert first[["zone_id", "period_id"]].duplicated().sum() == 0 + assert first["treatment"].between(0, 1).all() + assert first["assigned_treatment"].between(0, 1).all() + assert first["treatment_probability"].between(0, 1).all() + assert set(first["analysis_eligible"].unique()).issubset({0, 1}) + assert set(first["assignment_seed"]) == {41} + + +def test_individual_design_is_a_partial_saturation_assignment() -> None: + config = DesignConfig(name="individual", treatment_probability=0.4) + assignment = generate_assignment( + 4, + 20, + config, + seed=7, + individuals_per_cell=200, + ) + + assert assignment["assigned_treatment"].nunique() > 2 + assert np.isclose(assignment["treatment_probability"], 0.4).all() + assert assignment["treated_units"].between(0, 200).all() + assert np.isclose( + assignment["assigned_treatment"], assignment["treated_units"] / 200 + ).all() + + +def test_geographic_assignment_is_constant_within_zone() -> None: + config = DesignConfig( + name="geo_cluster", + treatment_probability=0.34, + n_clusters=3, + ) + assignment = generate_assignment(6, 8, config, seed=12) + + assert (assignment.groupby("zone_id")["assigned_treatment"].nunique() == 1).all() + assert assignment["cluster_id"].nunique() == 3 + # Complete randomization has one of three clusters treated, so the exact + # inclusion probability is 1/3 rather than the requested rounding target .34. + assert np.isclose(assignment["treatment_probability"], 1 / 3).all() + + +def test_geo_design_never_mistakes_contemporaneous_arms_for_washout() -> None: + assignment = generate_assignment( + 4, + 12, + DesignConfig(name="geo_cluster", washout_periods=1, treatment_duration=4), + seed=3, + ) + + assert assignment["analysis_eligible"].eq(1).all() + assert assignment["washout"].eq(0).all() + + +def test_time_blocks_and_switchback_pairs_obey_schedule() -> None: + block_config = DesignConfig(name="time_block", treatment_duration=2) + blocks = generate_assignment(4, 12, block_config, seed=4) + assert (blocks.groupby("period_id")["assigned_treatment"].nunique() == 1).all() + assert (blocks.groupby("time_block")["assigned_treatment"].nunique() == 1).all() + + switch_config = DesignConfig( + name="switchback", + treatment_probability=0.7, + treatment_duration=2, + washout_periods=1, + ) + switch = generate_assignment(3, 16, switch_config, seed=5) + block_arms = switch.groupby("time_block")["assigned_treatment"].first().sort_index() + for _, pair in block_arms.groupby(block_arms.index // 2): + if len(pair) == 2: + assert set(pair) == {0.0, 1.0} + even_probability = switch.loc[switch["time_block"] % 2 == 0, "treatment_probability"] + odd_probability = switch.loc[switch["time_block"] % 2 == 1, "treatment_probability"] + assert np.isclose(even_probability, 0.7).all() + assert np.isclose(odd_probability, 0.3).all() + assert switch["washout"].sum() > 0 + assert (switch["analysis_eligible"] == 1 - switch["washout"]).all() + + +def test_geo_time_is_constant_within_randomization_cell() -> None: + config = DesignConfig(name="geo_time", cluster_size=2, treatment_duration=3) + assignment = generate_assignment(6, 12, config, seed=8) + within_cell = assignment.groupby(["cluster_id", "time_block"])["assigned_treatment"] + assert (within_cell.nunique() == 1).all() + assert assignment["randomization_cluster"].nunique() == 3 * 4 + + +def test_expected_budget_attenuation_preserves_assignment() -> None: + assignment = generate_assignment( + 4, + 6, + DesignConfig(name="geo_cluster"), + seed=2, + ) + constrained = enforce_budget(assignment, cost_per_full_treatment=10.0, budget=30.0) + + pd.testing.assert_series_equal( + constrained["assigned_treatment"], assignment["assigned_treatment"] + ) + assert constrained["expected_treatment_cost"].sum() <= 30.0 + 1e-10 + assert constrained["budget_scale"].iat[0] < 1.0 + + +@pytest.mark.parametrize("design", ["individual", "geo_cluster", "time_block", "geo_time"]) +def test_single_randomization_group_reports_bernoulli_probability_not_realized_arm( + design: str, +) -> None: + config = DesignConfig(name=design, treatment_probability=0.37) + assignment = generate_assignment(1, 1, config, seed=4) + + assert np.isclose(assignment["treatment_probability"], 0.37).all() diff --git a/CasualLab/tests/test_enrichments.py b/CasualLab/tests/test_enrichments.py new file mode 100644 index 0000000000000000000000000000000000000000..7491682fd87398de7bc6d7ebe56e24f15e53a525 --- /dev/null +++ b/CasualLab/tests/test_enrichments.py @@ -0,0 +1,48 @@ +from pathlib import Path + +import pandas as pd +import pytest + +from casuallab.enrichments import EnrichmentAdapter, apply_optional_enrichments + + +def test_missing_optional_enrichment_leaves_core_panel_unchanged() -> None: + panel = pd.DataFrame({"zone_id": [1, 2], "trip_count": [3, 4]}) + result = apply_optional_enrichments( + panel, + [EnrichmentAdapter("neighborhood", None, ("zone_id",))], + ) + pd.testing.assert_frame_equal(result.panel, panel) + assert result.diagnostics.loc[0, "status"] == "unavailable_optional" + + +def test_available_enrichment_preserves_missing_coverage(tmp_path: Path) -> None: + panel = pd.DataFrame({"zone_id": [1, 2, 3], "trip_count": [3, 4, 5]}) + source_path = tmp_path / "income.csv" + pd.DataFrame({"area": [1, 2], "income_index": [0.1, 0.8]}).to_csv( + source_path, index=False + ) + result = apply_optional_enrichments( + panel, + [ + EnrichmentAdapter( + "neighborhood", + source_path, + ("zone_id",), + source_keys=("area",), + value_columns=("income_index",), + ) + ], + ) + assert result.panel["neighborhood__income_index"].isna().sum() == 1 + assert result.diagnostics.loc[0, "coverage_rate"] == pytest.approx(2 / 3) + + +def test_required_enrichment_fails_closed() -> None: + panel = pd.DataFrame({"zone_id": [1], "trip_count": [3]}) + with pytest.raises(FileNotFoundError): + apply_optional_enrichments( + panel, + [EnrichmentAdapter("events", None, ("zone_id",), required=True)], + ) + diff --git a/CasualLab/tests/test_equilibrium.py b/CasualLab/tests/test_equilibrium.py new file mode 100644 index 0000000000000000000000000000000000000000..57b9ca97b9206f72e93235361341de4a25d99aa7 --- /dev/null +++ b/CasualLab/tests/test_equilibrium.py @@ -0,0 +1,411 @@ +from __future__ import annotations + +import hashlib +import json +from dataclasses import replace +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +import casuallab.equilibrium as equilibrium_module +from casuallab.config import TreatmentVersion +from casuallab.equilibrium import ( + CAUSAL_SCOPE, + EMPIRICAL_STATUS, + EVIDENCE_TYPE, + EquilibriumConfig, + EquilibriumConvergenceError, + run_equilibrium_benchmark, + solve_market_equilibrium, + write_equilibrium_artifacts, +) + + +def _config(**overrides: object) -> EquilibriumConfig: + return replace( + EquilibriumConfig( + n_zones=2, + seed=4711, + demand_shock_sd=0.04, + supply_shock_sd=0.03, + tolerance=1e-11, + ), + **overrides, + ) + + +def test_same_seed_reproduces_equilibria_truth_and_ledgers() -> None: + first = run_equilibrium_benchmark(_config()) + second = run_equilibrium_benchmark(_config()) + + pd.testing.assert_frame_equal(first.control.panel, second.control.panel) + pd.testing.assert_frame_equal(first.treatment.panel, second.treatment.panel) + pd.testing.assert_frame_equal(first.zone_effects, second.zone_effects) + pd.testing.assert_frame_equal(first.ledger, second.ledger) + assert first.ground_truth == second.ground_truth + assert first.metadata == second.metadata + + changed = run_equilibrium_benchmark(_config(seed=4712)) + assert changed.metadata["state_id"] != first.metadata["state_id"] + assert not np.allclose( + changed.control.panel["baseline_rider_arrivals"], + first.control.panel["baseline_rider_arrivals"], + ) + + +@pytest.mark.parametrize("scenario", ["control", "treatment"]) +def test_reported_residual_recomputes_from_declared_fixed_point(scenario: str) -> None: + config = _config(cross_zone_share=0.35) + result = run_equilibrium_benchmark(config) + outcome = result.control if scenario == "control" else result.treatment + panel = outcome.panel.sort_values("zone_id") + + local_tightness = np.log( + panel["latent_demand"].to_numpy() + / (config.capacity_per_driver * panel["available_drivers"].to_numpy()) + ) + # With two zones the declared ring maps each zone to the other one. + neighbor_tightness = local_tightness[::-1] + target = config.congestion_elasticity * ( + (1.0 - config.cross_zone_share) * local_tightness + + config.cross_zone_share * neighbor_tightness + ) + recomputed = float( + np.max(np.abs(target - panel["log_wait_ratio"].to_numpy())) + ) + + assert outcome.diagnostics.converged + assert outcome.diagnostics.uniqueness_condition_satisfied + assert outcome.diagnostics.contraction_bound < 1.0 + assert recomputed == pytest.approx( + outcome.diagnostics.residual_sup_norm, abs=1e-14 + ) + assert recomputed <= config.tolerance + + +@pytest.mark.parametrize( + ("version", "rider_spend_positive", "driver_spend_positive"), + [ + (TreatmentVersion.RIDER_DISCOUNT, True, False), + (TreatmentVersion.DRIVER_INCENTIVE, False, True), + (TreatmentVersion.BUNDLED, True, True), + ], +) +def test_declared_intervention_version_activates_only_its_market_side( + version: TreatmentVersion, + rider_spend_positive: bool, + driver_spend_positive: bool, +) -> None: + result = run_equilibrium_benchmark(_config(treatment_version=version)) + control = result.control.panel + treated = result.treatment.panel + + assert (float(treated["rider_discount_spend"].sum()) > 0) is rider_spend_positive + assert (float(treated["driver_incentive_spend"].sum()) > 0) is driver_spend_positive + if rider_spend_positive: + assert (treated["rider_price"] < control["rider_price"]).all() + assert (treated["latent_demand"] > control["latent_demand"]).all() + else: + np.testing.assert_allclose(treated["rider_price"], control["rider_price"]) + assert np.allclose(treated["rider_treatment_dose"], 0.0) + if driver_spend_positive: + assert (treated["driver_incentive_per_driver"] > 0).all() + assert (treated["available_drivers"] > control["available_drivers"]).all() + else: + assert np.allclose(treated["driver_treatment_dose"], 0.0) + + # Both a lower rider price and a positive supply incentive weakly relax the + # matching constraint in this pre-specified model; each version raises trips. + assert result.ground_truth["market_total_trip_effect"] > 0 + + +def test_budget_binds_with_a_re_solved_equilibrium_and_balanced_welfare_ledger() -> None: + budget = 100.0 + result = run_equilibrium_benchmark(_config(budget=budget)) + treatment = result.treatment.panel + diagnostics = result.metadata["budget_diagnostics"] + + assert diagnostics["binding"] is True + assert diagnostics["budget_feasible"] is True + assert 0 < diagnostics["budget_scale"] < 1 + assert float(treatment["treatment_spend"].sum()) <= budget + 1e-8 + np.testing.assert_allclose( + treatment["treatment_spend"], + treatment["rider_discount_spend"] + + treatment["driver_incentive_spend"], + atol=1e-12, + ) + np.testing.assert_allclose( + treatment["total_welfare"], + treatment["rider_surplus"] + + treatment["driver_surplus"] + + treatment["platform_net_revenue"], + atol=1e-10, + ) + treatment_ledger = result.ledger.set_index("scenario").loc["treatment"] + assert treatment_ledger["treatment_spend"] == pytest.approx( + result.ground_truth["treatment_spend"] + ) + assert abs(float(treatment_ledger["welfare_accounting_residual"])) < 1e-10 + + +def test_solver_fails_closed_when_sufficient_uniqueness_condition_fails() -> None: + config = _config( + demand_wait_elasticity=0.80, + supply_wait_elasticity=0.50, + congestion_elasticity=0.90, + ) + + with pytest.raises(EquilibriumConvergenceError) as caught: + solve_market_equilibrium(config, 1.0) + + diagnostics = caught.value.diagnostics + assert not diagnostics.converged + assert not diagnostics.uniqueness_condition_satisfied + assert diagnostics.contraction_bound >= 1.0 + assert diagnostics.iterations == 0 + assert diagnostics.residual_sup_norm is None + assert diagnostics.termination_reason == "sufficient_contraction_condition_failed" + + +def test_solver_fails_closed_when_iteration_cap_precedes_residual_tolerance() -> None: + config = _config(max_iterations=1, tolerance=1e-15) + + with pytest.raises(EquilibriumConvergenceError) as caught: + solve_market_equilibrium(config, 1.0) + + diagnostics = caught.value.diagnostics + assert diagnostics.uniqueness_condition_satisfied + assert not diagnostics.converged + assert diagnostics.iterations == 1 + assert diagnostics.residual_sup_norm is not None + assert diagnostics.residual_sup_norm > config.tolerance + assert ( + diagnostics.termination_reason + == "maximum_iterations_reached_before_residual_tolerance" + ) + + +def test_common_random_number_ground_truth_equals_paired_path_differences() -> None: + result = run_equilibrium_benchmark(_config(), planned_treatment_intensity=[1.0, 0.5]) + control = result.control.panel.sort_values("zone_id").reset_index(drop=True) + treatment = result.treatment.panel.sort_values("zone_id").reset_index(drop=True) + + assert result.metadata["common_random_numbers"] is True + assert result.metadata["control_state_id"] == result.metadata["treatment_state_id"] + np.testing.assert_array_equal( + control["baseline_rider_arrivals"], treatment["baseline_rider_arrivals"] + ) + np.testing.assert_array_equal( + control["baseline_driver_pool"], treatment["baseline_driver_pool"] + ) + expected_trip_effect = treatment["trips"].to_numpy() - control["trips"].to_numpy() + expected_welfare_effect = ( + treatment["total_welfare"].to_numpy() + - control["total_welfare"].to_numpy() + ) + np.testing.assert_allclose(result.zone_effects["trip_effect"], expected_trip_effect) + assert result.ground_truth["market_total_trip_effect"] == pytest.approx( + expected_trip_effect.sum() + ) + assert result.ground_truth["market_total_welfare_effect"] == pytest.approx( + expected_welfare_effect.sum() + ) + assert result.ground_truth["incremental_trips_per_dollar"] == pytest.approx( + expected_trip_effect.sum() / result.ground_truth["treatment_spend"] + ) + + +def test_optional_cross_zone_channel_transmits_a_local_policy_to_neighbor_wait() -> None: + common = dict( + treatment_version=TreatmentVersion.RIDER_DISCOUNT, + cross_zone_share=0.40, + ) + disconnected = run_equilibrium_benchmark( + _config(cross_zone_enabled=False, **common), + planned_treatment_intensity=[1.0, 0.0], + ) + connected = run_equilibrium_benchmark( + _config(cross_zone_enabled=True, **common), + planned_treatment_intensity=[1.0, 0.0], + ) + + disconnected_neighbor = disconnected.zone_effects.set_index("zone_id").loc[1] + connected_neighbor = connected.zone_effects.set_index("zone_id").loc[1] + assert disconnected_neighbor["wait_effect_minutes"] == pytest.approx(0.0, abs=1e-10) + assert abs(float(connected_neighbor["wait_effect_minutes"])) > 1e-4 + assert disconnected.metadata["cross_zone_channel"] is False + assert connected.metadata["cross_zone_channel"] is True + + +def test_zero_policy_has_zero_known_effect_and_no_efficiency_ratio() -> None: + result = run_equilibrium_benchmark(_config(), planned_treatment_intensity=0.0) + + assert result.ground_truth["market_total_trip_effect"] == pytest.approx(0.0) + assert result.ground_truth["market_total_welfare_effect"] == pytest.approx(0.0) + assert result.ground_truth["treatment_spend"] == pytest.approx(0.0) + assert result.ground_truth["incremental_trips_per_dollar"] is None + assert result.ground_truth["incremental_welfare_per_dollar"] is None + + +def test_evidence_labels_and_equations_prevent_empirical_overclaiming() -> None: + result = run_equilibrium_benchmark(_config()) + + assert result.metadata["evidence_type"] == EVIDENCE_TYPE + assert result.metadata["causal_scope"] == CAUSAL_SCOPE + assert result.metadata["empirical_calibration_status"] == EMPIRICAL_STATUS + assert result.metadata["is_nyc_structural_estimate"] is False + assert result.metadata["ground_truth_status"].startswith("known_exactly") + assert "rider_demand" in result.metadata["equations"] + assert "driver_supply" in result.metadata["equations"] + assert "wait_fixed_point" in result.metadata["equations"] + assert "service_probability" in result.metadata["equations"] + assert any("not estimated from NYC" in item for item in result.metadata["limitations"]) + for panel in (result.control.panel, result.treatment.panel): + assert set(panel["evidence_type"]) == {EVIDENCE_TYPE} + assert set(panel["causal_scope"]) == {CAUSAL_SCOPE} + assert set(panel["is_nyc_structural_estimate"]) == {False} + + +def test_configuration_rejects_unknown_or_invalid_values() -> None: + with pytest.raises(ValueError, match="unknown equilibrium"): + EquilibriumConfig.from_mapping({"n_zonez": 2}) + with pytest.raises(ValueError, match="discount_rate"): + EquilibriumConfig(discount_rate=1.1) + with pytest.raises(ValueError, match="treatment_intensity"): + solve_market_equilibrium(_config(), [0.0, 1.1]) + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def test_artifact_writer_publishes_portable_hash_verified_bundle(tmp_path: Path) -> None: + output = tmp_path / "artifacts/benchmarks/equilibrium" + result = run_equilibrium_benchmark(_config(budget=100.0)) + + artifacts = write_equilibrium_artifacts(result, output, tmp_path) + + assert {path.name for path in artifacts.paths()} == { + "summary.json", + "zone_effects.csv", + "ledger.csv", + "manifest.json", + } + assert all(path.is_file() for path in artifacts.paths()) + assert not (output / "EQUILIBRIUM_INCOMPLETE.json").exists() + + summary = json.loads(artifacts.summary_path.read_text(encoding="utf-8")) + manifest = json.loads(artifacts.manifest_path.read_text(encoding="utf-8")) + assert summary["evidence_type"] == EVIDENCE_TYPE + assert summary["causal_scope"] == CAUSAL_SCOPE + assert summary["empirical_calibration_status"] == EMPIRICAL_STATUS + assert summary["is_nyc_structural_estimate"] is False + assert summary["ground_truth"] == result.ground_truth + assert manifest["portable_paths"] is True + assert manifest["checks"] == { + "budget_feasible": True, + "common_random_numbers_verified": True, + "control_equilibrium_converged": True, + "ground_truth_recomputed": True, + "hashes_recomputed": True, + "residuals_within_tolerance": True, + "sufficient_uniqueness_condition_satisfied": True, + "treatment_equilibrium_converged": True, + "welfare_accounting_balanced": True, + } + for entry in manifest["files"]: + assert not Path(entry["path"]).is_absolute() + path = tmp_path / entry["path"] + assert path.is_file() + assert entry["bytes"] == path.stat().st_size + assert entry["sha256"] == _sha256(path) + declared_digest = hashlib.sha256( + json.dumps( + manifest["files"], sort_keys=True, separators=(",", ":") + ).encode("utf-8") + ).hexdigest() + assert manifest["declared_file_set_sha256"] == declared_digest + + stored_effects = pd.read_csv(artifacts.zone_effects_path) + stored_ledger = pd.read_csv(artifacts.ledger_path) + pd.testing.assert_frame_equal(stored_effects, result.zone_effects) + assert set(stored_ledger["scenario"]) == {"control", "treatment"} + assert stored_ledger.loc[ + stored_ledger["scenario"] == "treatment", "treatment_spend" + ].iloc[0] == pytest.approx(result.ground_truth["treatment_spend"]) + + +def test_artifact_writer_is_byte_deterministic_across_project_roots( + tmp_path: Path, +) -> None: + result = run_equilibrium_benchmark(_config()) + first_root = tmp_path / "first" + second_root = tmp_path / "second" + first_root.mkdir() + second_root.mkdir() + relative_output = Path("artifacts/benchmarks/equilibrium") + + first = write_equilibrium_artifacts( + result, first_root / relative_output, first_root + ) + second = write_equilibrium_artifacts( + result, second_root / relative_output, second_root + ) + + first_by_name = {path.name: path.read_bytes() for path in first.paths()} + second_by_name = {path.name: path.read_bytes() for path in second.paths()} + assert first_by_name == second_by_name + manifest = json.loads(first.manifest_path.read_text(encoding="utf-8")) + assert all( + entry["path"].startswith("artifacts/benchmarks/equilibrium/") + for entry in manifest["files"] + ) + + +def test_artifact_writer_rejects_paths_outside_project_root(tmp_path: Path) -> None: + root = tmp_path / "project" + root.mkdir() + outside = tmp_path / "outside/equilibrium" + + with pytest.raises(ValueError, match="outside project_root"): + write_equilibrium_artifacts( + run_equilibrium_benchmark(_config()), outside, root + ) + + assert not outside.exists() + + +def test_artifact_writer_recomputes_truth_before_publishing(tmp_path: Path) -> None: + result = run_equilibrium_benchmark(_config()) + altered_effects = result.zone_effects.copy() + altered_effects.loc[0, "trip_effect"] += 1.0 + tampered = replace(result, zone_effects=altered_effects) + output = tmp_path / "artifacts/benchmarks/equilibrium" + + with pytest.raises(ValueError, match="ground truth failed recomputation"): + write_equilibrium_artifacts(tampered, output, tmp_path) + + assert not output.exists() + + +def test_artifact_writer_withholds_manifest_and_leaves_marker_on_write_failure( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + output = tmp_path / "artifacts/benchmarks/equilibrium" + + def fail_csv(_frame: pd.DataFrame, destination: Path) -> Path: + raise OSError(f"injected failure for {destination.name}") + + monkeypatch.setattr(equilibrium_module, "_atomic_artifact_csv", fail_csv) + with pytest.raises(OSError, match="injected failure"): + write_equilibrium_artifacts( + run_equilibrium_benchmark(_config()), output, tmp_path + ) + + assert (output / "EQUILIBRIUM_INCOMPLETE.json").is_file() + assert not (output / "manifest.json").exists() + assert not list(output.glob(".*-*.json")) diff --git a/CasualLab/tests/test_estimands.py b/CasualLab/tests/test_estimands.py new file mode 100644 index 0000000000000000000000000000000000000000..12d6f95b6fe78711d1517c20d148b8272c0b490c --- /dev/null +++ b/CasualLab/tests/test_estimands.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +import pytest + +from casuallab.estimands import identification_assessment + + +def test_identification_guard_enforces_design_compatibility() -> None: + identified, reasons = identification_assessment( + "direct_effect", + design="geo_cluster", + interference_present=False, + ) + assert not identified + assert any("not compatible" in reason for reason in reasons) + + identified, reasons = identification_assessment( + "spillover_effect", + design="geo_cluster", + interference_present=True, + exposure_mapped=True, + ) + assert not identified + assert any("not compatible" in reason for reason in reasons) + + +def test_identification_guard_rejects_unknown_design() -> None: + with pytest.raises(ValueError, match="unknown design"): + identification_assessment( + "market_total_effect", + design="bogus", + interference_present=False, + ) + diff --git a/CasualLab/tests/test_estimators.py b/CasualLab/tests/test_estimators.py new file mode 100644 index 0000000000000000000000000000000000000000..e63fff2c4dd21d0f0a60c2ec45f4594098286761 --- /dev/null +++ b/CasualLab/tests/test_estimators.py @@ -0,0 +1,328 @@ +from __future__ import annotations + +import numpy as np +import pandas as pd +import pytest + +from casuallab.config import DesignConfig, EstimatorConfig, SimulationConfig +from casuallab.estimators import ( + estimate_effect, + estimate_heterogeneous_effects, + estimate_ladder, +) +from casuallab.simulator import simulate_market + + +def _randomized_sample(seed: int = 4, n_obs: int = 400) -> pd.DataFrame: + rng = np.random.default_rng(seed) + covariate = rng.normal(size=n_obs) + treatment = np.repeat([0.0, 1.0], n_obs // 2) + noise = rng.normal(scale=0.25, size=n_obs) + outcome = 2.0 * treatment + 1.5 * covariate + noise + return pd.DataFrame( + { + "outcome": outcome, + "assigned_treatment": treatment, + "covariate": covariate, + "cluster": np.repeat(np.arange(n_obs // 10), 10), + } + ) + + +def test_difference_in_means_returns_common_uncertainty_contract() -> None: + result = estimate_effect(_randomized_sample(), "difference_in_means") + + assert abs(result.estimate - 2.0) < 0.25 + assert result.standard_error > 0 + assert result.std_error == result.se + assert result.ci_low < result.estimate < result.ci_high + assert result.target_estimand == "intent_to_treat" + assert result.to_dict()["std_error"] == result.standard_error + + +def test_regression_and_cluster_adjustment_recover_constructed_effect() -> None: + data = _randomized_sample() + regression = estimate_effect( + data, + "regression_adjusted", + covariates=("covariate",), + ) + clustered = estimate_effect( + data, + "cluster_robust", + covariates=("covariate",), + cluster="cluster", + ) + + assert abs(regression.estimate - 2.0) < 0.08 + assert np.isclose(regression.estimate, clustered.estimate) + assert clustered.diagnostics["n_clusters"] == 40 + assert clustered.diagnostics["variance_estimator"] == "CR1" + + +def test_difference_in_differences_recovers_known_panel_effect() -> None: + rows: list[dict[str, float | int]] = [] + for unit in range(12): + for period in range(8): + treated_group = float(unit < 6) + post = float(period >= 4) + rows.append( + { + "unit": unit, + "period": period, + "treated_group": treated_group, + "post": post, + "outcome": 0.3 * unit + 0.2 * period + 3.0 * treated_group * post, + } + ) + panel = pd.DataFrame(rows) + config = EstimatorConfig( + outcome="outcome", + treatment="treated_group", + unit="unit", + time="period", + post="post", + ) + result = estimate_effect(panel, "did", config) + + assert np.isclose(result.estimate, 3.0, atol=1e-10) + assert result.diagnostics["parallel_trends_required"] is True + + +def test_cross_fitted_doubly_robust_estimator_recovers_ate() -> None: + data = _randomized_sample(n_obs=600) + result = estimate_effect( + data, + "aipw", + covariates=("covariate",), + crossfit_folds=3, + seed=9, + ) + + assert abs(result.estimate - 2.0) < 0.08 + assert result.diagnostics["estimating_equation"] == "AIPW" + assert result.diagnostics["crossfit_folds"] == 3 + + +def test_doubly_robust_nuisance_folds_keep_clusters_intact() -> None: + data = _randomized_sample(n_obs=400) + # Assignment is homogeneous in each ten-row cluster for this constructed sample. + result = estimate_effect( + data, + "doubly_robust", + covariates=("covariate",), + cluster="cluster", + crossfit_folds=4, + seed=17, + ) + + assert result.diagnostics["crossfit_unit"] == "cluster" + assert result.diagnostics["crossfit_groups"] == 40 + assert result.diagnostics["group_leakage_prevented"] is True + assert result.diagnostics["reference_distribution"] == "cluster_t" + assert result.diagnostics["degrees_freedom"] == 39 + + +def test_synthetic_control_uses_preperiod_donor_fit() -> None: + rows: list[dict[str, float | int | str]] = [] + for period in range(10): + baseline = 10.0 + period + rows.extend( + [ + { + "unit": "treated", + "period": period, + "treatment": float(period >= 6), + "outcome": baseline + (4.0 if period >= 6 else 0.0), + }, + { + "unit": "donor_exact", + "period": period, + "treatment": 0.0, + "outcome": baseline, + }, + { + "unit": "donor_other", + "period": period, + "treatment": 0.0, + "outcome": 0.5 * baseline + 3.0, + }, + ] + ) + panel = pd.DataFrame(rows) + result = estimate_effect( + panel, + "synthetic_control_style", + outcome="outcome", + treatment="treatment", + unit="unit", + time="period", + ) + + assert np.isclose(result.estimate, 4.0, atol=1e-5) + assert result.diagnostics["pre_rmspe"] < 1e-5 + assert np.isclose(sum(result.diagnostics["donor_weights"].values()), 1.0) + assert "uncertainty_warning" in result.diagnostics + + +def test_continuous_saturation_is_regressed_not_dichotomized() -> None: + saturation = np.linspace(0.1, 0.9, 80) + data = pd.DataFrame( + { + "outcome": 5.0 + 3.0 * saturation, + "assigned_treatment": saturation, + } + ) + with pytest.raises(ValueError, match="exactly two"): + estimate_effect(data, "difference_in_means") + result = estimate_effect(data, "regression_adjustment") + assert np.isclose(result.estimate, 3.0) + + +def test_ladder_records_inapplicable_methods() -> None: + data = _randomized_sample() + ladder = estimate_ladder( + data, + methods=("difference_in_means", "cluster_robust"), + ) + + assert ladder.loc[ladder["method"] == "difference_in_means", "status"].iat[0] == "ok" + failed = ladder.loc[ladder["method"] == "cluster_robust"].iloc[0] + assert failed["status"] == "not_applicable" + assert "requires config.cluster" in failed["diagnostics"]["error"] + + +def test_two_way_cluster_robust_uses_geographic_and_time_groups() -> None: + rng = np.random.default_rng(401) + rows: list[dict[str, float | int]] = [] + zone_shocks = rng.normal(0.0, 1.0, 16) + time_shocks = rng.normal(0.0, 1.0, 18) + for period in range(18): + for zone in range(16): + treatment = float(rng.binomial(1, 0.5)) + rows.append( + { + "zone_id": zone, + "time_block": period, + "assigned_treatment": treatment, + "baseline": float(np.cos(zone)), + "outcome": ( + 3.0 + + 2.25 * treatment + + zone_shocks[zone] + + time_shocks[period] + + 0.3 * np.cos(zone) + + rng.normal(0.0, 0.2) + ), + } + ) + result = estimate_effect( + pd.DataFrame(rows), + "two_way_cluster", + cluster="zone_id", + time="time_block", + covariates=("baseline",), + target_estimand="market_total_effect", + ) + + assert result.estimate == pytest.approx(2.25, abs=0.3) + assert result.standard_error > 0 + assert result.diagnostics["n_geographic_clusters"] == 16 + assert result.diagnostics["n_time_clusters"] == 18 + assert result.diagnostics["degrees_freedom"] == 15 + assert result.diagnostics["inference_warning"] is None + + +def test_two_way_cluster_robust_requires_both_group_dimensions() -> None: + with pytest.raises(ValueError, match="config.cluster and config.time"): + estimate_effect( + _randomized_sample(), + "two_way_cluster_robust", + cluster="cluster", + ) + + +def test_simple_hte_benchmark_is_deterministic() -> None: + data = _randomized_sample(n_obs=300) + first = estimate_heterogeneous_effects(data, ("covariate",), seed=21) + second = estimate_heterogeneous_effects(data, ("covariate",), seed=21) + + pd.testing.assert_frame_equal(first, second) + assert set(first["method"]) == {"cross_fitted_linear_t_learner"} + assert np.isfinite(first["estimated_treatment_effect"]).all() + + +def test_no_interference_design_recovers_simulator_truth_within_mc_uncertainty() -> None: + errors: list[float] = [] + for replication in range(24): + simulation = simulate_market( + SimulationConfig( + n_zones=20, + n_periods=12, + seed=500 + replication, + design=DesignConfig(name="geo_cluster", cluster_size=1), + spillover_strength=0.0, + rider_substitution=0.0, + driver_mobility=0.0, + persistence=0.0, + budget=None, + ) + ) + estimate = estimate_effect( + simulation.panel, + "difference_in_means", + target_estimand="market_total_effect", + ) + errors.append( + estimate.estimate - simulation.ground_truth["market_total_effect"] + ) + + error_array = np.asarray(errors) + monte_carlo_se = float(error_array.std(ddof=1) / np.sqrt(len(error_array))) + assert abs(float(error_array.mean())) <= 2.5 * monte_carlo_se + + +def test_individual_saturation_slope_targets_direct_not_total_effect_with_spillovers() -> None: + direct_errors: list[float] = [] + total_errors: list[float] = [] + for replication in range(20): + simulation = simulate_market( + SimulationConfig( + n_zones=10, + n_periods=16, + individuals_per_cell=60, + seed=800 + replication, + design=DesignConfig(name="individual", treatment_probability=0.5), + spillover_strength=0.30, + rider_substitution=0.15, + driver_mobility=0.15, + persistence=0.0, + budget=None, + ) + ) + naive_saturation_slope = estimate_effect( + simulation.panel, + "regression_adjustment", + covariates=( + "baseline_demand", + "baseline_supply", + "hour_sin", + "hour_cos", + ), + target_estimand="controlled_zone_direct_effect", + ).estimate + direct_errors.append( + naive_saturation_slope + - simulation.ground_truth["controlled_zone_direct_effect"] + ) + total_errors.append( + naive_saturation_slope - simulation.ground_truth["market_total_effect"] + ) + + direct_error = np.asarray(direct_errors) + total_error = np.asarray(total_errors) + direct_mcse = float(direct_error.std(ddof=1) / np.sqrt(len(direct_error))) + total_mcse = float(total_error.std(ddof=1) / np.sqrt(len(total_error))) + assert abs(float(direct_error.mean())) <= 2.5 * direct_mcse + assert float(total_error.mean()) < 0 + assert abs(float(total_error.mean())) > 4.0 * total_mcse diff --git a/CasualLab/tests/test_generated_reports.py b/CasualLab/tests/test_generated_reports.py new file mode 100644 index 0000000000000000000000000000000000000000..4fdb49a35f55c6c56810e742a3c8b767593fdcd8 --- /dev/null +++ b/CasualLab/tests/test_generated_reports.py @@ -0,0 +1,1093 @@ +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +import pandas as pd +import pytest +from test_equilibrium import _config as _equilibrium_config +from test_nyc_benchmark import _laptop_config, _verified_anchor_artifacts +from test_nyc_events import _data_manifest as _event_data_manifest +from test_nyc_events import _panel as _event_panel +from test_nyc_events import _snapshots as _event_snapshots +from test_nyc_graph_benchmark import _synthetic_bundle +from test_nyc_income import _fixture as _income_fixture +from test_nyc_simulation import write_nyc_calibration_test_bundle +from test_nyc_weather import _data_manifest, _panel, _raw_weather + +from casuallab.cli import write_nyc_simulation_anchor_output +from casuallab.config import SimulationConfig +from casuallab.equilibrium import ( + run_equilibrium_benchmark, + write_equilibrium_artifacts, +) +from casuallab.generated_reports import generate_report_bundle +from casuallab.interference_benchmark import ( + InterferenceBenchmarkConfig, + run_interference_benchmark, +) +from casuallab.nyc_benchmark import ( + run_nyc_informed_marketplace_benchmark, + write_nyc_benchmark_artifacts, +) +from casuallab.nyc_events import write_nyc_events_bundle +from casuallab.nyc_graph_benchmark import ( + NYCGraphBenchmarkConfig, + run_nyc_graph_benchmark, + write_nyc_graph_benchmark_artifacts, +) +from casuallab.nyc_income import write_nyc_income_bundle +from casuallab.nyc_simulation import ( + NYCSimulationAnchorSettings, + build_nyc_simulation_anchor, +) +from casuallab.nyc_weather import write_nyc_weather_bundle + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _rewrite_bundle_json_role( + manifest_path: Path, + role: str, + payload: dict[str, object], +) -> Path: + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + entry = next(item for item in manifest["files"] if item["role"] == role) + declared = Path(entry["path"]) + artifact_path = next( + parent / declared + for parent in manifest_path.parents + if (parent / declared).is_file() + ) + artifact_path.write_text( + json.dumps(payload, sort_keys=True, separators=(",", ":")), + encoding="utf-8", + ) + entry["bytes"] = artifact_path.stat().st_size + entry["sha256"] = _sha256(artifact_path) + manifest["declared_file_set_sha256"] = hashlib.sha256( + json.dumps(manifest["files"], sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + manifest_path.write_text( + json.dumps(manifest, sort_keys=True, separators=(",", ":")), + encoding="utf-8", + ) + return artifact_path + + +def _write_verified_nyc_full_evidence(tmp_path: Path) -> tuple[Path, Path]: + root = tmp_path / "nyc_evidence" + validation_path = root / "artifacts/nyc_full/validation.json" + data_manifest_path = root / "data/nyc_full/manifest.json" + analysis_manifest_path = root / "artifacts/nyc_full/manifest.json" + validation_path.parent.mkdir(parents=True) + data_manifest_path.parent.mkdir(parents=True) + raw_sha = "9" * 64 + config = { + "source": "nyc_hvfhv", + "mode": "full", + "nyc_year": 2024, + "nyc_months": [1], + "nyc_expected_rows": 19_663_930, + "nyc_expected_bytes": 472_757_547, + "nyc_expected_sha256": raw_sha, + "manifest_path": "data/nyc_full/manifest.json", + } + data_manifest_path.write_text( + json.dumps( + { + "config": config, + "files": [], + "metadata": { + "causal_claim": False, + "evidence_label": "descriptive_real_data", + }, + } + ), + encoding="utf-8", + ) + data_manifest_sha = _sha256(data_manifest_path) + validation_path.write_text( + json.dumps( + { + "evidence_label": "descriptive_real_data", + "causal_claim": False, + "validation_passed": True, + "checks": { + "raw_equals_clean": True, + "zone_conserves_clean": True, + "od_conserves_clean": True, + "calendar_complete": True, + "manifest_files_valid": True, + "manifest_scope_valid": True, + "resource_limit_passed": True, + }, + "scope": { + "source": "nyc_hvfhv", + "pickup_month": "2024-01", + "unit": "published_completed_trip_record", + "population_claim": False, + }, + "coverage": { + "clean_rows": 19_663_930, + "service_dates": 31, + "hours_of_day": 24, + "date_hours": 744, + }, + "conservation": { + "raw_rows": 19_663_930, + "zone_time_rows": 194_928, + "od_rows": 6_877_734, + "zone_trip_sum": 19_663_930, + "od_trip_sum": 19_663_930, + }, + "provenance": { + "data_manifest": "data/nyc_full/manifest.json", + "data_manifest_sha256": data_manifest_sha, + "sha256": [raw_sha], + }, + "resources": { + "elapsed_seconds": 55.18, + "max_rss_bytes": 3_839_901_696, + "peak_memory_footprint_bytes": 6_313_925_232, + "memory_limit_bytes": 16 * 1024**3, + }, + "limitations": [ + "Published completed-trip records exclude latent and unserved demand.", + "Observed fare-demand relationships are endogenous associations, not elasticities.", + "No treatment assignment exists; no causal intervention effect is estimated.", + ], + } + ), + encoding="utf-8", + ) + files = [] + for path in (validation_path, data_manifest_path): + files.append( + { + "path": str(path.relative_to(root)), + "bytes": path.stat().st_size, + "sha256": _sha256(path), + } + ) + analysis_manifest_path.write_text( + json.dumps( + { + "config": config, + "files": files, + "metadata": { + "evidence_label": "descriptive_real_data", + "causal_claim": False, + "validation_passed": True, + "source_data_manifest_sha256": data_manifest_sha, + }, + } + ), + encoding="utf-8", + ) + return validation_path, analysis_manifest_path + + +def _write_treatment_version_policy_evidence( + tmp_path: Path, bundled_policy_path: Path +) -> tuple[Path, Path]: + root = tmp_path / "version_policy_evidence" + summary_path = root / "artifacts/benchmarks/treatment_version_policy_results.csv" + ledger_path = ( + root / "artifacts/benchmarks/treatment_version_policy_market_ledger.csv" + ) + manifest_path = ( + root / "artifacts/benchmarks/treatment_version_policy_manifest.json" + ) + summary_path.parent.mkdir(parents=True) + base = pd.read_csv(bundled_policy_path) + versions = ("rider_discount", "driver_incentive", "bundled") + frames = [] + ledger_rows = [] + pairing = "common training/holdout market seeds across intervention versions" + for version in versions: + frame = base.copy() + frame["treatment_version"] = version + frame["version_pairing"] = pairing + frame["version_evidence_scope"] = ( + "semi-synthetic response-function sensitivity; not an empirical dose response" + ) + frame["simulation_config"] = json.dumps( + {"n_zones": 4, "treatment_version": version}, sort_keys=True + ) + frames.append(frame) + for policy in frame["policy"]: + for seed in (3, 4): + ledger_rows.append( + { + "policy": policy, + "treatment_version": version, + "version_pairing": pairing, + "holdout_market_seed": seed, + "evidence_type": "semi_synthetic_policy_holdout_market", + } + ) + pd.concat(frames, ignore_index=True).to_csv(summary_path, index=False) + pd.DataFrame(ledger_rows).to_csv(ledger_path, index=False) + files = [ + { + "path": str(path.relative_to(root)), + "bytes": path.stat().st_size, + "sha256": _sha256(path), + } + for path in (summary_path, ledger_path) + ] + manifest_path.write_text( + json.dumps( + { + "files": files, + "metadata": { + "evidence_type": ( + "semi_synthetic_treatment_version_policy_sensitivity" + ), + "treatment_versions": list(versions), + "version_pairing": pairing, + }, + } + ), + encoding="utf-8", + ) + return summary_path, manifest_path + + +def _write_interference_evidence(tmp_path: Path) -> tuple[Path, Path]: + root = tmp_path / "interference_evidence" + output = root / "artifacts/benchmarks" + output.mkdir(parents=True) + result = run_interference_benchmark( + InterferenceBenchmarkConfig( + replications=4, + n_zones=8, + n_clusters=8, + n_periods=12, + seed=777, + ) + ) + paths = { + "interference_records.csv": result.records, + "interference_summary.csv": result.summary, + "interference_failures.csv": result.failures, + "interference_fit_ledger.csv": result.fit_ledger, + } + for name, frame in paths.items(): + frame.to_csv(output / name, index=False) + metadata_path = output / "interference_metadata.json" + metadata_path.write_text(json.dumps(result.metadata, sort_keys=True), encoding="utf-8") + files = [ + { + "path": str(path.relative_to(root)), + "bytes": path.stat().st_size, + "sha256": _sha256(path), + } + for path in sorted(output.glob("interference_*.csv")) + ] + files.append( + { + "path": str(metadata_path.relative_to(root)), + "bytes": metadata_path.stat().st_size, + "sha256": _sha256(metadata_path), + } + ) + manifest_path = output / "interference_manifest.json" + manifest_path.write_text( + json.dumps( + { + "files": files, + "metadata": { + "evidence_type": result.metadata["evidence_type"], + "benchmark_config": result.metadata["config"], + "known_estimands": result.metadata["known_estimands"], + "controlled_exposure_not_market_total": True, + }, + } + ), + encoding="utf-8", + ) + return output / "interference_summary.csv", manifest_path + + +def _write_nyc_simulation_anchor_evidence( + tmp_path: Path, +) -> tuple[Path, Path, dict[str, Path]]: + root = tmp_path / "nyc_anchor_evidence" + calibration_bundle = write_nyc_calibration_test_bundle(root) + simulation_config = SimulationConfig( + base_demand=80.0, + base_supply=40.0, + direct_demand_effect=0.31, + direct_supply_effect=0.27, + spillover_strength=0.19, + persistence=0.41, + rider_substitution=0.17, + driver_mobility=0.23, + ) + simulation_config_path = root / "configs/simulation.yaml" + simulation_config_path.parent.mkdir(parents=True) + simulation_config_path.write_text( + json.dumps(simulation_config.to_dict(), sort_keys=True), encoding="utf-8" + ) + anchor = build_nyc_simulation_anchor( + calibration_bundle["calibration"], + project_root=root, + manifest_path=calibration_bundle["bundle_manifest"], + settings=NYCSimulationAnchorSettings( + target_n_zones=2, + target_n_periods=168, + seed=99, + ), + assumption_template=simulation_config, + ) + outputs = write_nyc_simulation_anchor_output( + anchor, + root / "artifacts/nyc_full/simulation_anchor", + calibration_path=calibration_bundle["calibration"], + calibration_manifest_path=calibration_bundle["bundle_manifest"], + simulation_config_path=simulation_config_path, + project_root=root, + ) + return outputs["anchor"], outputs["manifest"], calibration_bundle + + +def _write_six_new_evidence_manifests(tmp_path: Path) -> dict[str, Path]: + nyc_root = tmp_path / "nyc_benchmark_project" + nyc_root.mkdir() + anchor = _verified_anchor_artifacts(nyc_root) + nyc_result = run_nyc_informed_marketplace_benchmark( + anchor["anchor_path"], + anchor["anchor_manifest_path"], + config=_laptop_config(), + project_root=nyc_root, + ) + nyc_paths = write_nyc_benchmark_artifacts( + nyc_result, + "artifacts/benchmarks/nyc_informed", + project_root=nyc_root, + ) + + graph_root = tmp_path / "nyc_graph_project" + graph_root.mkdir() + calibration_bundle = _synthetic_bundle(graph_root) + graph_result = run_nyc_graph_benchmark( + calibration_bundle, + NYCGraphBenchmarkConfig( + replications=2, + n_zones=12, + n_periods=12, + seed=904, + ), + ) + graph_paths = write_nyc_graph_benchmark_artifacts( + graph_result, + "artifacts/benchmarks/nyc_graph", + project_root=graph_root, + ) + + equilibrium_root = tmp_path / "equilibrium_project" + equilibrium_root.mkdir() + equilibrium_paths = write_equilibrium_artifacts( + run_equilibrium_benchmark(_equilibrium_config(budget=100.0)), + equilibrium_root / "artifacts/benchmarks/equilibrium", + equilibrium_root, + ) + + weather_root = tmp_path / "weather_project" + weather_root.mkdir() + raw_weather = weather_root / "data/nyc_weather/raw/noaa.csv" + raw_weather.parent.mkdir(parents=True) + weather_config = _raw_weather(raw_weather) + panel_directory = weather_root / "data/nyc_full/panel/zone_time" + panel_directory.mkdir(parents=True) + panel_path = panel_directory / "part.parquet" + panel = _panel(panel_path) + data_manifest = _data_manifest( + weather_root, + panel_path, + int(panel["trip_count"].sum()), + ) + weather_paths = write_nyc_weather_bundle( + raw_weather, + panel_directory, + data_manifest, + weather_root / "artifacts/nyc_full/weather", + project_root=weather_root, + config=weather_config, + ) + + events_root = tmp_path / "events_project" + events_root.mkdir() + holiday_path, event_path, events_config = _event_snapshots(events_root) + event_panel_directory = events_root / "data/nyc_full/panel/zone_time" + event_panel_directory.mkdir(parents=True) + event_panel_path = event_panel_directory / "part.parquet" + event_panel = _event_panel(event_panel_path) + event_data_manifest = _event_data_manifest( + events_root, + event_panel_path, + int(event_panel["trip_count"].sum()), + ) + events_paths = write_nyc_events_bundle( + holiday_path, + event_path, + event_panel_directory, + event_data_manifest, + events_root / "artifacts/nyc_full/events", + project_root=events_root, + config=events_config, + ) + + income_root = tmp_path / "income_project" + income_root.mkdir() + income_inputs, income_config = _income_fixture(income_root) + income_paths = write_nyc_income_bundle( + income_inputs["taxi"], + income_inputs["nta"], + income_inputs["tract"], + income_inputs["acs"], + income_inputs["panel_dir"], + income_inputs["manifest"], + income_root / "artifacts/nyc_full/income", + project_root=income_root, + config=income_config, + ) + return { + "nyc": nyc_paths["manifest"], + "graph": graph_paths["manifest"], + "equilibrium": equilibrium_paths.manifest_path, + "weather": weather_paths.manifest_path, + "events": events_paths.manifest_path, + "income": income_paths.manifest_path, + } + + +def test_report_bundle_generates_technical_executive_and_appendix(tmp_path: Path) -> None: + benchmark_path = tmp_path / "benchmark.csv" + policy_path = tmp_path / "policy.csv" + descriptive_path = tmp_path / "descriptive.json" + hte_summary_path = tmp_path / "hte_recovery.json" + hte_calibration_path = tmp_path / "hte_calibration.csv" + hte_stability_path = tmp_path / "hte_stability.csv" + nyc_validation_path, nyc_manifest_path = _write_verified_nyc_full_evidence( + tmp_path + ) + rows = [] + for scenario, rmse in (("none", 0.2), ("adverse", 0.4)): + rows.append( + { + "scenario": scenario, + "declared_scenario_set": '["adverse", "none"]', + "declared_scenario_count": 2, + "spillover_strength": 0.0, + "persistence": 0.0, + "design": "geo_cluster", + "estimator": "cluster_robust", + "target_estimand": "market_total_effect", + "identified": True, + "inference_valid": True, + "fit_complete": True, + "applicable": True, + "attempted_fits": 10, + "successful_fits": 10, + "failed_fits": 0, + "bias": 0.1, + "rmse": rmse, + "coverage": 0.95, + "power": 0.8, + "confidence_level": 0.95, + "evidence_type": "semi_synthetic_causal_monte_carlo", + } + ) + pd.DataFrame(rows).to_csv(benchmark_path, index=False) + policies = ["no_treatment", "random", "uniform", "rule_based", "model_based"] + policy_rows = len(policies) + pd.DataFrame( + { + "policy": policies, + "expected_incremental_outcome": [0.0, 2.0, 2.3, 2.6, 3.0], + "incremental_outcome_se": [0.0, 0.2, 0.2, 0.25, 0.3], + "incremental_outcome_p10": [0.0, 1.5, 1.7, 2.0, 2.4], + "incremental_outcome_vs_random": [-2.0, 0.0, 0.3, 0.6, 1.0], + "paired_difference_se_vs_random": [0.1, 0.0, 0.1, 0.1, 0.1], + "budget_spent": [0.0, 10.0, 10.0, 10.0, 10.0], + "budget_efficiency": [float("nan"), 0.2, 0.23, 0.26, 0.3], + "budget_feasible": [True] * policy_rows, + "evaluation_complete": [True] * policy_rows, + "policy_eligible": [True] * policy_rows, + "mean_model_instability": [0.0, 0.0, 0.0, 0.0, 0.1], + "decision_instability": [0.0, 0.0, 0.0, 0.0, 0.05], + "training_market_seeds": ["[1, 2]"] * policy_rows, + "holdout_market_seeds": ["[3, 4]"] * policy_rows, + "training_markets": [2] * policy_rows, + "holdout_markets": [2] * policy_rows, + "training_signal": [ + "randomized observed outcomes; no structural truth columns" + ] + * policy_rows, + "evaluation_engine": [ + "full marketplace simulator rerun per policy and seed" + ] + * policy_rows, + "planning_cost_basis": [ + "pre-treatment features; no treated holdout counterfactual" + ] + * policy_rows, + "target_estimand": ["full_horizon_incremental_trips"] * policy_rows, + "target_population_id": ["paired_market_total"] * policy_rows, + "n_zones": [4] * policy_rows, + "n_periods": [12] * policy_rows, + "weighting": ["paired mean"] * policy_rows, + "simulation_config": ['{"n_zones":4}'] * policy_rows, + "policy_config": ['{"budget":10}'] * policy_rows, + "evidence_type": ["semi_synthetic_policy_holdout"] * policy_rows, + } + ).to_csv(policy_path, index=False) + version_policy_path, version_policy_manifest_path = ( + _write_treatment_version_policy_evidence(tmp_path, policy_path) + ) + interference_summary_path, interference_manifest_path = ( + _write_interference_evidence(tmp_path) + ) + nyc_anchor_path, nyc_anchor_manifest_path, nyc_anchor_bundle = ( + _write_nyc_simulation_anchor_evidence(tmp_path) + ) + descriptive_path.write_text( + '{"evidence_type":"empirical_association","panel_rows":170,' + '"total_observed_trips":300}', + encoding="utf-8", + ) + hte_summary_path.write_text( + json.dumps( + { + "evidence_type": "semi_synthetic_hte_known_truth_recovery", + "target_estimand": "controlled_zone_direct_effect", + "rows": 32, + "bias": 0.02, + "rmse": 0.15, + "fold_mean_cate_sd": 0.03, + "known_truth_sd": 0.10, + "oracle_constant_effect_rmse": 0.10, + "predicted_truth_correlation": 0.20, + "predicted_truth_rank_correlation": 0.15, + "hte_beats_oracle_constant": False, + "recovery_gate": "rmse_below_oracle_constant_effect_rmse", + "crossfit_group": "geographic_randomization_cluster", + "interference": 0.0, + "persistence": 0.0, + } + ), + encoding="utf-8", + ) + pd.DataFrame( + { + "score_bin": ["low", "high"], + "mean_predicted_cate": [0.2, 0.7], + "mean_known_truth": [0.1, 0.8], + "mean_error": [0.1, -0.1], + "rmse": [0.12, 0.14], + "rows": [16, 16], + } + ).to_csv(hte_calibration_path, index=False) + pd.DataFrame( + { + "crossfit_fold": [0, 1], + "mean_predicted_cate": [0.4, 0.5], + "mean_known_truth": [0.42, 0.48], + "mean_error": [-0.02, 0.02], + "rmse": [0.11, 0.12], + "rows": [16, 16], + } + ).to_csv(hte_stability_path, index=False) + + paths = generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "reports", + policy_path=policy_path, + descriptive_path=descriptive_path, + hte_summary_path=hte_summary_path, + hte_calibration_path=hte_calibration_path, + hte_stability_path=hte_stability_path, + nyc_full_validation_path=nyc_validation_path, + nyc_full_manifest_path=nyc_manifest_path, + treatment_version_policy_path=version_policy_path, + treatment_version_policy_manifest_path=version_policy_manifest_path, + interference_summary_path=interference_summary_path, + interference_manifest_path=interference_manifest_path, + nyc_simulation_anchor_path=nyc_anchor_path, + nyc_simulation_anchor_manifest_path=nyc_anchor_manifest_path, + target_estimand="market_total_effect", + ) + + assert set(paths) == {"technical", "executive", "appendix"} + assert all(path.is_file() for path in paths.values()) + technical = paths["technical"].read_text(encoding="utf-8") + executive = paths["executive"].read_text(encoding="utf-8") + assert "0.4000" in technical + assert "300 trips" in technical + assert "Input hashes" not in technical + assert "Reproducibility inputs" in executive + assert "geo_cluster" in executive + assert "controlled_zone_direct_effect" in technical + assert "does not beat the oracle constant-effect baseline" in technical + assert "not decision-ready" in executive + assert "HTE recovery summary SHA-256" in technical + assert "Heterogeneity evidence" in executive + assert "No unique policy winner is issued" in executive + assert "19,663,930 published completed-trip records" in technical + assert "55.18 seconds" in technical + assert "3,839,901,696 bytes (3.58 GiB)" in technical + assert "6,313,925,232 bytes (5.88 GiB)" in executive + assert "NYC full validation SHA-256" in technical + assert "has not been verified below" not in technical + assert "same 2 training and 2 holdout market seeds" in executive + assert "Treatment-version policy summary SHA-256" in technical + assert "not an empirical dose response" in executive + assert "two-stage geographic saturation" in technical + assert "market-total bias, RMSE" in executive + assert "Interference summary SHA-256" in technical + assert "NYC-informed semi-synthetic scale anchor" in technical + assert "7,440 published January 2024 completed trips" in technical + assert "Treatment response, supply response" in executive + assert "NYC simulation anchor SHA-256" in technical + assert "NYC anchor assumption template SHA-256" in technical + + source_file = nyc_anchor_bundle["source_file"] + original_source = source_file.read_text(encoding="utf-8") + source_file.write_text(original_source + "tampered", encoding="utf-8") + with pytest.raises(ValueError, match="NYC source-data manifest byte mismatch"): + generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "stale_nyc_anchor_reports", + nyc_simulation_anchor_path=nyc_anchor_path, + nyc_simulation_anchor_manifest_path=nyc_anchor_manifest_path, + target_estimand="market_total_effect", + ) + source_file.write_text(original_source, encoding="utf-8") + + original_anchor = nyc_anchor_path.read_text(encoding="utf-8") + original_anchor_manifest = nyc_anchor_manifest_path.read_text(encoding="utf-8") + tampered_anchor = json.loads(original_anchor) + tampered_anchor["simulation_config"]["persistence"] = 0.99 + tampered_anchor["field_provenance"]["explicit_assumptions"]["persistence"][ + "value" + ] = 0.99 + nyc_anchor_path.write_text(json.dumps(tampered_anchor), encoding="utf-8") + tampered_manifest = json.loads(original_anchor_manifest) + anchor_entry = next( + entry + for entry in tampered_manifest["files"] + if entry["path"].endswith("nyc_simulation_anchor.json") + ) + anchor_entry["bytes"] = nyc_anchor_path.stat().st_size + anchor_entry["sha256"] = _sha256(nyc_anchor_path) + nyc_anchor_manifest_path.write_text( + json.dumps(tampered_manifest), encoding="utf-8" + ) + with pytest.raises(ValueError, match="causal assumptions disagree"): + generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "unsafe_nyc_anchor_reports", + nyc_simulation_anchor_path=nyc_anchor_path, + nyc_simulation_anchor_manifest_path=nyc_anchor_manifest_path, + target_estimand="market_total_effect", + ) + nyc_anchor_path.write_text(original_anchor, encoding="utf-8") + nyc_anchor_manifest_path.write_text(original_anchor_manifest, encoding="utf-8") + + original_interference = interference_summary_path.read_text(encoding="utf-8") + interference_summary_path.write_text( + original_interference + "\n", encoding="utf-8" + ) + with pytest.raises(ValueError, match="interference benchmark manifest byte mismatch"): + generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "stale_interference_reports", + interference_summary_path=interference_summary_path, + interference_manifest_path=interference_manifest_path, + target_estimand="market_total_effect", + ) + interference_summary_path.write_text(original_interference, encoding="utf-8") + + original_validation = nyc_validation_path.read_text(encoding="utf-8") + failed_validation = json.loads(original_validation) + failed_validation["checks"]["calendar_complete"] = False + nyc_validation_path.write_text(json.dumps(failed_validation), encoding="utf-8") + with pytest.raises(ValueError, match="checks did not all pass"): + generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "failed_nyc_reports", + policy_path=policy_path, + descriptive_path=descriptive_path, + hte_summary_path=hte_summary_path, + hte_calibration_path=hte_calibration_path, + hte_stability_path=hte_stability_path, + nyc_full_validation_path=nyc_validation_path, + nyc_full_manifest_path=nyc_manifest_path, + treatment_version_policy_path=version_policy_path, + treatment_version_policy_manifest_path=version_policy_manifest_path, + target_estimand="market_total_effect", + ) + nyc_validation_path.write_text(original_validation, encoding="utf-8") + + tampered_validation = json.loads(original_validation) + tampered_validation["resources"]["max_rss_bytes"] += 1 + nyc_validation_path.write_text(json.dumps(tampered_validation), encoding="utf-8") + with pytest.raises(ValueError, match="manifest SHA-256 mismatch"): + generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "stale_nyc_reports", + policy_path=policy_path, + descriptive_path=descriptive_path, + hte_summary_path=hte_summary_path, + hte_calibration_path=hte_calibration_path, + hte_stability_path=hte_stability_path, + nyc_full_validation_path=nyc_validation_path, + nyc_full_manifest_path=nyc_manifest_path, + treatment_version_policy_path=version_policy_path, + treatment_version_policy_manifest_path=version_policy_manifest_path, + target_estimand="market_total_effect", + ) + nyc_validation_path.write_text(original_validation, encoding="utf-8") + + original_version_policy = version_policy_path.read_text(encoding="utf-8") + version_policy_path.write_text(original_version_policy + "\n", encoding="utf-8") + with pytest.raises( + ValueError, match="treatment-version policy manifest byte mismatch" + ): + generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "stale_version_policy_reports", + policy_path=policy_path, + descriptive_path=descriptive_path, + hte_summary_path=hte_summary_path, + hte_calibration_path=hte_calibration_path, + hte_stability_path=hte_stability_path, + nyc_full_validation_path=nyc_validation_path, + nyc_full_manifest_path=nyc_manifest_path, + treatment_version_policy_path=version_policy_path, + treatment_version_policy_manifest_path=version_policy_manifest_path, + target_estimand="market_total_effect", + ) + version_policy_path.write_text(original_version_policy, encoding="utf-8") + + invalid_hte = json.loads(hte_summary_path.read_text(encoding="utf-8")) + invalid_hte["interference"] = 0.2 + hte_summary_path.write_text(json.dumps(invalid_hte), encoding="utf-8") + with pytest.raises(ValueError, match="interference and persistence disabled"): + generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "unsafe_reports", + policy_path=policy_path, + descriptive_path=descriptive_path, + hte_summary_path=hte_summary_path, + hte_calibration_path=hte_calibration_path, + hte_stability_path=hte_stability_path, + nyc_full_validation_path=nyc_validation_path, + nyc_full_manifest_path=nyc_manifest_path, + treatment_version_policy_path=version_policy_path, + treatment_version_policy_manifest_path=version_policy_manifest_path, + target_estimand="market_total_effect", + ) + + +def test_report_bundle_withholds_recommendation_if_scenario_is_unidentified( + tmp_path: Path, +) -> None: + benchmark_path = tmp_path / "benchmark.csv" + pd.DataFrame( + { + "scenario": ["none", "spillover"], + "declared_scenario_set": ['["none", "spillover"]'] * 2, + "declared_scenario_count": [2, 2], + "design": ["geo_cluster", "geo_cluster"], + "estimator": ["cluster_robust", "cluster_robust"], + "target_estimand": ["market_total_effect"] * 2, + "identified": [True, False], + "inference_valid": [True, True], + "fit_complete": [True, True], + "applicable": [True, True], + "attempted_fits": [10, 10], + "successful_fits": [10, 10], + "rmse": [0.2, 0.3], + "coverage": [0.95, 0.95], + "power": [0.8, 0.8], + "bias": [0.1, float("nan")], + "evidence_type": ["semi_synthetic_causal_monte_carlo"] * 2, + } + ).to_csv(benchmark_path, index=False) + + paths = generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "reports", + ) + + executive = paths["executive"].read_text(encoding="utf-8") + technical = paths["technical"].read_text(encoding="utf-8") + assert "No robust design recommendation is issued" in executive + assert "no robust rollout recommendation" in executive + assert "Verified NYC full-month artifacts were not supplied" in technical + assert "has not been verified below" not in technical + + +def test_report_bundle_validates_six_new_evidence_layers_and_fails_closed( + tmp_path: Path, +) -> None: + benchmark_path = tmp_path / "benchmark.csv" + pd.DataFrame( + { + "scenario": ["none", "spillover"], + "declared_scenario_set": ['["none", "spillover"]'] * 2, + "declared_scenario_count": [2, 2], + "design": ["geo_cluster", "geo_cluster"], + "estimator": ["cluster_robust", "cluster_robust"], + "target_estimand": ["market_total_effect"] * 2, + "identified": [True, True], + "inference_valid": [True, True], + "fit_complete": [True, True], + "applicable": [True, True], + "attempted_fits": [10, 10], + "successful_fits": [10, 10], + "rmse": [0.2, 0.3], + "coverage": [0.95, 0.90], + "power": [0.8, 0.75], + "bias": [0.01, 0.02], + "evidence_type": ["semi_synthetic_causal_monte_carlo"] * 2, + } + ).to_csv(benchmark_path, index=False) + manifests = _write_six_new_evidence_manifests(tmp_path) + report_arguments = { + "nyc_benchmark_manifest_path": manifests["nyc"], + "nyc_graph_benchmark_manifest_path": manifests["graph"], + "equilibrium_manifest_path": manifests["equilibrium"], + "nyc_weather_manifest_path": manifests["weather"], + "nyc_events_manifest_path": manifests["events"], + "nyc_income_manifest_path": manifests["income"], + } + + paths = generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "reports", + **report_arguments, + ) + + technical = paths["technical"].read_text(encoding="utf-8") + executive = paths["executive"].read_text(encoding="utf-8") + appendix = paths["appendix"].read_text(encoding="utf-8") + for body in (technical, executive, appendix): + assert "NYC-informed known-truth" in body + assert "NYC OD-graph" in body or "NYC graph" in body + assert "equilibrium" in body.lower() + assert "NYC NOAA weather" in body + assert "calendar" in body.lower() and "permitted-event" in body.lower() + assert "neighborhood-income" in body.lower() + assert "not a treatment effect estimated from NYC trips" in technical + assert "not an NYC structural estimate" in technical + assert "not a causal weather effect" in technical + assert "all 0 weekend days" in technical + assert "not rider or driver income" in technical + assert "does not identify a causal income effect" in technical + assert "dominant-nonresidential zones" in technical + assert "it is not the primary result" in technical + + events_manifest = json.loads(manifests["events"].read_text(encoding="utf-8")) + holiday_entry = next( + entry + for entry in events_manifest["inputs"] + if entry["role"] == "official_holiday_snapshot" + ) + holiday_path = next( + parent / holiday_entry["path"] + for parent in manifests["events"].parents + if (parent / holiday_entry["path"]).is_file() + ) + original_holiday = holiday_path.read_bytes() + holiday_path.write_bytes(original_holiday + b"\n") + with pytest.raises(ValueError, match="input manifest byte mismatch"): + generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "tampered_events_report", + nyc_events_manifest_path=manifests["events"], + ) + holiday_path.write_bytes(original_holiday) + + original_events_manifest = manifests["events"].read_bytes() + unsafe_events = json.loads(original_events_manifest) + unsafe_events["checks"][ + "zero_duration_source_intervals_retained_and_excluded" + ] = False + manifests["events"].write_text(json.dumps(unsafe_events), encoding="utf-8") + with pytest.raises(ValueError, match="unsafe evidence schema"): + generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "unsafe_event_interval_report", + nyc_events_manifest_path=manifests["events"], + ) + manifests["events"].write_bytes(original_events_manifest) + + events_payload = json.loads(original_events_manifest) + events_summary_entry = next( + entry for entry in events_payload["files"] if entry["role"] == "descriptive_summary" + ) + events_summary_path = next( + parent / events_summary_entry["path"] + for parent in manifests["events"].parents + if (parent / events_summary_entry["path"]).is_file() + ) + original_events_summary = events_summary_path.read_bytes() + unsafe_events_summary = json.loads(original_events_summary) + unsafe_events_summary["coverage"][ + "zero_duration_interval_rows_retained_but_not_expanded" + ] += 1 + _rewrite_bundle_json_role( + manifests["events"], "descriptive_summary", unsafe_events_summary + ) + with pytest.raises(ValueError, match="coverage is inconsistent"): + generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "unsafe_event_count_report", + nyc_events_manifest_path=manifests["events"], + ) + events_summary_path.write_bytes(original_events_summary) + manifests["events"].write_bytes(original_events_manifest) + + original_income_manifest = manifests["income"].read_bytes() + unsafe_income = json.loads(original_income_manifest) + unsafe_income["causal_claim"] = True + manifests["income"].write_text(json.dumps(unsafe_income), encoding="utf-8") + with pytest.raises(ValueError, match="unsafe evidence schema"): + generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "unsafe_income_report", + nyc_income_manifest_path=manifests["income"], + ) + manifests["income"].write_bytes(original_income_manifest) + + unsafe_income = json.loads(original_income_manifest) + unsafe_income["checks"]["dominant_nonresidential_primary_unclassified"] = False + manifests["income"].write_text(json.dumps(unsafe_income), encoding="utf-8") + with pytest.raises(ValueError, match="unsafe evidence schema"): + generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "unsafe_income_classification_report", + nyc_income_manifest_path=manifests["income"], + ) + manifests["income"].write_bytes(original_income_manifest) + + income_payload = json.loads(original_income_manifest) + income_summary_entry = next( + entry + for entry in income_payload["files"] + if entry["role"] == "income_association_summary" + ) + income_summary_path = next( + parent / income_summary_entry["path"] + for parent in manifests["income"].parents + if (parent / income_summary_entry["path"]).is_file() + ) + original_income_summary = income_summary_path.read_bytes() + unsafe_income_summary = json.loads(original_income_summary) + unsafe_income_summary["classification_uncertainty"][ + "zone_level_margin_of_error_propagated" + ] = True + _rewrite_bundle_json_role( + manifests["income"], "income_association_summary", unsafe_income_summary + ) + with pytest.raises(ValueError, match="violates its ecological scope"): + generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "unsafe_income_uncertainty_report", + nyc_income_manifest_path=manifests["income"], + ) + income_summary_path.write_bytes(original_income_summary) + manifests["income"].write_bytes(original_income_manifest) + + unsafe_income_summary = json.loads(original_income_summary) + unsafe_income_summary["sensitivity"]["all_zone_area_allocation"][ + "primary_result" + ] = True + _rewrite_bundle_json_role( + manifests["income"], "income_association_summary", unsafe_income_summary + ) + with pytest.raises(ValueError, match="sensitivity arithmetic is inconsistent"): + generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "unsafe_income_sensitivity_report", + nyc_income_manifest_path=manifests["income"], + ) + income_summary_path.write_bytes(original_income_summary) + manifests["income"].write_bytes(original_income_manifest) + + with pytest.raises(FileNotFoundError, match="manifest is required"): + generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "partial_events_report", + nyc_events_manifest_path=tmp_path / "missing-events-manifest.json", + ) + + nyc_manifest = json.loads(manifests["nyc"].read_text(encoding="utf-8")) + nyc_summary_entry = next( + entry for entry in nyc_manifest["files"] if entry["role"] == "summary" + ) + nyc_summary_path = manifests["nyc"].parent / nyc_summary_entry["path"] + original_nyc_summary = nyc_summary_path.read_bytes() + nyc_summary_path.write_bytes(original_nyc_summary + b"\n") + with pytest.raises(ValueError, match="manifest byte mismatch"): + generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "tampered_nyc_report", + nyc_benchmark_manifest_path=manifests["nyc"], + ) + nyc_summary_path.write_bytes(original_nyc_summary) + + graph_manifest = json.loads(manifests["graph"].read_text(encoding="utf-8")) + mapping_entry = next( + entry + for entry in graph_manifest["inputs"] + if entry["role"] == "exposure_mapping" + ) + mapping_path = next( + parent / mapping_entry["path"] + for parent in manifests["graph"].parents + if (parent / mapping_entry["path"]).is_file() + ) + original_mapping = mapping_path.read_bytes() + mapping_path.write_bytes(original_mapping + b"\n") + with pytest.raises(ValueError, match="input manifest byte mismatch"): + generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "tampered_graph_report", + nyc_graph_benchmark_manifest_path=manifests["graph"], + ) + mapping_path.write_bytes(original_mapping) + + original_weather_manifest = manifests["weather"].read_bytes() + unsafe_weather = json.loads(original_weather_manifest) + unsafe_weather["causal_claim"] = True + manifests["weather"].write_text(json.dumps(unsafe_weather), encoding="utf-8") + with pytest.raises(ValueError, match="manifest checks did not all pass"): + generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "unsafe_weather_report", + nyc_weather_manifest_path=manifests["weather"], + ) + manifests["weather"].write_bytes(original_weather_manifest) + + original_equilibrium_manifest = manifests["equilibrium"].read_bytes() + unsafe_equilibrium = json.loads(original_equilibrium_manifest) + unsafe_equilibrium["is_nyc_structural_estimate"] = True + manifests["equilibrium"].write_text( + json.dumps(unsafe_equilibrium), encoding="utf-8" + ) + with pytest.raises(ValueError, match="manifest metadata is incompatible"): + generate_report_bundle( + benchmark_path, + output_directory=tmp_path / "unsafe_equilibrium_report", + equilibrium_manifest_path=manifests["equilibrium"], + ) + manifests["equilibrium"].write_bytes(original_equilibrium_manifest) diff --git a/CasualLab/tests/test_heterogeneity.py b/CasualLab/tests/test_heterogeneity.py new file mode 100644 index 0000000000000000000000000000000000000000..bc8962a3dcf77b46c673fc66be5756d869124840 --- /dev/null +++ b/CasualLab/tests/test_heterogeneity.py @@ -0,0 +1,40 @@ +import numpy as np +import pandas as pd + +from casuallab.heterogeneity import cross_fitted_s_learner, subgroup_effect_summary + + +def test_cross_fitted_s_learner_is_deterministic_and_complete() -> None: + rng = np.random.default_rng(17) + n = 240 + baseline = rng.normal(size=n) + treatment = rng.binomial(1, 0.5, size=n) + data = pd.DataFrame( + { + "unit_id": np.arange(n), + "baseline_demand": baseline, + "market_tightness": rng.uniform(size=n), + "hour_sin": rng.uniform(-1, 1, size=n), + "hour_cos": rng.uniform(-1, 1, size=n), + "assigned_treatment": treatment, + "outcome": 2.0 * baseline + treatment * (1.0 + baseline) + rng.normal(0, 0.2, n), + } + ) + first = cross_fitted_s_learner(data, folds=3, trees=20, min_samples_leaf=5, seed=4) + second = cross_fitted_s_learner(data, folds=3, trees=20, min_samples_leaf=5, seed=4) + pd.testing.assert_frame_equal(first.predictions, second.predictions) + assert first.predictions["estimated_cate"].notna().all() + assert set(first.predictions["crossfit_fold"]) == {0, 1, 2} + + +def test_subgroup_summary_uses_pretreatment_modifier_bins() -> None: + data = pd.DataFrame({"baseline_demand": np.arange(20, dtype=float)}) + summary = subgroup_effect_summary( + data, + 0.1 * data["baseline_demand"].to_numpy(), + modifier="baseline_demand", + bins=4, + ) + assert summary["rows"].sum() == 20 + assert summary["mean_estimated_cate"].is_monotonic_increasing + diff --git a/CasualLab/tests/test_interference.py b/CasualLab/tests/test_interference.py new file mode 100644 index 0000000000000000000000000000000000000000..f0b335e950b4259d056603e39517d28e84589752 --- /dev/null +++ b/CasualLab/tests/test_interference.py @@ -0,0 +1,191 @@ +import numpy as np +import pandas as pd +import pytest + +from casuallab.interference import ( + ExposureMappingConfig, + TwoStageSaturationConfig, + add_mapped_exposures, + estimate_exposure_response, + two_stage_saturation_assignment, +) + + +def _units(n_zones: int = 12, n_periods: int = 8) -> pd.DataFrame: + return pd.MultiIndex.from_product( + [range(n_periods), range(n_zones)], + names=["period_id", "zone_id"], + ).to_frame(index=False) + + +def _ring_edges(n_zones: int) -> pd.DataFrame: + return pd.DataFrame( + { + "focal_zone_id": np.arange(n_zones), + "neighbor_zone_id": np.roll(np.arange(n_zones), -1), + "weight": 1.0, + } + ) + + +def test_two_stage_saturation_is_deterministic_balanced_and_records_probabilities() -> None: + config = TwoStageSaturationConfig( + n_clusters=6, + individuals_per_cell=40, + saturation_levels=(0.0, 0.5, 1.0), + seed=91, + ) + first = two_stage_saturation_assignment(_units(), config) + second = two_stage_saturation_assignment(_units(), config) + pd.testing.assert_frame_equal(first, second) + + cluster_arms = first.groupby("cluster_id")["cluster_saturation"].nunique() + assert cluster_arms.eq(1).all() + assert ( + first[["cluster_id", "cluster_saturation"]] + .drop_duplicates()["cluster_saturation"] + .value_counts() + .sort_index() + .to_dict() + == {0.0: 2, 0.5: 2, 1.0: 2} + ) + assert set(first["saturation_assignment_probability"]) == {1 / 3} + assert first.loc[first["cluster_saturation"] == 0, "treated_units"].eq(0).all() + assert first.loc[first["cluster_saturation"] == 1, "treated_units"].eq(40).all() + assert first["assigned_treatment"].between(0, 1).all() + assert first["randomization_cluster"].nunique() == 6 + assert set(first["evidence_type"]) == {"randomized_design_assignment"} + + +def test_two_stage_saturation_config_rejects_unsupported_arm_geometry() -> None: + with pytest.raises(ValueError, match="number of saturation levels"): + TwoStageSaturationConfig(n_clusters=2, saturation_levels=(0.0, 0.5, 1.0)) + with pytest.raises(ValueError, match="sum to one"): + TwoStageSaturationConfig( + n_clusters=4, + saturation_levels=(0.0, 1.0), + saturation_probabilities=(0.2, 0.2), + ) + + +def test_mapped_exposure_uses_predeclared_neighbors_and_exact_time_lags() -> None: + assignments = _units(n_zones=4, n_periods=4) + assignments["treatment"] = ( + assignments["zone_id"] + assignments["period_id"] + ) % 2 + mapped = add_mapped_exposures( + assignments, + _ring_edges(4), + history_lags=1, + ) + + lookup = assignments.set_index(["zone_id", "period_id"])["treatment"] + for row in mapped.itertuples(index=False): + expected_neighbor = lookup.loc[((row.zone_id + 1) % 4, row.period_id)] + assert row.neighbor_exposure == expected_neighbor + if row.period_id == 0: + assert np.isnan(row.history_exposure) + assert row.history_support == 0 + else: + assert row.history_exposure == lookup.loc[(row.zone_id, row.period_id - 1)] + assert row.history_support == 1 + assert mapped["exposure_mapping_id"].nunique() == 1 + + +def test_unmapped_focal_zone_remains_unknown_not_zero() -> None: + assignments = _units(n_zones=3, n_periods=2) + assignments["treatment"] = 0.0 + edges = pd.DataFrame( + { + "focal_zone_id": [0, 1], + "neighbor_zone_id": [1, 2], + "weight": [1.0, 1.0], + } + ) + mapped = add_mapped_exposures(assignments, edges) + assert mapped.loc[mapped["zone_id"] == 2, "neighbor_exposure"].isna().all() + assert mapped.loc[mapped["zone_id"].isin([0, 1]), "neighbor_exposure"].eq(0).all() + + +def test_exposure_mapped_regression_recovers_own_neighbor_and_history_slopes() -> None: + assignment = two_stage_saturation_assignment( + _units(n_zones=12, n_periods=40), + TwoStageSaturationConfig( + n_clusters=12, + individuals_per_cell=80, + saturation_levels=(0.0, 0.35, 0.7, 1.0), + seed=81, + ), + ) + mapped = add_mapped_exposures(assignment, _ring_edges(12), history_lags=1) + mapped["baseline"] = np.sin(mapped["zone_id"]) + rng = np.random.default_rng(719) + mapped["outcome"] = ( + 4.0 + + 2.0 * mapped["treatment"] + + 1.5 * mapped["neighbor_exposure"] + + 0.7 * mapped["history_exposure"] + + 0.25 * mapped["baseline"] + + rng.normal(0.0, 0.03, len(mapped)) + ) + result = estimate_exposure_response( + mapped, + ExposureMappingConfig(covariates=("baseline",)), + ).set_index("exposure_term") + + assert result.loc["treatment", "estimate"] == pytest.approx(2.0, abs=0.05) + assert result.loc["neighbor_exposure", "estimate"] == pytest.approx(1.5, abs=0.05) + assert result.loc["history_exposure", "estimate"] == pytest.approx(0.7, abs=0.05) + assert result["inference_valid"].all() + assert set(result["target_estimand"]) == { + "controlled_zone_direct_effect", + "spillover_effect", + "controlled_history_exposure_response", + } + assert result["effect_scale"].str.contains("not the full-policy").all() + + +def test_exposure_estimator_rejects_collinear_own_and_neighbor_exposure() -> None: + frame = _units(n_zones=4, n_periods=4) + frame["treatment"] = np.tile([0.0, 1.0, 0.0, 1.0], 4) + frame["neighbor_exposure"] = frame["treatment"] + frame["outcome"] = frame["treatment"] + frame["randomization_cluster"] = "z_" + frame["zone_id"].astype(str) + with pytest.raises(ValueError, match="rank deficient"): + estimate_exposure_response( + frame, + ExposureMappingConfig(history_exposure=None), + ) + + +def test_exposure_estimator_fails_closed_when_configured_history_is_missing() -> None: + frame = _units(n_zones=4, n_periods=4) + frame["treatment"] = np.tile([0.0, 1.0, 0.0, 1.0], 4) + frame["neighbor_exposure"] = np.tile([1.0, 0.0, 1.0, 0.0], 4) + frame["outcome"] = frame["treatment"] + frame["randomization_cluster"] = "z_" + frame["zone_id"].astype(str) + + with pytest.raises(ValueError, match="missing configured history column"): + estimate_exposure_response(frame) + + +def test_exposure_estimator_rejects_mixed_mapping_versions() -> None: + assignment = two_stage_saturation_assignment( + _units(n_zones=8, n_periods=10), + TwoStageSaturationConfig( + n_clusters=8, + individuals_per_cell=20, + saturation_levels=(0.0, 0.5, 1.0), + seed=18, + ), + ) + frame = add_mapped_exposures(assignment, _ring_edges(8), history_lags=1) + frame["outcome"] = ( + 2.0 * frame["treatment"] + + frame["neighbor_exposure"] + + 0.5 * frame["history_exposure"] + ) + frame.loc[frame["period_id"] >= 5, "exposure_mapping_id"] = "second-map" + + with pytest.raises(ValueError, match="one predeclared exposure mapping"): + estimate_exposure_response(frame) diff --git a/CasualLab/tests/test_interference_benchmark.py b/CasualLab/tests/test_interference_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..f7c0a06b2a7f68dbb781166d34c3b29b1eddfebc --- /dev/null +++ b/CasualLab/tests/test_interference_benchmark.py @@ -0,0 +1,158 @@ +import numpy as np +import pandas as pd +import pytest + +from casuallab.interference_benchmark import ( + InterferenceBenchmarkConfig, + known_interference_estimands, + run_interference_benchmark, +) + + +@pytest.fixture(scope="module") +def benchmark_result(): + return run_interference_benchmark() + + +def test_known_estimands_keep_controlled_slopes_separate_from_market_total() -> None: + config = InterferenceBenchmarkConfig() + truth = known_interference_estimands(config) + + assert truth.controlled_zone_direct_effect == 2.0 + assert truth.spillover_effect == 1.5 + assert truth.controlled_history_exposure_response == 0.7 + assert truth.full_horizon_persistent_effect == pytest.approx(0.7 * 31 / 32) + assert truth.market_total_effect == pytest.approx(2.0 + 1.5 + 0.7 * 31 / 32) + assert truth.market_total_effect != truth.controlled_zone_direct_effect + + +def test_benchmark_is_deterministic_and_uses_two_stage_saturation() -> None: + config = InterferenceBenchmarkConfig( + replications=4, + n_zones=8, + n_clusters=8, + n_periods=12, + seed=901, + ) + first = run_interference_benchmark(config) + second = run_interference_benchmark(config) + + pd.testing.assert_frame_equal(first.records, second.records) + pd.testing.assert_frame_equal(first.summary, second.summary) + pd.testing.assert_frame_equal(first.fit_ledger, second.fit_ledger) + pd.testing.assert_frame_equal(first.failures, second.failures) + assert first.metadata == second.metadata + assert set(first.records["design"]) == {"two_stage_saturation"} + assert first.records["assignment_seed"].nunique() == config.replications + assert first.records["outcome_seed"].nunique() == config.replications + assert first.failures.empty + + +def test_mapped_benchmark_recovers_own_neighbor_and_history_truths( + benchmark_result, +) -> None: + mapped = benchmark_result.summary.loc[benchmark_result.summary["identified"]].set_index( + "target_estimand" + ) + + assert mapped.loc["controlled_zone_direct_effect", "mean_estimate"] == pytest.approx( + 2.0, abs=0.08 + ) + assert mapped.loc["spillover_effect", "mean_estimate"] == pytest.approx(1.5, abs=0.08) + assert mapped.loc[ + "controlled_history_exposure_response", "mean_estimate" + ] == pytest.approx(0.7, abs=0.08) + assert mapped["bias"].abs().lt(0.08).all() + assert mapped["inference_valid_for_target"].all() + assert mapped["controlled_exposure_not_market_total"].all() + assert set(mapped["evidence_type"]) == { + "semi_synthetic_exposure_mapped_known_truth_monte_carlo" + } + + mapped_records = benchmark_result.records.loc[ + benchmark_result.records["estimator"].eq("exposure_mapped_cluster_regression") + ] + assert mapped_records["coefficient_inference_cluster_aware"].all() + assert mapped_records["inference_valid_for_target"].all() + assert mapped_records["n_clusters"].eq(32).all() + assert mapped_records["variance_estimator"].eq("CR1 cluster-t").all() + assert set(mapped_records["target_estimand"]) == { + "controlled_zone_direct_effect", + "spillover_effect", + "controlled_history_exposure_response", + } + + +def test_naive_assignment_coefficient_is_an_honest_market_total_mismatch( + benchmark_result, +) -> None: + naive = benchmark_result.summary.loc[ + benchmark_result.summary["estimator"].eq("naive_assignment_cluster_regression") + ].iloc[0] + + assert naive["target_estimand"] == "market_total_effect" + assert not bool(naive["identified"]) + assert naive["comparison_status"] == "target_mismatch" + assert naive["diagnostic_mean_gap_to_market_total"] < -1.0 + assert np.isnan(naive["bias"]) + assert np.isnan(naive["rmse"]) + assert np.isnan(naive["coverage"]) + assert np.isnan(naive["power"]) + assert "withheld" in naive["withheld_reason"] + + naive_records = benchmark_result.records.loc[ + benchmark_result.records["estimator"].eq("naive_assignment_cluster_regression") + ] + assert naive_records["coefficient_inference_cluster_aware"].all() + assert naive_records["estimation_error"].isna().all() + assert naive_records["diagnostic_gap_to_market_total"].notna().all() + assert set(naive_records["evidence_type"]) == { + "semi_synthetic_assignment_diagnostic_target_mismatch" + } + + +def test_fit_ledger_is_complete_and_never_promotes_naive_target_mismatch( + benchmark_result, +) -> None: + ledger = benchmark_result.fit_ledger + assert len(ledger) == 4 + assert ledger["fit_complete"].all() + assert ledger["successful_fits"].eq(24).all() + assert ledger["failed_fits"].eq(0).all() + assert set(ledger["evidence_type"]) == {"semi_synthetic_benchmark_fit_ledger"} + + naive = ledger.loc[ledger["estimator"].eq("naive_assignment_cluster_regression")].iloc[0] + assert not bool(naive["identified"]) + assert not bool(naive["decision_eligible"]) + assert naive["target_inference_valid_rate"] == 0.0 + assert ledger.loc[ledger["identified"], "decision_eligible"].all() + + +def test_too_few_clusters_withholds_inferential_recovery_metrics() -> None: + result = run_interference_benchmark( + InterferenceBenchmarkConfig( + replications=4, + n_zones=6, + n_clusters=6, + n_periods=16, + minimum_inference_clusters=8, + seed=188, + ) + ) + mapped = result.summary.loc[result.summary["identified"]] + + assert not mapped["inference_valid_for_target"].any() + assert mapped["bias"].notna().all() + assert mapped["coverage"].isna().all() + assert mapped["power"].isna().all() + assert mapped["withheld_reason"].str.contains("below").all() + assert not result.fit_ledger["decision_eligible"].any() + + +def test_config_rejects_ambiguous_cluster_and_history_geometry() -> None: + with pytest.raises(ValueError, match="one randomized cluster per zone"): + InterferenceBenchmarkConfig(n_zones=8, n_clusters=4) + with pytest.raises(ValueError, match="history_lags"): + InterferenceBenchmarkConfig(history_lags=0) + with pytest.raises(ValueError, match="interior arm"): + InterferenceBenchmarkConfig(saturation_levels=(0.0, 1.0)) diff --git a/CasualLab/tests/test_marketplace_benchmark.py b/CasualLab/tests/test_marketplace_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..52e20085b776189e2ef158483c474f3e435c2f17 --- /dev/null +++ b/CasualLab/tests/test_marketplace_benchmark.py @@ -0,0 +1,588 @@ +import numpy as np +import pandas as pd +import pytest + +import casuallab.marketplace_benchmark as marketplace_module +from casuallab.benchmark import BenchmarkConfig +from casuallab.config import DesignConfig, DesignName, SimulationConfig, TreatmentVersion +from casuallab.estimators import estimate_effect as real_estimate_effect +from casuallab.marketplace_benchmark import ( + SensitivityScenario, + _applicable_methods, + _design_config, + _design_identification_flag, + _estimator_config, + _identification_reason, + _inference_assessment, + _scenario_simulation_config, + default_sensitivity_scenarios, + run_marketplace_benchmark, +) + + +def test_default_scenarios_form_spillover_persistence_factorial() -> None: + scenarios = default_sensitivity_scenarios( + SimulationConfig(spillover_strength=0.2, persistence=0.3) + ) + + by_name = {scenario.name: scenario for scenario in scenarios} + factorial_names = { + "no_interference", + "spillover_only", + "persistence_only", + "spillover_and_persistence", + } + assert factorial_names.issubset(by_name) + assert { + ( + by_name[name].spillover_strength > 0, + by_name[name].persistence > 0, + ) + for name in factorial_names + } == { + (False, False), + (True, False), + (False, True), + (True, True), + } + assert {scenario.varied_dimension for scenario in scenarios}.issuperset( + { + "treatment_duration", + "cluster_count", + "treatment_saturation", + "washout_periods", + "budget", + "treatment_version", + } + ) + assert by_name["treatment_duration_variant"].treatment_duration is not None + assert by_name["cluster_count_variant"].n_clusters is not None + assert by_name["partial_saturation"].treatment_saturation is not None + assert by_name["washout_variant"].washout_periods is not None + assert by_name["shared_budget_low"].budget is not None + assert by_name["rider_discount_only"].treatment_version is TreatmentVersion.RIDER_DISCOUNT + assert ( + by_name["driver_incentive_only"].treatment_version + is TreatmentVersion.DRIVER_INCENTIVE + ) + assert by_name["no_interference"].scenario_role == "reference" + assert by_name["spillover_only"].scenario_role == "mechanism_sensitivity" + assert by_name["partial_saturation"].scenario_role == "operational_sensitivity" + assert by_name["shared_budget_low"].scenario_role == "target_mismatch_diagnostic" + assert by_name["rider_discount_only"].scenario_role == "intervention_sensitivity" + + +def test_sensitivity_scenario_rejects_invalid_operating_overrides() -> None: + with pytest.raises(ValueError, match="shorter than treatment_duration"): + SensitivityScenario( + "bad_washout", + 0.0, + 0.0, + treatment_duration=2, + washout_periods=2, + ) + with pytest.raises(ValueError, match="treatment_saturation"): + SensitivityScenario("bad_saturation", 0.0, 0.0, treatment_saturation=0.0) + with pytest.raises(ValueError, match="budget"): + SensitivityScenario("bad_budget", 0.0, 0.0, budget=-1.0) + with pytest.raises(ValueError, match="unknown treatment version"): + SensitivityScenario("bad_version", 0.0, 0.0, treatment_version="mystery") + + +def test_treatment_version_scenario_changes_the_intervention_without_changing_base() -> None: + base = SimulationConfig(treatment_version="bundled") + scenario = SensitivityScenario( + "rider_only", + 0.0, + 0.0, + treatment_version="rider_discount", + varied_dimension="treatment_version", + ) + configured = _scenario_simulation_config(base, scenario, n_zones=4, seed=99) + + assert base.treatment_version is TreatmentVersion.BUNDLED + assert configured.treatment_version is TreatmentVersion.RIDER_DISCOUNT + assert configured.seed == 99 + + +def test_benchmark_fails_closed_for_unsupported_estimator_target() -> None: + with pytest.raises(ValueError, match="supports only market_total_effect"): + run_marketplace_benchmark( + BenchmarkConfig( + replications=2, + designs=("geo_cluster",), + estimators=("cluster_robust",), + target_estimand="cumulative_effect", + ), + SimulationConfig(n_periods=8), + ) + + +def test_method_compatibility_uses_known_dr_propensity_and_excludes_temporal_did() -> None: + requested = ("difference_in_differences", "doubly_robust") + assert "difference_in_differences" not in _applicable_methods(DesignName.SWITCHBACK, requested) + assert "difference_in_differences" not in _applicable_methods(DesignName.TIME_BLOCK, requested) + assert "difference_in_differences" in _applicable_methods(DesignName.GEO_TIME, requested) + assert "two_way_cluster_robust" in _applicable_methods( + DesignName.GEO_TIME, + ("two_way_cluster_robust",), + ) + assert "two_way_cluster_robust" not in _applicable_methods( + DesignName.GEO_CLUSTER, + ("two_way_cluster_robust",), + ) + config = _estimator_config( + "doubly_robust", + DesignName.GEO_CLUSTER, + "market_total_effect", + seed=9, + ) + assert config.propensity == "treatment_probability" + assert config.filter_eligible is False + assert not _estimator_config( + "cluster_robust", + DesignName.SWITCHBACK, + "persistent_effect", + seed=9, + ).filter_eligible + two_way = _estimator_config( + "two_way_cluster_robust", + DesignName.GEO_TIME, + "market_total_effect", + seed=9, + ) + assert two_way.cluster == "cluster_id" + assert two_way.time == "time_block" + + +def test_two_way_geo_time_inference_requires_enough_groups_in_both_dimensions() -> None: + valid, scope = _inference_assessment( + "two_way_cluster_robust", + DesignName.GEO_TIME, + 96, + n_geographic_clusters=8, + n_time_clusters=12, + ) + assert valid + assert "two-way" in scope + invalid, warning = _inference_assessment( + "two_way_cluster_robust", + DesignName.GEO_TIME, + 48, + n_geographic_clusters=4, + n_time_clusters=12, + ) + assert not invalid + assert "below" in warning + assert not _inference_assessment("doubly_robust", DesignName.GEO_TIME, 20)[0] + assert not _inference_assessment("cluster_robust", DesignName.GEO_TIME, 20)[0] + assert not _inference_assessment("cluster_robust", DesignName.GEO_CLUSTER, 4)[0] + assert _inference_assessment("cluster_robust", DesignName.GEO_CLUSTER, 8)[0] + + +def test_two_way_uncertainty_does_not_promote_unmodeled_exposure_to_market_total() -> None: + scenario = SensitivityScenario( + "spatial_and_temporal_exposure", + spillover_strength=0.3, + persistence=0.4, + ) + inference_valid, _ = _inference_assessment( + "two_way_cluster_robust", + DesignName.GEO_TIME, + 64, + n_geographic_clusters=8, + n_time_clusters=8, + ) + + assert inference_valid + assert not _design_identification_flag( + DesignName.GEO_TIME, + "market_total_effect", + scenario, + ) + assert "unmodeled spatial or temporal exposure" in _identification_reason( + DesignName.GEO_TIME, + "market_total_effect", + scenario, + ) + + +def test_benchmark_design_protocol_honors_configured_duration_and_washout() -> None: + simulation = SimulationConfig(design=DesignConfig(treatment_duration=3, washout_periods=2)) + + temporal = _design_config(DesignName.SWITCHBACK, simulation, seed=8) + geographic = _design_config(DesignName.GEO_CLUSTER, simulation, seed=8) + + assert temporal.treatment_duration == 3 + assert temporal.washout_periods == 2 + assert geographic.treatment_duration == 3 + assert geographic.washout_periods == 0 + + +def test_end_to_end_benchmark_is_deterministic_and_labels_target_mismatch() -> None: + benchmark = BenchmarkConfig( + replications=2, + seed=33, + designs=("individual", "geo_cluster", "switchback"), + estimators=("difference_in_means", "regression_adjustment", "cluster_robust"), + target_estimand="market_total_effect", + ) + simulation = SimulationConfig( + n_zones=4, + n_periods=24, + seed=8, + budget=None, + design=DesignConfig(treatment_duration=4), + ) + scenarios = (SensitivityScenario("none", 0.0, 0.0),) + first = run_marketplace_benchmark(benchmark, simulation, scenarios=scenarios) + second = run_marketplace_benchmark(benchmark, simulation, scenarios=scenarios) + pd.testing.assert_frame_equal(first.records, second.records) + pd.testing.assert_frame_equal(first.summary, second.summary) + pd.testing.assert_frame_equal(first.fit_ledger, second.fit_ledger) + assert len(first.summary) > 0 + assert not first.summary.loc[first.summary["design"] == "individual", "identified"].any() + assert first.summary.loc[first.summary["design"] == "geo_cluster", "identified"].all() + assert set(first.summary["evidence_type"]) == {"semi_synthetic_causal_monte_carlo"} + assert (first.records.groupby(["scenario", "replication"])["seed"].nunique() == 1).all() + assert (first.fit_ledger["attempted_fits"] == 2).all() + assert ( + first.fit_ledger["successful_fits"] + first.fit_ledger["failed_fits"] + == first.fit_ledger["attempted_fits"] + ).all() + assert first.fit_ledger["fit_complete"].all() + assert "normalized_precision_cost" in first.summary + assert "information_cost" not in first.summary + assert first.summary["budget"].isna().all() + assert "n_clusters" not in first.summary + assert not first.summary["operational_cost_included"].any() + assert first.summary["measurement_cost_basis"].str.contains("excludes").all() + threshold = float(first.summary["nonbinding_budget_threshold"].iloc[0]) + assert np.isfinite(threshold) + assert first.summary["nonbinding_budget_threshold"].eq(threshold).all() + assert first.records["nonbinding_budget_threshold"].eq(threshold).all() + assert threshold >= first.records["full_policy_spend"].max() + assert threshold >= first.records["realized_schedule_spend"].max() + assert first.summary["incentive_per_driver"].eq(simulation.incentive_per_driver).all() + assert first.summary["treatment_version"].eq("bundled").all() + assert first.summary["declared_scenario_set"].eq('["none"]').all() + assert first.records["declared_scenario_set"].eq('["none"]').all() + + +def test_geo_time_two_way_cluster_runs_end_to_end_with_valid_dimensions() -> None: + result = run_marketplace_benchmark( + BenchmarkConfig( + replications=2, + seed=39, + designs=("geo_time",), + estimators=("two_way_cluster_robust",), + target_estimand="market_total_effect", + ), + SimulationConfig( + n_periods=32, + budget=None, + design=DesignConfig( + n_clusters=8, + treatment_duration=4, + washout_periods=0, + ), + ), + scenarios=(SensitivityScenario("none", 0.0, 0.0),), + ) + + assert result.failures.empty + assert len(result.records) == 2 + row = result.summary.iloc[0] + assert row["estimator"] == "two_way_cluster_robust" + assert row["inference_geographic_clusters"] == 8 + assert row["inference_time_clusters"] == 8 + assert row["inference_valid"] + assert row["fit_complete"] + assert np.isfinite(row["mean_estimate"]) + assert np.isfinite(row["mean_std_error"]) + + +def test_benchmark_honors_and_records_assignment_probability_and_geo_clusters() -> None: + result = run_marketplace_benchmark( + BenchmarkConfig( + replications=2, + seed=7, + designs=("geo_cluster",), + estimators=("cluster_robust",), + ), + SimulationConfig( + n_periods=24, + design=DesignConfig( + treatment_probability=0.35, + n_clusters=3, + treatment_duration=4, + ), + ), + scenarios=(SensitivityScenario("none", 0.0, 0.0),), + ) + + assert np.isclose(result.summary.iloc[0]["treatment_probability"], 0.35) + assert np.isclose(result.summary.iloc[0]["mean_assignment_propensity"], 1.0 / 3.0) + assert result.summary.iloc[0]["configured_geo_clusters"] == 3 + assert result.summary.iloc[0]["n_zones"] == 6 + assert result.summary.iloc[0]["cluster_size"] == 2 + assert result.summary.iloc[0]["cluster_semantics"] == "geographic assignment clusters" + assert not result.summary.iloc[0]["inference_valid"] + assert result.summary.iloc[0]["minimum_inference_clusters"] == 8 + + +def test_operating_sensitivity_overrides_are_recorded_and_budget_is_target_mismatch() -> None: + scenario = SensitivityScenario( + "joint_operating_check", + 0.0, + 0.0, + treatment_duration=6, + n_clusters=8, + treatment_saturation=0.4, + washout_periods=2, + budget=100.0, + varied_dimension="test_joint_override", + ) + result = run_marketplace_benchmark( + BenchmarkConfig( + replications=2, + seed=17, + designs=("geo_cluster", "switchback"), + estimators=("difference_in_means",), + ), + SimulationConfig(n_periods=24, budget=5000.0), + scenarios=(scenario,), + ) + + summary = result.summary.set_index("design") + assert summary["varied_dimension"].eq("test_joint_override").all() + assert summary["scenario_role"].eq("target_mismatch_diagnostic").all() + assert summary["treatment_duration"].eq(6).all() + assert summary["treatment_saturation"].eq(0.4).all() + assert summary["budget"].eq(100.0).all() + assert summary["n_zones"].eq(16).all() + assert summary.loc["geo_cluster", "configured_geo_clusters"] == 8 + assert np.isnan(summary.loc["switchback", "configured_geo_clusters"]) + assert summary.loc["geo_cluster", "washout_periods"] == 0 + assert summary.loc["switchback", "washout_periods"] == 2 + assert not bool(summary.loc["geo_cluster", "inference_valid"]) + assert not summary["identified"].any() + assert summary["identification_scope"].str.contains("shared-budget").all() + assert summary["comparison_status"].eq("target_mismatch").all() + assert summary["budget_binding_rate"].eq(1.0).all() + assert result.records["budget_binding"].all() + assert result.fit_ledger["declared_scenario_count"].eq(1).all() + + +def test_cluster_count_cell_supplies_eight_cluster_geometry_and_valid_inference() -> None: + simulation = SimulationConfig( + n_periods=24, + design=DesignConfig(n_clusters=2, treatment_duration=4), + ) + cluster_scenario = next( + scenario + for scenario in default_sensitivity_scenarios(simulation) + if scenario.varied_dimension == "cluster_count" + ) + result = run_marketplace_benchmark( + BenchmarkConfig( + replications=2, + seed=91, + designs=("geo_cluster",), + estimators=("cluster_robust",), + ), + simulation, + scenarios=(cluster_scenario,), + ) + + row = result.summary.iloc[0] + assert row["configured_geo_clusters"] == 8 + assert row["n_zones"] == 16 + assert row["cluster_size"] == 2 + assert row["inference_clusters"] == 8 + assert row["inference_valid"] + + +def test_capped_runs_cannot_self_certify_a_nonbinding_budget_threshold() -> None: + result = run_marketplace_benchmark( + BenchmarkConfig( + replications=2, + seed=92, + designs=("geo_cluster",), + estimators=("difference_in_means",), + ), + SimulationConfig(n_periods=12), + scenarios=(SensitivityScenario("only_capped", 0.0, 0.0, budget=1.0),), + ) + + assert result.summary["nonbinding_budget_threshold"].isna().all() + assert result.records["nonbinding_budget_threshold"].isna().all() + + +def test_impossible_group_crossfit_is_predeclared_not_counted_as_fit_failure() -> None: + result = run_marketplace_benchmark( + BenchmarkConfig( + replications=2, + seed=93, + designs=("geo_cluster",), + estimators=("doubly_robust",), + ), + SimulationConfig(n_periods=12, design=DesignConfig(n_clusters=2)), + scenarios=(SensitivityScenario("two_clusters", 0.0, 0.0),), + ) + + row = result.fit_ledger.iloc[0] + assert not row["applicable"] + assert row["attempted_fits"] == 0 + assert row["successful_fits"] == 0 + assert row["failed_fits"] == 0 + assert row["fit_complete"] + assert "two" in row["applicability_reason"] + assert result.records.empty + assert result.failures.empty + + imbalanced = run_marketplace_benchmark( + BenchmarkConfig( + replications=2, + seed=94, + designs=("geo_cluster",), + estimators=("doubly_robust",), + ), + SimulationConfig( + n_periods=12, + design=DesignConfig(n_clusters=8, treatment_probability=0.1), + ), + scenarios=(SensitivityScenario("imbalanced_arms", 0.0, 0.0),), + ) + imbalanced_row = imbalanced.fit_ledger.iloc[0] + assert not imbalanced_row["applicable"] + assert imbalanced_row["attempted_fits"] == 0 + assert "each arm" in imbalanced_row["applicability_reason"] + + +def test_benchmark_rejects_duplicate_or_empty_declared_scenario_plans() -> None: + benchmark = BenchmarkConfig( + replications=2, + designs=("geo_cluster",), + estimators=("difference_in_means",), + ) + simulation = SimulationConfig(n_periods=8) + duplicate = SensitivityScenario("duplicate", 0.0, 0.0) + + with pytest.raises(ValueError, match="at least one sensitivity scenario"): + run_marketplace_benchmark(benchmark, simulation, scenarios=()) + with pytest.raises(ValueError, match="names must be unique"): + run_marketplace_benchmark( + benchmark, + simulation, + scenarios=(duplicate, duplicate), + ) + + +def test_spillover_scenario_is_generated_not_hard_coded() -> None: + benchmark = BenchmarkConfig( + replications=2, + seed=19, + designs=("geo_cluster",), + estimators=("difference_in_means", "regression_adjustment"), + ) + simulation = SimulationConfig(n_periods=24, budget=None) + result = run_marketplace_benchmark( + benchmark, + simulation, + scenarios=( + SensitivityScenario("none", 0.0, 0.0), + SensitivityScenario("spillover", 0.45, 0.0), + ), + ) + assert set(result.records["scenario"]) == {"none", "spillover"} + assert result.records.groupby("replication")["seed"].nunique().eq(1).all() + scenario_truth = result.records.groupby("scenario")["truth"].mean() + assert scenario_truth["spillover"] != scenario_truth["none"] + assert not result.records.loc[result.records["scenario"] == "spillover", "identified"].any() + + +def test_no_interference_cluster_estimator_recovers_truth_with_mc_uncertainty() -> None: + benchmark = BenchmarkConfig( + replications=40, + seed=123, + designs=("geo_cluster",), + estimators=("cluster_robust",), + ) + result = run_marketplace_benchmark( + benchmark, + SimulationConfig( + n_periods=24, + budget=None, + design=DesignConfig(n_clusters=8), + ), + scenarios=(SensitivityScenario("none", 0.0, 0.0),), + ) + row = result.summary.iloc[0] + assert abs(row["bias"]) <= 3.0 * row["bias_mcse"] + assert row["coverage"] >= 0.80 + + +def test_naive_cluster_estimator_misses_full_policy_target_under_spillover() -> None: + benchmark = BenchmarkConfig( + replications=30, + seed=321, + designs=("geo_cluster",), + estimators=("cluster_robust",), + ) + result = run_marketplace_benchmark( + benchmark, + SimulationConfig(n_periods=24, budget=None), + scenarios=(SensitivityScenario("spillover", 0.45, 0.0),), + ) + row = result.summary.iloc[0] + assert not row["identified"] + assert np.isnan(row["bias"]) + assert abs(row["diagnostic_mean_gap"]) > 5.0 * row["diagnostic_gap_mcse"] + assert row["comparison_status"] == "target_mismatch" + + +def test_fit_failures_remain_in_ledger_and_make_candidate_incomplete(monkeypatch) -> None: + calls = 0 + + def fail_once(panel, config): + nonlocal calls + calls += 1 + if calls == 1: + raise ValueError("deliberate fit failure") + return real_estimate_effect(panel, config) + + monkeypatch.setattr(marketplace_module, "estimate_effect", fail_once) + result = run_marketplace_benchmark( + BenchmarkConfig( + replications=3, + seed=17, + designs=("geo_cluster",), + estimators=("cluster_robust",), + ), + SimulationConfig(n_periods=24, budget=None), + scenarios=(SensitivityScenario("none", 0.0, 0.0),), + ) + + ledger = result.fit_ledger.iloc[0] + assert ledger["attempted_fits"] == 3 + assert ledger["successful_fits"] == 2 + assert ledger["failed_fits"] == 1 + assert not ledger["fit_complete"] + assert not result.summary.iloc[0]["fit_complete"] + assert result.failures.iloc[0]["stage"] == "estimation" + + +def test_unavailable_individual_truth_target_fails_before_fitting() -> None: + with pytest.raises(ValueError, match="supports only market_total_effect"): + run_marketplace_benchmark( + BenchmarkConfig( + replications=2, + seed=27, + designs=("individual",), + estimators=("regression_adjustment",), + target_estimand="direct_effect", + ), + SimulationConfig(n_periods=12, budget=None), + scenarios=(SensitivityScenario("none", 0.0, 0.0),), + ) diff --git a/CasualLab/tests/test_marketplace_policy.py b/CasualLab/tests/test_marketplace_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..26d8c577a5cea4a395e2c3fe161558c81f244519 --- /dev/null +++ b/CasualLab/tests/test_marketplace_policy.py @@ -0,0 +1,215 @@ +from __future__ import annotations + +import json + +import numpy as np +import pandas as pd +import pytest + +from casuallab.config import DesignConfig, SimulationConfig, TreatmentVersion +from casuallab.marketplace_policy import ( + MarketplacePolicyConfig, + _pretreatment_planning_cost, + _random_full_budget_plan, + _ranked_full_budget_plan, + run_marketplace_policy_benchmark, + run_marketplace_policy_evaluation, + run_treatment_version_policy_evaluation, +) +from casuallab.simulator import simulate_market + + +def _simulation(**overrides: object) -> SimulationConfig: + values: dict[str, object] = { + "n_zones": 4, + "n_periods": 16, + "spillover_strength": 0.15, + "persistence": 0.20, + "seed": 31, + "design": DesignConfig(name="geo_cluster", n_clusters=4, seed=32), + } + values.update(overrides) + return SimulationConfig(**values) + + +def _policy() -> MarketplacePolicyConfig: + return MarketplacePolicyConfig( + budget=500.0, + model_trees=12, + model_replicates=2, + seed=71, + ) + + +def test_marketplace_policy_is_deterministic_budget_feasible_and_honest() -> None: + first = run_marketplace_policy_benchmark( + _simulation(), + _policy(), + n_train_markets=3, + n_holdout_markets=2, + ) + second = run_marketplace_policy_benchmark( + _simulation(), + _policy(), + n_train_markets=3, + n_holdout_markets=2, + ) + pd.testing.assert_frame_equal(first, second) + assert set(first["policy"]) == { + "no_treatment", + "random", + "uniform", + "rule_based", + "model_based", + } + assert first["budget_feasible"].all() + assert first["evaluation_complete"].all() + assert first["policy_eligible"].all() + assert ( + first.loc[first["policy"] != "no_treatment", "budget_spent"] + <= _policy().budget + 1e-6 + ).all() + assert first.loc[first["policy"] == "no_treatment", "budget_spent"].item() == 0.0 + assert pd.isna( + first.loc[first["policy"] == "no_treatment", "budget_efficiency"].item() + ) + assert first["training_signal"].str.contains("no structural truth").all() + assert first["planning_cost_basis"].str.contains("no treated holdout").all() + train_seeds = set(json.loads(first.iloc[0]["training_market_seeds"])) + holdout_seeds = set(json.loads(first.iloc[0]["holdout_market_seeds"])) + assert train_seeds.isdisjoint(holdout_seeds) + assert first["evaluation_engine"].str.contains("simulator rerun").all() + assert set(first["target_estimand"]) == {"full_horizon_incremental_trips"} + indexed = first.set_index("policy") + assert indexed.loc["uniform", "treated_cell_share"] == pytest.approx(1.0) + assert ( + indexed.loc[ + ["random", "rule_based", "model_based"], + "treated_cell_share", + ] + < 1.0 + ).all() + assert first["expected_incremental_outcome"].nunique() == len(first) + + detailed = run_marketplace_policy_evaluation( + _simulation(), + _policy(), + n_train_markets=3, + n_holdout_markets=2, + ) + assert len(detailed.market_results) == 5 * 2 + assert detailed.market_results.groupby("holdout_market_seed")["policy"].nunique().eq(5).all() + assert ( + detailed.market_results.groupby("holdout_market_seed")["incremental_trips"] + .nunique() + .eq(5) + .all() + ) + assert "paired_incremental_outcome_vs_random" in detailed.market_results + + +def test_policy_values_are_recomputed_when_market_interference_changes() -> None: + no_interference = run_marketplace_policy_benchmark( + _simulation( + spillover_strength=0.0, + persistence=0.0, + rider_substitution=0.0, + driver_mobility=0.0, + ), + _policy(), + n_train_markets=3, + n_holdout_markets=2, + ) + interference = run_marketplace_policy_benchmark( + _simulation(spillover_strength=0.4, persistence=0.5), + _policy(), + n_train_markets=3, + n_holdout_markets=2, + ) + merged = no_interference.merge(interference, on="policy", suffixes=("_none", "_active")) + nonzero = merged["policy"] != "no_treatment" + assert ( + merged.loc[nonzero, "expected_incremental_outcome_none"] + != merged.loc[nonzero, "expected_incremental_outcome_active"] + ).any() + + +def test_policy_config_rejects_unknown_or_invalid_values() -> None: + with pytest.raises(ValueError, match="unknown marketplace policy keys"): + MarketplacePolicyConfig.from_mapping({"budegt": 100.0}) + with pytest.raises(ValueError, match="budget must be positive"): + MarketplacePolicyConfig(budget=0.0) + + +def test_planning_cost_respects_selected_treatment_version() -> None: + rider_config = _simulation(treatment_version=TreatmentVersion.RIDER_DISCOUNT) + driver_config = _simulation(treatment_version=TreatmentVersion.DRIVER_INCENTIVE) + bundled_config = _simulation(treatment_version=TreatmentVersion.BUNDLED) + rider_control = simulate_market(rider_config) + driver_control = simulate_market(driver_config) + bundled_control = simulate_market(bundled_config) + + rider_cost = _pretreatment_planning_cost(rider_control, rider_config) + driver_cost = _pretreatment_planning_cost(driver_control, driver_config) + bundled_cost = _pretreatment_planning_cost(bundled_control, bundled_config) + assert (rider_cost > 0).all() + assert (driver_cost > 0).all() + assert (bundled_cost > 0).all() + assert bundled_cost == pytest.approx(rider_cost + driver_cost) + + +def test_ranked_policy_never_spends_on_nonpositive_scores() -> None: + allocation = _ranked_full_budget_plan( + np.array([3.0, 0.0, -2.0]), + np.ones(3), + budget=100.0, + ) + assert allocation.tolist() == [1.0, 0.0, 0.0] + + +def test_random_policy_uses_a_cost_independent_random_order() -> None: + planning_cost = np.array([4.0, 1.0, 3.0, 2.0]) + budget = 4.0 + seed = 13 + order = np.random.default_rng(seed).permutation(len(planning_cost)) + expected = np.zeros(len(planning_cost)) + cumulative = 0.0 + for index in order: + expected[index] = 1.0 + cumulative += planning_cost[index] + if cumulative >= 1.10 * budget: + break + + actual = _random_full_budget_plan(planning_cost, budget, random_seed=seed) + assert actual.tolist() == expected.tolist() + + +def test_policy_evaluation_pairs_markets_across_treatment_versions() -> None: + result = run_treatment_version_policy_evaluation( + _simulation(n_periods=8), + _policy(), + n_train_markets=2, + n_holdout_markets=2, + ) + assert set(result.summary["treatment_version"]) == { + "rider_discount", + "driver_incentive", + "bundled", + } + assert len(result.summary) == 3 * 5 + assert len(result.market_results) == 3 * 5 * 2 + assert result.summary.groupby("treatment_version")["policy"].nunique().eq(5).all() + assert result.summary["training_market_seeds"].nunique() == 1 + assert result.summary["holdout_market_seeds"].nunique() == 1 + assert result.summary["version_evidence_scope"].str.contains("not an empirical").all() + nonzero = result.summary.loc[result.summary["policy"] != "no_treatment"] + assert nonzero.groupby("policy")["expected_incremental_outcome"].nunique().gt(1).any() + + with pytest.raises(ValueError, match="must be unique"): + run_treatment_version_policy_evaluation( + _simulation(n_periods=8), + _policy(), + treatment_versions=("bundled", "bundled"), + n_train_markets=2, + n_holdout_markets=2, + ) diff --git a/CasualLab/tests/test_nyc_benchmark.py b/CasualLab/tests/test_nyc_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..e542318b45d1979f21d175989a1987e3588d71d5 --- /dev/null +++ b/CasualLab/tests/test_nyc_benchmark.py @@ -0,0 +1,421 @@ +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest +import yaml +from test_nyc_simulation import write_nyc_calibration_test_bundle + +import casuallab.nyc_benchmark as nyc_benchmark_module +from casuallab.config import DesignConfig, SimulationConfig +from casuallab.data import sha256_file +from casuallab.nyc_benchmark import ( + NYC_BENCHMARK_EVIDENCE_TYPE, + NYCBenchmarkConfig, + run_nyc_informed_marketplace_benchmark, + validate_nyc_benchmark_anchor, + write_nyc_benchmark_artifacts, +) +from casuallab.nyc_simulation import ( + CAUSAL_ASSUMPTION_FIELDS, + NYCSimulationAnchorSettings, + build_nyc_simulation_anchor, +) + + +def _write_json(path: Path, value: object) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + json.dumps(value, indent=2, sort_keys=True, allow_nan=False) + "\n", + encoding="utf-8", + ) + + +def _entry(path: Path, root: Path) -> dict[str, object]: + return { + "path": str(path.relative_to(root)), + "bytes": path.stat().st_size, + "sha256": sha256_file(path), + } + + +def _verified_anchor_artifacts(tmp_path: Path) -> dict[str, object]: + calibration_bundle = write_nyc_calibration_test_bundle(tmp_path) + calibration_path = calibration_bundle["calibration"] + calibration = json.loads(calibration_path.read_text(encoding="utf-8")) + zones = 16 + periods = 744 + panel_cells = zones * periods + trips = panel_cells * 5 + calibration["conservation"].update( + { + "raw_rows_declared": trips, + "clean_rows": trips, + "zone_trip_sum": trips, + "od_trip_sum": trips, + "zones": zones, + "periods": periods, + "zone_rows": panel_cells, + } + ) + calibration["trip_level_descriptive_moments"]["trip_rows"] = trips + calibration["zone_hour_variance_decomposition"].update( + { + "zones": zones, + "periods": periods, + "panel_cells": panel_cells, + "occupied_cells": panel_cells - 4, + "total_completed_trips": trips, + "mean_completed_trips_per_zone_hour": 5.0, + } + ) + _write_json(calibration_path, calibration) + calibration_manifest_path = calibration_bundle["bundle_manifest"] + calibration_manifest = json.loads( + calibration_manifest_path.read_text(encoding="utf-8") + ) + for index, entry in enumerate(calibration_manifest["files"]): + if entry["path"] == "calibration.json": + calibration_manifest["files"][index] = _entry( + calibration_path, calibration_path.parent + ) + _write_json(calibration_manifest_path, calibration_manifest) + + template = SimulationConfig( + n_zones=4, + n_periods=48, + spillover_strength=0.15, + persistence=0.25, + budget=5000.0, + seed=202503, + design=DesignConfig( + n_clusters=2, + treatment_duration=4, + budget=5000.0, + seed=202503, + ), + ) + template_path = tmp_path / "configs" / "simulation.yaml" + template_path.parent.mkdir(parents=True) + template_path.write_text( + yaml.safe_dump({"simulation": template.to_dict()}, sort_keys=False), + encoding="utf-8", + ) + anchor = build_nyc_simulation_anchor( + calibration_path, + project_root=tmp_path, + manifest_path=calibration_manifest_path, + settings=NYCSimulationAnchorSettings( + target_n_zones=16, + target_n_periods=48, + seed=202503, + ), + assumption_template=template, + ) + anchor_path = tmp_path / "artifacts" / "simulation_anchor" / "anchor.json" + _write_json(anchor_path, anchor) + anchor_manifest_path = anchor_path.with_name("manifest.json") + _write_json( + anchor_manifest_path, + { + "files": [ + _entry(calibration_path, tmp_path), + _entry(calibration_manifest_path, tmp_path), + _entry(anchor_path, tmp_path), + _entry(template_path, tmp_path), + ], + "metadata": { + "evidence_label": anchor["evidence_label"], + "causal_claim": False, + "status": anchor["status"], + "calibration_sha256": sha256_file(calibration_path), + "calibration_manifest_sha256": sha256_file( + calibration_manifest_path + ), + "simulation_config_sha256": sha256_file(template_path), + "source_data_manifest_sha256": anchor["integrity"][ + "source_data_manifest_sha256" + ], + }, + }, + ) + return { + "root": tmp_path, + "anchor": anchor, + "anchor_path": anchor_path, + "anchor_manifest_path": anchor_manifest_path, + "template": template, + } + + +def _laptop_config() -> NYCBenchmarkConfig: + return NYCBenchmarkConfig( + replications=2, + seed=7701, + n_zones=16, + n_periods=32, + max_planned_fits=64, + ) + + +def test_nyc_benchmark_is_deterministic_and_passes_known_truth_target_gates( + tmp_path: Path, +) -> None: + artifacts = _verified_anchor_artifacts(tmp_path) + kwargs = { + "config": _laptop_config(), + "project_root": tmp_path, + } + first = run_nyc_informed_marketplace_benchmark( + artifacts["anchor_path"], artifacts["anchor_manifest_path"], **kwargs + ) + second = run_nyc_informed_marketplace_benchmark( + artifacts["anchor_path"], artifacts["anchor_manifest_path"], **kwargs + ) + + pd.testing.assert_frame_equal(first.records, second.records) + pd.testing.assert_frame_equal(first.summary, second.summary) + pd.testing.assert_frame_equal(first.failures, second.failures) + pd.testing.assert_frame_equal(first.fit_ledger, second.fit_ledger) + assert first.metadata == second.metadata + json.dumps(first.metadata, allow_nan=False) + assert first.metadata["anchor"]["anchor_path"] == str( + Path(artifacts["anchor_path"]).relative_to(tmp_path) + ) + assert first.metadata["anchor"]["anchor_manifest_path"] == str( + Path(artifacts["anchor_manifest_path"]).relative_to(tmp_path) + ) + assert first.failures.empty + assert first.metadata["target_gates"]["all_passed"] is True + assert all(first.metadata["target_gates"].values()) + assert set(first.records["evidence_type"]) == {NYC_BENCHMARK_EVIDENCE_TYPE} + assert set(first.summary["evidence_type"]) == {NYC_BENCHMARK_EVIDENCE_TYPE} + assert first.records["nyc_empirical_causal_effect"].eq(False).all() + assert first.records["simulator_known_truth"].all() + assert np.isfinite(first.records["truth"]).all() + assert first.records["target_estimand"].eq("market_total_effect").all() + assert first.records["n_zones"].eq(16).all() + assert first.records["n_periods"].eq(32).all() + assert first.summary.loc[ + first.summary["identified"].astype(bool), "rmse" + ].notna().all() + assert first.summary.loc[ + ~first.summary["identified"].astype(bool), + ["bias", "rmse", "coverage", "power"], + ].isna().all().all() + assert ( + first.summary["identified"].astype(bool) + & first.summary["inference_valid"].astype(bool) + ).any() + + +def test_causal_assumptions_remain_explicit_and_are_never_labeled_nyc_effects( + tmp_path: Path, +) -> None: + artifacts = _verified_anchor_artifacts(tmp_path) + result = run_nyc_informed_marketplace_benchmark( + artifacts["anchor_path"], + artifacts["anchor_manifest_path"], + project_root=tmp_path, + config=_laptop_config(), + ) + anchor_config = result.metadata["anchor"]["simulation_config"] + base_config = result.metadata["benchmark_base_simulation_config"] + for field in CAUSAL_ASSUMPTION_FIELDS: + assert base_config[field] == anchor_config[field] + scenarios = result.metadata["scenario_causal_provenance"] + assert scenarios["anchor_explicit_assumptions"][ + "anchor_causal_assumptions_preserved" + ] is True + reference_overrides = scenarios["no_interference_no_carryover"][ + "causal_overrides" + ] + assert set(reference_overrides) == { + "spillover_strength", + "persistence", + "rider_substitution", + "driver_mobility", + } + assert result.metadata["nyc_empirical_causal_effect"] is False + assert result.metadata["simulator_known_truth"] is True + assert "not an NYC causal estimate" in result.metadata["known_truth_scope"] + assert result.metadata["effective_overrides"]["n_periods"]["effective"] == 32 + assert result.metadata["effective_overrides"]["budget"]["effective"] is None + + +def test_anchor_file_tampering_is_rejected_by_manifest_hash(tmp_path: Path) -> None: + artifacts = _verified_anchor_artifacts(tmp_path) + anchor_path = artifacts["anchor_path"] + original = anchor_path.read_text(encoding="utf-8") + tampered = original.replace('"base_fare": 20.0', '"base_fare": 21.0', 1) + assert tampered != original + assert len(tampered.encode()) == len(original.encode()) + anchor_path.write_text(tampered, encoding="utf-8") + + with pytest.raises(ValueError, match="anchor manifest SHA-256 mismatch"): + validate_nyc_benchmark_anchor( + anchor_path, + artifacts["anchor_manifest_path"], + project_root=tmp_path, + ) + + +def test_coordinated_causal_tampering_fails_exact_reconstruction(tmp_path: Path) -> None: + artifacts = _verified_anchor_artifacts(tmp_path) + anchor_path = artifacts["anchor_path"] + anchor = json.loads(anchor_path.read_text(encoding="utf-8")) + anchor["simulation_config"]["direct_demand_effect"] = 0.91 + anchor["field_provenance"]["explicit_assumptions"]["direct_demand_effect"][ + "value" + ] = 0.91 + _write_json(anchor_path, anchor) + manifest_path = artifacts["anchor_manifest_path"] + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + for index, entry in enumerate(manifest["files"]): + if entry["path"] == str(anchor_path.relative_to(tmp_path)): + manifest["files"][index] = _entry(anchor_path, tmp_path) + _write_json(manifest_path, manifest) + + with pytest.raises(ValueError, match="does not exactly reconstruct"): + run_nyc_informed_marketplace_benchmark( + anchor_path, + manifest_path, + project_root=tmp_path, + config=_laptop_config(), + ) + + +def test_laptop_safety_limits_fail_before_monte_carlo(tmp_path: Path) -> None: + artifacts = _verified_anchor_artifacts(tmp_path) + + with pytest.raises(ValueError, match="max_panel_cells"): + run_nyc_informed_marketplace_benchmark( + artifacts["anchor_path"], + artifacts["anchor_manifest_path"], + project_root=tmp_path, + config=NYCBenchmarkConfig( + replications=2, + n_zones=16, + n_periods=48, + max_panel_cells=100, + ), + ) + + +def test_nyc_benchmark_artifact_bundle_is_atomic_portable_and_hashed( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + anchor = _verified_anchor_artifacts(tmp_path) + result = run_nyc_informed_marketplace_benchmark( + anchor["anchor_path"], + anchor["anchor_manifest_path"], + project_root=tmp_path, + config=_laptop_config(), + ) + output = tmp_path / "published" / "nyc_benchmark" + paths = write_nyc_benchmark_artifacts( + result, + output, + project_root=tmp_path, + ) + + assert set(paths) == { + "output_directory", + "records", + "summary", + "fit_ledger", + "failures", + "metadata", + "manifest", + } + assert all(path.is_file() for key, path in paths.items() if key != "output_directory") + manifest = json.loads(paths["manifest"].read_text(encoding="utf-8")) + metadata = json.loads(paths["metadata"].read_text(encoding="utf-8")) + assert manifest["artifact_type"] == "nyc_informed_marketplace_benchmark" + assert manifest["portable_paths"] is True + assert manifest["causal_claim"] is False + assert manifest["causal_claim_from_nyc_data"] is False + assert manifest["simulator_known_truth"] is True + assert manifest["artifact_directory"] == "published/nyc_benchmark" + assert metadata["artifact_bundle"]["portable_paths"] is True + assert metadata["artifact_bundle"]["nyc_empirical_causal_effect"] is False + assert metadata["artifact_bundle"]["inputs"] == manifest["inputs"] + assert str(tmp_path) not in json.dumps({"manifest": manifest, "metadata": metadata}) + + input_entries = {entry["role"]: entry for entry in manifest["inputs"]} + assert set(input_entries) == {"anchor", "anchor_manifest"} + for role, source in ( + ("anchor", anchor["anchor_path"]), + ("anchor_manifest", anchor["anchor_manifest_path"]), + ): + source_path = Path(source) + entry = input_entries[role] + assert entry["path"] == source_path.relative_to(tmp_path).as_posix() + assert entry["bytes"] == source_path.stat().st_size + assert entry["sha256"] == sha256_file(source_path) + assert not Path(entry["path"]).is_absolute() + + tables = { + "records": result.records, + "summary": result.summary, + "fit_ledger": result.fit_ledger, + "failures": result.failures, + } + entries = {entry["role"]: entry for entry in manifest["files"]} + assert set(entries) == {*tables, "metadata"} + for role, frame in tables.items(): + entry = entries[role] + path = paths[role] + assert entry["path"] == f"{role}.csv" + assert entry["rows"] == len(frame) + assert entry["bytes"] == path.stat().st_size + assert entry["sha256"] == sha256_file(path) + assert Path(entry["path"]).name == entry["path"] + assert entries["metadata"]["bytes"] == paths["metadata"].stat().st_size + assert entries["metadata"]["sha256"] == sha256_file(paths["metadata"]) + + first_hashes = { + key: sha256_file(path) + for key, path in paths.items() + if key != "output_directory" + } + rewritten = write_nyc_benchmark_artifacts( + result, + output, + project_root=tmp_path, + ) + assert first_hashes == { + key: sha256_file(path) + for key, path in rewritten.items() + if key != "output_directory" + } + + sentinel = output / "previous_bundle_sentinel.txt" + sentinel.write_text("preserve\n", encoding="utf-8") + original_manifest = paths["manifest"].read_bytes() + + def fail_staged_write(*_args: object, **_kwargs: object) -> Path: + raise RuntimeError("synthetic staged write failure") + + monkeypatch.setattr( + nyc_benchmark_module, + "_artifact_write_table", + fail_staged_write, + ) + with pytest.raises(RuntimeError, match="synthetic staged write failure"): + write_nyc_benchmark_artifacts(result, output, project_root=tmp_path) + assert sentinel.read_text(encoding="utf-8") == "preserve\n" + assert paths["manifest"].read_bytes() == original_manifest + assert not list(output.parent.glob(f".{output.name}-stage-*")) + + anchor_path = Path(anchor["anchor_path"]) + anchor_path.write_bytes(anchor_path.read_bytes() + b" ") + with pytest.raises(ValueError, match="anchor SHA-256"): + write_nyc_benchmark_artifacts(result, output, project_root=tmp_path) + assert sentinel.read_text(encoding="utf-8") == "preserve\n" + assert paths["manifest"].read_bytes() == original_manifest + assert not list(output.parent.glob(f".{output.name}-stage-*")) diff --git a/CasualLab/tests/test_nyc_calibration.py b/CasualLab/tests/test_nyc_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..e50c3cbecf0e0ad0c10fb1ff9b7f3dab24e030f8 --- /dev/null +++ b/CasualLab/tests/test_nyc_calibration.py @@ -0,0 +1,237 @@ +from __future__ import annotations + +import csv +import json +from datetime import datetime, timedelta +from pathlib import Path + +import pandas as pd +import polars as pl +import pytest + +from casuallab import nyc_calibration as calibration_module +from casuallab.data import DataConfig, write_manifest +from casuallab.interference import add_mapped_exposures +from casuallab.nyc_calibration import ( + NYCCalibrationSettings, + write_nyc_calibration_bundle, +) + + +def _synthetic_full_data(tmp_path: Path) -> DataConfig: + clean_dir = tmp_path / "clean" / "trips" + zone_dir = tmp_path / "panel" / "zone_time" + od_dir = tmp_path / "panel" / "od_flow" + clean_dir.mkdir(parents=True) + zone_dir.mkdir(parents=True) + od_dir.mkdir(parents=True) + + start = datetime(2024, 1, 1) + zone_counts = { + "1": (2, 3, 4, 5), + "2": (1, 1, 2, 2), + } + trip_rows: list[dict[str, object]] = [] + sequence = 0 + for zone_id, counts in zone_counts.items(): + for hour, count in enumerate(counts): + pickup = start + timedelta(hours=hour) + for within_cell in range(count): + wait_minutes = 1 + sequence % 5 + trip_rows.append( + { + "request_datetime": pickup - timedelta(minutes=wait_minutes), + "pickup_datetime": pickup, + "pickup_zone_id": zone_id, + "dropoff_zone_id": ( + zone_id if within_cell == 0 else ("2" if zone_id == "1" else "1") + ), + "fare": 10.0 + sequence, + "driver_pay": 6.0 + sequence / 2, + } + ) + sequence += 1 + clean = pl.DataFrame(trip_rows) + clean_path = clean_dir / "part-00000.parquet" + clean.write_parquet(clean_path) + + zone_rows = [ + { + "zone_id": zone_id, + "time_bin": start + timedelta(hours=hour), + "trip_count": count, + } + for zone_id, counts in zone_counts.items() + for hour, count in enumerate(counts) + ] + zone_path = zone_dir / "part-00000.parquet" + pl.DataFrame(zone_rows).write_parquet(zone_path) + + od_path = od_dir / "part-00000.parquet" + ( + clean.group_by("pickup_zone_id", "dropoff_zone_id", "pickup_datetime") + .agg(pl.len().cast(pl.Int64).alias("trip_count")) + .rename( + { + "pickup_zone_id": "origin_zone_id", + "dropoff_zone_id": "destination_zone_id", + "pickup_datetime": "time_bin", + } + ) + .write_parquet(od_path) + ) + + diagnostics_path = tmp_path / "diagnostics.json" + diagnostics_path.write_text( + json.dumps({"row_count": clean.height}, sort_keys=True) + "\n", + encoding="utf-8", + ) + config = DataConfig( + source="nyc_hvfhv", + mode="full", + project_root=tmp_path, + raw_dir=tmp_path / "raw", + clean_dir=clean_dir.parent, + panel_dir=tmp_path / "panel", + manifest_path=tmp_path / "manifest.json", + diagnostics_path=diagnostics_path, + start_datetime=None, + end_datetime=None, + nyc_expected_rows=clean.height, + panel_frequency="1h", + complete_panel_grid=True, + ) + write_manifest( + (clean_path, zone_path, od_path, diagnostics_path), + config.manifest_path, + config=config, + root=tmp_path, + metadata={ + "causal_claim": False, + "evidence_label": "descriptive_real_data", + "full_month_processing": {"raw_rows": clean.height}, + }, + ) + return config + + +def _csv_rows(path: Path) -> list[dict[str, str]]: + with path.open(encoding="utf-8", newline="") as handle: + return list(csv.DictReader(handle)) + + +def test_writes_streamed_descriptive_calibration_and_network_bundle( + tmp_path: Path, +) -> None: + config = _synthetic_full_data(tmp_path) + artifacts = write_nyc_calibration_bundle( + config, + tmp_path / "calibration_network", + settings=NYCCalibrationSettings( + exact_lag_hours=(1, 2), + target_cluster_count=2, + ), + ) + + calibration = json.loads(artifacts.calibration_path.read_text(encoding="utf-8")) + assert calibration["bundle_valid"] is True + assert calibration["causal_claim"] is False + assert all(calibration["checks"].values()) + assert calibration["conservation"]["clean_rows"] == 20 + assert calibration["conservation"]["zone_trip_sum"] == 20 + assert calibration["conservation"]["od_trip_sum"] == 20 + + moments = calibration["trip_level_descriptive_moments"] + assert moments["request_to_pickup_wait_minutes"]["valid_rows"] == 20 + assert moments["request_to_pickup_wait_minutes"]["mean"] == pytest.approx(3.0) + assert moments["fare"]["mean"] == pytest.approx(19.5) + assert moments["driver_pay"]["mean"] == pytest.approx(10.75) + + variance = calibration["zone_hour_variance_decomposition"] + assert variance["panel_cells"] == 8 + assert variance["zones"] == 2 + assert 0 < variance["icc_like_between_zone_share"] < 1 + assert variance["zone_decomposition_residual"] == pytest.approx(0.0) + assert "not a fitted random-effects ICC" in variance["interpretation"] + + lags = _csv_rows(artifacts.autocorrelation_path) + assert [int(row["lag_hours"]) for row in lags] == [1, 2] + assert [int(row["exact_lag_support_pairs"]) for row in lags] == [6, 4] + assert all(float(row["support_share"]) == pytest.approx(1.0) for row in lags) + + mapping = _csv_rows(artifacts.exposure_mapping_path) + assert mapping + assert {"focal_zone_id", "neighbor_zone_id", "weight"} <= mapping[0].keys() + assert {(row["focal_zone_id"], row["neighbor_zone_id"]) for row in mapping} == { + ("1", "2"), + ("2", "1"), + } + assert all(float(row["weight"]) > 0 for row in mapping) + assignments = pd.DataFrame( + { + "zone_id": ["1", "2", "1", "2"], + "period_id": [0, 0, 1, 1], + "treatment": [1.0, 0.0, 0.0, 1.0], + } + ) + mapped = add_mapped_exposures( + assignments, + pd.DataFrame(mapping)[["focal_zone_id", "neighbor_zone_id", "weight"]], + ) + assert mapped["neighbor_exposure"].tolist() == [0.0, 1.0, 1.0, 0.0] + assert mapped["mapped_neighbor_weight"].tolist() == [1.0] * 4 + + proposal = calibration["simulator_scale_calibration_proposal"] + assert proposal["status"].endswith("not_fitted_structural_model") + assert "spillover_strength" in proposal["not_estimated_from_trip_records"] + assert "persistence" in proposal["not_estimated_from_trip_records"] + assert "welfare_function_or_welfare_effect" in proposal[ + "not_estimated_from_trip_records" + ] + assert all(path.is_file() for path in artifacts.paths()) + assert not (tmp_path / "calibration_network_INCOMPLETE.json").exists() + + manifest = json.loads(artifacts.manifest_path.read_text(encoding="utf-8")) + assert manifest["portable_paths"] is True + assert len(manifest["files"]) == 7 + serialized = "\n".join( + path.read_text(encoding="utf-8") + for path in (artifacts.calibration_path, artifacts.manifest_path) + ) + assert str(tmp_path) not in serialized + + +def test_failure_keeps_previous_bundle_and_leaves_fail_closed_marker( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + config = _synthetic_full_data(tmp_path) + output = tmp_path / "calibration_network" + output.mkdir() + sentinel = output / "previous_success.txt" + sentinel.write_text("previous\n", encoding="utf-8") + + def fail_copy(*_args: object, **_kwargs: object) -> Path: + raise RuntimeError("synthetic publication failure") + + monkeypatch.setattr(calibration_module, "_copy_csv", fail_copy) + with pytest.raises(RuntimeError, match="synthetic publication failure"): + write_nyc_calibration_bundle(config, output) + + assert sentinel.read_text(encoding="utf-8") == "previous\n" + marker = tmp_path / "calibration_network_INCOMPLETE.json" + assert marker.is_file() + assert json.loads(marker.read_text(encoding="utf-8"))["status"] == "incomplete" + + +def test_source_hash_mismatch_fails_before_publishing(tmp_path: Path) -> None: + config = _synthetic_full_data(tmp_path) + clean_path = next((config.clean_dir / "trips").glob("*.parquet")) + clean_path.write_bytes(clean_path.read_bytes() + b"corrupt") + + output = tmp_path / "calibration_network" + with pytest.raises(ValueError, match="source data manifest validation failed"): + write_nyc_calibration_bundle(config, output) + + assert not output.exists() + assert (tmp_path / "calibration_network_INCOMPLETE.json").is_file() diff --git a/CasualLab/tests/test_nyc_events.py b/CasualLab/tests/test_nyc_events.py new file mode 100644 index 0000000000000000000000000000000000000000..25684c2a9804ae8a2966a7b23c81bd43a0ef407c --- /dev/null +++ b/CasualLab/tests/test_nyc_events.py @@ -0,0 +1,422 @@ +import hashlib +import json +from datetime import date +from pathlib import Path + +import pandas as pd +import pytest + +from casuallab.data import sha256_file +from casuallab.nyc_events import ( + EVENT_EVIDENCE_LABEL, + EVENT_SNAPSHOT_SHA256, + HOLIDAY_SNAPSHOT_SHA256, + NYCEventsConfig, + build_nyc_event_calendar, + event_demand_associations, + normalize_nyc_holiday_calendar, + normalize_nyc_permitted_events, + write_nyc_events_bundle, +) + +RAW_EVENTS = Path(__file__).resolve().parents[1] / "data/nyc_events/raw" +HOLIDAY_SNAPSHOT = RAW_EVENTS / "official_holidays_2024-01.csv" +EVENT_SNAPSHOT = RAW_EVENTS / "nyc_permitted_events_overlap_2024-01.csv" + + +@pytest.mark.skipif( + not (HOLIDAY_SNAPSHOT.exists() and EVENT_SNAPSHOT.exists()), + reason="raw NYC event snapshots are gitignored (rights unknown); they ship only in the HF dataset", +) +def test_committed_january_snapshots_match_pinned_official_contract() -> None: + holiday_path = HOLIDAY_SNAPSHOT + event_path = EVENT_SNAPSHOT + + assert holiday_path.stat().st_size == 185 + assert event_path.stat().st_size == 1_307_528 + assert sha256_file(holiday_path) == HOLIDAY_SNAPSHOT_SHA256 + assert sha256_file(event_path) == EVENT_SNAPSHOT_SHA256 + holidays = normalize_nyc_holiday_calendar(holiday_path) + events = normalize_nyc_permitted_events(event_path) + assert len(holidays) == 31 + assert holidays.columns[:3].tolist() == [ + "service_date", + "federal_holiday_name", + "nyc_city_employee_holiday_name", + ] + assert int(holidays["is_any_official_holiday"].sum()) == 2 + assert len(events) == 6007 + assert events["event_id"].nunique() == 951 + assert int(events["invalid_permit_interval"].sum()) == 1 + assert int(events["zero_duration_permit_interval"].sum()) == 8 + assert int((~events["usable_for_daily_expansion"]).sum()) == 9 + + +def _snapshots(root: Path) -> tuple[Path, Path, NYCEventsConfig]: + raw = root / "data/nyc_events/raw" + raw.mkdir(parents=True, exist_ok=True) + holidays = raw / "holidays.csv" + pd.DataFrame( + { + "service_date": ["2024-01-01"], + "federal_holiday_name": ["New Year's Day"], + "nyc_city_employee_holiday_name": ["New Year's Day"], + } + ).to_csv(holidays, index=False) + events = raw / "events.csv" + pd.DataFrame( + { + "event_id": ["100", "101", "101", "102"], + "event_name": ["Major Night", "Public Walk", "Public Walk", "Bad Clock"], + "start_date_time": [ + "2023-12-31T20:00:00.000", + "2024-01-01T10:00:00.000", + "2024-01-01T10:00:00.000", + "2024-01-03T23:00:00.000", + ], + "end_date_time": [ + "2024-01-01T02:00:00.000", + "2024-01-02T11:00:00.000", + "2024-01-02T11:00:00.000", + "2024-01-03T01:00:00.000", + ], + "event_agency": ["Agency A", "Agency B", "Agency B", "Agency C"], + "event_type": ["Special Event", "Parade", "Parade", "Special Event"], + "event_borough": ["Manhattan", "Brooklyn", "Brooklyn", "Queens"], + "event_location": ["A", "B", "C", "D"], + "community_board": ["1,", "2,", "2,", "3,"], + "police_precinct": ["1,", "2,", "2,", "3,"], + } + ).to_csv(events, index=False) + config = NYCEventsConfig( + start_date=date(2024, 1, 1), + end_date=date(2024, 1, 3), + expected_holiday_rows=1, + expected_event_rows=4, + expected_unique_event_ids=3, + holiday_snapshot_sha256=hashlib.sha256(holidays.read_bytes()).hexdigest(), + event_snapshot_sha256=hashlib.sha256(events.read_bytes()).hexdigest(), + major_event_ids=("100",), + public_gathering_event_types=("Parade",), + ) + return holidays, events, config + + +def _panel(path: Path) -> pd.DataFrame: + rows = [] + for day_index, day in enumerate( + (date(2024, 1, 1), date(2024, 1, 2), date(2024, 1, 3)), start=1 + ): + for hour in range(24): + for zone in ("1", "2"): + rows.append( + { + "service_date": day, + "hour": hour, + "zone_id": zone, + "trip_count": 10 * day_index + hour + int(zone), + } + ) + frame = pd.DataFrame(rows) + frame.to_parquet(path, index=False) + return frame + + +def _data_manifest(root: Path, panel_path: Path, trip_sum: int) -> Path: + manifest = root / "data/nyc_full/manifest.json" + manifest.parent.mkdir(parents=True, exist_ok=True) + manifest.write_text( + json.dumps( + { + "config": {"source": "nyc_hvfhv", "mode": "full"}, + "metadata": { + "evidence_label": "descriptive_real_data", + "causal_claim": False, + "full_month_processing": { + "row_conservation": {"zone_time_trip_sum": trip_sum} + }, + }, + "files": [ + { + "path": str(panel_path.relative_to(root)), + "bytes": panel_path.stat().st_size, + "sha256": sha256_file(panel_path), + } + ], + } + ), + encoding="utf-8", + ) + return manifest + + +def test_calendar_and_events_normalize_without_inventing_precision(tmp_path: Path) -> None: + holiday_path, event_path, config = _snapshots(tmp_path) + + holidays = normalize_nyc_holiday_calendar(holiday_path, config) + events = normalize_nyc_permitted_events(event_path, config) + + assert len(holidays) == 3 + assert holidays["is_any_official_holiday"].tolist() == [True, False, False] + assert not holidays["causal_claim"].any() + assert len(events) == 4 + assert events["event_id"].nunique() == 3 + assert events["invalid_permit_interval"].tolist() == [False, False, False, True] + assert not events["zero_duration_permit_interval"].any() + assert events["researcher_defined_major_event"].sum() == 1 + assert set(events["evidence_label"]) == {EVENT_EVIDENCE_LABEL} + + +def test_event_calendar_deduplicates_event_ids_and_excludes_bad_interval( + tmp_path: Path, +) -> None: + holiday_path, event_path, config = _snapshots(tmp_path) + holidays = normalize_nyc_holiday_calendar(holiday_path, config) + events = normalize_nyc_permitted_events(event_path, config) + + calendar, type_daily = build_nyc_event_calendar(holidays, events, config) + + assert calendar["active_permitted_event_count"].tolist() == [2, 1, 0] + assert calendar["active_public_gathering_permitted_event_count"].tolist() == [1, 1, 0] + assert calendar["active_major_permitted_event_count"].tolist() == [1, 0, 0] + assert calendar["is_above_monthly_median_permit_intensity_day"].tolist() == [ + True, + False, + False, + ] + assert int(type_daily["active_unique_permitted_events"].sum()) == 3 + assert not type_daily["causal_claim"].any() + + +def test_event_calendar_uses_positive_duration_half_open_intervals( + tmp_path: Path, +) -> None: + holiday_path, _, config = _snapshots(tmp_path) + holidays = normalize_nyc_holiday_calendar(holiday_path, config) + events = pd.DataFrame( + { + "event_id": ["valid", "zero"], + "event_name": ["Ends at midnight", "No duration"], + "event_type": ["Parade", "Parade"], + "permit_start_local": pd.to_datetime( + ["2024-01-01 20:00:00", "2024-01-02 12:00:00"] + ), + "permit_end_local": pd.to_datetime( + ["2024-01-02 00:00:00", "2024-01-02 12:00:00"] + ), + "usable_for_daily_expansion": [True, False], + "researcher_defined_major_event": [False, False], + "public_gathering_permit_subset": [True, True], + } + ) + + calendar, type_daily = build_nyc_event_calendar(holidays, events, config) + + assert calendar["active_permitted_event_count"].tolist() == [1, 0, 0] + assert int(type_daily["active_unique_permitted_events"].sum()) == 1 + + +def test_event_associations_are_descriptive_complete_and_trip_conserving( + tmp_path: Path, +) -> None: + holiday_path, event_path, config = _snapshots(tmp_path) + holidays = normalize_nyc_holiday_calendar(holiday_path, config) + events = normalize_nyc_permitted_events(event_path, config) + calendar, type_daily = build_nyc_event_calendar(holidays, events, config) + panel_path = tmp_path / "panel.parquet" + panel = _panel(panel_path) + + daily, hourly, summary = event_demand_associations( + [panel_path], calendar, events, type_daily, config + ) + + assert len(daily) == 3 + assert len(hourly) == 24 + assert summary["causal_claim"] is False + assert summary["coverage"]["joined_date_hours"] == 72 + assert summary["coverage"]["source_permit_rows"] == 4 + assert summary["coverage"]["source_unique_event_ids"] == 3 + assert summary["coverage"]["invalid_interval_rows_retained_but_not_expanded"] == 1 + assert summary["coverage"]["weekend_days"] == 0 + assert summary["conservation"]["daily_trip_sum"] == int(panel["trip_count"].sum()) + assert summary["identification_checks"]["causal_effect_identified"] is False + assert summary["identification_checks"][ + "major_event_contrast_separately_identifies_event_effect" + ] is False + assert ( + summary["associations"][ + "above_vs_at_or_below_median_permit_intensity_weekdays_only" + ]["exposed_days"] + == 1 + ) + assert "confound" in " ".join(summary["limitations"]) + + +def test_event_snapshot_hash_and_query_order_fail_closed(tmp_path: Path) -> None: + _, event_path, config = _snapshots(tmp_path) + event_path.write_text(event_path.read_text(encoding="utf-8") + "\n", encoding="utf-8") + with pytest.raises(ValueError, match="SHA-256"): + normalize_nyc_permitted_events(event_path, config) + + _, ordered_path, _ = _snapshots(tmp_path / "ordered") + shuffled = pd.read_csv(ordered_path, dtype=str, keep_default_na=False).iloc[::-1] + shuffled.to_csv(ordered_path, index=False) + shuffled_config = NYCEventsConfig( + start_date=date(2024, 1, 1), + end_date=date(2024, 1, 3), + expected_holiday_rows=1, + expected_event_rows=4, + expected_unique_event_ids=3, + holiday_snapshot_sha256="0" * 64, + event_snapshot_sha256=hashlib.sha256(ordered_path.read_bytes()).hexdigest(), + major_event_ids=("100",), + public_gathering_event_types=("Parade",), + ) + with pytest.raises(ValueError, match="query order"): + normalize_nyc_permitted_events(ordered_path, shuffled_config) + + +def test_event_bundle_verifies_lineage_and_publishes_manifest_last(tmp_path: Path) -> None: + holiday_path, event_path, config = _snapshots(tmp_path) + panel_dir = tmp_path / "data/nyc_full/panel/zone_time" + panel_dir.mkdir(parents=True) + panel_path = panel_dir / "part.parquet" + panel = _panel(panel_path) + data_manifest = _data_manifest(tmp_path, panel_path, int(panel["trip_count"].sum())) + output = tmp_path / "artifacts/nyc_full/events" + + artifacts = write_nyc_events_bundle( + holiday_path, + event_path, + panel_dir, + data_manifest, + output, + project_root=tmp_path, + config=config, + ) + + assert all(path.is_file() for path in artifacts.paths()) + assert not (output / "NYC_EVENTS_INCOMPLETE.json").exists() + payload = json.loads(artifacts.manifest_path.read_text(encoding="utf-8")) + assert payload["evidence_label"] == EVENT_EVIDENCE_LABEL + assert payload["causal_claim"] is False + assert payload["checks"]["trip_conservation"] is True + assert payload["checks"]["joined_days"] == 3 + assert {entry["role"] for entry in payload["files"]} == { + "normalized_daily_calendar", + "normalized_permit_records", + "daily_permit_type_counts", + "joined_daily_trip_panel", + "descriptive_hourly_profiles", + "descriptive_summary", + } + assert {entry["role"] for entry in payload["inputs"]} == { + "official_holiday_snapshot", + "official_nyc_permitted_events_snapshot", + "nyc_full_data_manifest", + "nyc_full_zone_time_panel", + } + assert all( + not Path(entry["path"]).is_absolute() + for collection in (payload["files"], payload["inputs"]) + for entry in collection + ) + + +def test_event_bundle_leaves_marker_and_no_manifest_on_stale_panel(tmp_path: Path) -> None: + holiday_path, event_path, config = _snapshots(tmp_path) + panel_dir = tmp_path / "data/nyc_full/panel/zone_time" + panel_dir.mkdir(parents=True) + panel_path = panel_dir / "part.parquet" + panel = _panel(panel_path) + data_manifest = _data_manifest(tmp_path, panel_path, int(panel["trip_count"].sum())) + output = tmp_path / "artifacts/nyc_full/events" + + write_nyc_events_bundle( + holiday_path, + event_path, + panel_dir, + data_manifest, + output, + project_root=tmp_path, + config=config, + ) + assert (output / "manifest.json").is_file() + panel_path.write_bytes(panel_path.read_bytes() + b"tamper") + + with pytest.raises(ValueError, match="lineage mismatch"): + write_nyc_events_bundle( + holiday_path, + event_path, + panel_dir, + data_manifest, + output, + project_root=tmp_path, + config=config, + ) + assert (output / "NYC_EVENTS_INCOMPLETE.json").is_file() + assert not (output / "manifest.json").exists() + + +def test_event_bundle_rejects_stale_declared_panel_partition(tmp_path: Path) -> None: + holiday_path, event_path, config = _snapshots(tmp_path) + panel_dir = tmp_path / "data/nyc_full/panel/zone_time" + panel_dir.mkdir(parents=True) + panel_path = panel_dir / "part.parquet" + panel = _panel(panel_path) + data_manifest = _data_manifest(tmp_path, panel_path, int(panel["trip_count"].sum())) + payload = json.loads(data_manifest.read_text(encoding="utf-8")) + payload["files"].append( + { + "path": str((panel_dir / "stale.parquet").relative_to(tmp_path)), + "bytes": 1, + "sha256": "0" * 64, + } + ) + data_manifest.write_text(json.dumps(payload), encoding="utf-8") + output = tmp_path / "artifacts/nyc_full/events" + + with pytest.raises(ValueError, match="exactly match"): + write_nyc_events_bundle( + holiday_path, + event_path, + panel_dir, + data_manifest, + output, + project_root=tmp_path, + config=config, + ) + + assert (output / "NYC_EVENTS_INCOMPLETE.json").is_file() + assert not (output / "manifest.json").exists() + + +@pytest.mark.parametrize("bad_entry", [{"bytes": 1}, {"path": "../escape.parquet"}]) +def test_event_bundle_rejects_malformed_or_traversing_manifest_entry( + tmp_path: Path, + bad_entry: dict[str, object], +) -> None: + holiday_path, event_path, config = _snapshots(tmp_path) + panel_dir = tmp_path / "data/nyc_full/panel/zone_time" + panel_dir.mkdir(parents=True) + panel_path = panel_dir / "part.parquet" + panel = _panel(panel_path) + data_manifest = _data_manifest(tmp_path, panel_path, int(panel["trip_count"].sum())) + payload = json.loads(data_manifest.read_text(encoding="utf-8")) + payload["files"].append(bad_entry) + data_manifest.write_text(json.dumps(payload), encoding="utf-8") + output = tmp_path / "artifacts/nyc_full/events" + + with pytest.raises(ValueError, match="malformed|nonportable"): + write_nyc_events_bundle( + holiday_path, + event_path, + panel_dir, + data_manifest, + output, + project_root=tmp_path, + config=config, + ) + + assert (output / "NYC_EVENTS_INCOMPLETE.json").is_file() + assert not (output / "manifest.json").exists() diff --git a/CasualLab/tests/test_nyc_full_analysis.py b/CasualLab/tests/test_nyc_full_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..45dbf0ef37b762e99226abbf771a8b5b740066e1 --- /dev/null +++ b/CasualLab/tests/test_nyc_full_analysis.py @@ -0,0 +1,127 @@ +from __future__ import annotations + +import json +from datetime import datetime, timedelta +from pathlib import Path +from time import perf_counter + +import polars as pl +import pytest + +from casuallab import nyc_full_analysis as nyc_full_analysis_module +from casuallab.data import DataConfig, run_data_pipeline, sha256_file +from casuallab.nyc_full_analysis import write_nyc_full_analysis + + +def _calendar_raw() -> pl.DataFrame: + pickups = [datetime(2024, 1, 1) + timedelta(hours=index) for index in range(31 * 24)] + pickups.append(datetime(2024, 1, 1, 0, 30)) + rows = len(pickups) + origins = [1 + index % 2 for index in range(rows)] + destinations = [2 - index % 2 for index in range(rows)] + return pl.DataFrame( + { + "hvfhs_license_num": ["HV0003"] * rows, + "dispatching_base_num": ["B00001"] * rows, + "request_datetime": pickups, + "pickup_datetime": pickups, + "dropoff_datetime": [value + timedelta(minutes=10) for value in pickups], + "PULocationID": origins, + "DOLocationID": destinations, + "trip_miles": [2.5] * rows, + "trip_time": [600] * rows, + "base_passenger_fare": [15.0] * (rows - 1) + [20.0], + "tips": [2.0] * rows, + "driver_pay": [10.0] * rows, + "shared_request_flag": ["N"] * rows, + "shared_match_flag": ["N"] * rows, + } + ) + + +def _full_config(tmp_path: Path) -> DataConfig: + raw_dir = tmp_path / "raw" + raw_dir.mkdir() + raw_path = raw_dir / "fhvhv_tripdata_2024-01.parquet" + raw = _calendar_raw() + raw.write_parquet(raw_path, row_group_size=100) + config = DataConfig( + source="nyc_hvfhv", + mode="full", + project_root=tmp_path, + raw_dir=raw_dir, + clean_dir=tmp_path / "clean", + panel_dir=tmp_path / "panel", + manifest_path=tmp_path / "manifest.json", + diagnostics_path=tmp_path / "diagnostics.json", + start_datetime=None, + end_datetime=None, + nyc_year=2024, + nyc_months=(1,), + nyc_batch_rows=200, + nyc_expected_rows=raw.height, + nyc_expected_bytes=raw_path.stat().st_size, + nyc_expected_sha256=sha256_file(raw_path), + panel_frequency="1h", + complete_panel_grid=True, + ) + run_data_pipeline(config) + return config + + +def test_full_month_analysis_validates_and_writes_compact_evidence(tmp_path: Path) -> None: + config = _full_config(tmp_path) + + artifacts = write_nyc_full_analysis( + config, + tmp_path / "analysis", + started_at_monotonic=perf_counter(), + raw_cached=True, + command="synthetic-test", + ) + validation = json.loads(artifacts.validation_path.read_text(encoding="utf-8")) + + assert validation["validation_passed"] is True + assert validation["causal_claim"] is False + assert validation["scope"]["population_claim"] is False + assert validation["coverage"]["date_hours"] == 31 * 24 + assert validation["conservation"]["raw_rows"] == config.nyc_expected_rows + assert validation["conservation"]["zone_time_rows"] == 2 * 31 * 24 + assert validation["conservation"]["zone_trip_sum"] == config.nyc_expected_rows + assert validation["conservation"]["od_trip_sum"] == config.nyc_expected_rows + assert validation["checks"]["manifest_files_valid"] is True + assert validation["provenance"]["data_manifest"] == "manifest.json" + assert not Path(validation["provenance"]["data_manifest"]).is_absolute() + assert sum(1 for _ in artifacts.daily_path.open(encoding="utf-8")) == 32 + assert sum(1 for _ in artifacts.hourly_path.open(encoding="utf-8")) == 25 + assert sum(1 for _ in artifacts.weekday_path.open(encoding="utf-8")) == 8 + assert all(path.is_file() for path in artifacts.paths()) + assert not ( + tmp_path / "analysis" / "NYC_FULL_ANALYSIS_INCOMPLETE.json" + ).exists() + + +def test_full_month_analysis_invalidates_manifest_and_marks_failure( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + config = _full_config(tmp_path) + output = tmp_path / "analysis" + output.mkdir() + stale_manifest = output / "manifest.json" + stale_manifest.write_text('{"stale": true}\n', encoding="utf-8") + + marker = output / "NYC_FULL_ANALYSIS_INCOMPLETE.json" + + def fail_manifest(*_args: object, **_kwargs: object) -> Path: + assert marker.is_file() + assert not stale_manifest.exists() + raise RuntimeError("synthetic analysis failure") + + monkeypatch.setattr(nyc_full_analysis_module, "write_manifest", fail_manifest) + with pytest.raises(RuntimeError, match="synthetic analysis failure"): + write_nyc_full_analysis(config, output) + + assert not stale_manifest.exists() + assert marker.is_file() + assert json.loads(marker.read_text(encoding="utf-8"))["status"] == "incomplete" diff --git a/CasualLab/tests/test_nyc_graph_benchmark.py b/CasualLab/tests/test_nyc_graph_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..920546dacbf1996d49b224d2422df79c86be08d2 --- /dev/null +++ b/CasualLab/tests/test_nyc_graph_benchmark.py @@ -0,0 +1,402 @@ +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +import casuallab.nyc_graph_benchmark as nyc_graph_benchmark_module +from casuallab.data import sha256_file +from casuallab.nyc_graph_benchmark import ( + NYCGraphBenchmarkConfig, + known_nyc_graph_estimands, + run_nyc_graph_benchmark, + validate_nyc_graph_bundle, + write_nyc_graph_benchmark_artifacts, +) + +REAL_BUNDLE = ( + Path(__file__).resolve().parents[1] + / "artifacts" + / "nyc_full" + / "calibration_network" +) +requires_real_bundle = pytest.mark.skipif( + not REAL_BUNDLE.is_dir(), + reason="artifacts/nyc_full/calibration_network is gitignored; `make validate-nyc-full` builds it", +) + + +def _source_attestation() -> dict[str, object]: + return { + "all_valid": True, + "hashes_recomputed": True, + "queried_files_listed": True, + "scope_is_full_nyc_descriptive": True, + "mismatches": [], + "sha256": "a" * 64, + "entries": 3, + "declared_file_set_sha256": "b" * 64, + "path": "data/nyc_full/manifest.json", + } + + +def _write_json(path: Path, payload: dict[str, object]) -> None: + path.write_text( + json.dumps(payload, indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + + +def _synthetic_bundle(tmp_path: Path, n_zones: int = 12) -> Path: + bundle = tmp_path / "calibration_network" + bundle.mkdir() + rows: list[dict[str, object]] = [] + for left in range(n_zones): + for right in range(left + 1, n_zones): + # Symmetric pre-treatment graph geometry with heterogeneous raw weights. + weight = float(1 + ((left + 3) * (right + 5)) % 17) + for focal, neighbor in ((left, right), (right, left)): + rows.append( + { + "focal_zone_id": str(focal), + "neighbor_zone_id": str(neighbor), + "weight": weight, + "evidence_label": "descriptive_real_data", + "weight_definition": ( + "Symmetric monthly completed-trip flow; downstream " + "row-normalizes weight." + ), + "interpretation_warning": ( + "Pre-treatment exposure-map input; not an estimated " + "spillover effect." + ), + } + ) + mapping_path = bundle / "exposure_mapping_edges.csv" + pd.DataFrame(rows).sort_values( + ["focal_zone_id", "neighbor_zone_id"] + ).to_csv(mapping_path, index=False) + + source = _source_attestation() + calibration = { + "schema_version": "1.0.0", + "evidence_label": "descriptive_real_data", + "causal_claim": False, + "bundle_valid": True, + "scope": { + "source": "nyc_hvfhv", + "population_claim": False, + }, + "checks": {"synthetic_conservation": True}, + "critical_warning": ( + "Published completed-trip associations are descriptive and do not identify " + "treatment response, spillovers, persistence, substitution, or welfare." + ), + "provenance": {"source_data_manifest": source}, + "od_flow_graph": { + "evidence_label": "descriptive_real_data", + "exposure_mapping_file": "exposure_mapping_edges.csv", + "exposure_mapping_schema": [ + "focal_zone_id", + "neighbor_zone_id", + "weight", + ], + "interpretation": ( + "Observed OD weights define a candidate exposure graph but do not " + "estimate interference, rider substitution, or driver movement." + ), + }, + } + calibration_path = bundle / "calibration.json" + _write_json(calibration_path, calibration) + + files = [ + { + "path": path.name, + "bytes": path.stat().st_size, + "sha256": sha256_file(path), + } + for path in (calibration_path, mapping_path) + ] + manifest = { + "schema_version": "1.0.0", + "evidence_label": "descriptive_real_data", + "causal_claim": False, + "portable_paths": True, + "files": files, + "source_data_manifest": source, + "config": { + "data": {"source": "nyc_hvfhv", "mode": "full"}, + "calibration": {"verify_source_hashes": True}, + }, + "interpretation_warning": ( + "Published completed-trip associations are descriptive and do not identify " + "treatment response, spillovers, persistence, substitution, or welfare." + ), + } + _write_json(bundle / "manifest.json", manifest) + return bundle + + +@requires_real_bundle +def test_real_and_synthetic_calibration_bundles_validate_and_run( + tmp_path: Path, +) -> None: + synthetic_path = _synthetic_bundle(tmp_path) + real = validate_nyc_graph_bundle(REAL_BUNDLE) + synthetic = validate_nyc_graph_bundle(synthetic_path) + + assert len(real.edges) > 60_000 + assert len(synthetic.edges) == 12 * 11 + assert real.mapping_sha256 == sha256_file( + REAL_BUNDLE / "exposure_mapping_edges.csv" + ) + assert set(real.edges["evidence_label"]) == {"descriptive_real_data"} + assert set(synthetic.edges["evidence_label"]) == {"descriptive_real_data"} + + config = NYCGraphBenchmarkConfig( + replications=2, + n_zones=12, + n_periods=12, + seed=447, + ) + real_result = run_nyc_graph_benchmark(REAL_BUNDLE, config) + synthetic_result = run_nyc_graph_benchmark(synthetic_path, config) + assert real_result.failures.empty + assert synthetic_result.failures.empty + assert real_result.fit_ledger["fit_complete"].all() + assert synthetic_result.fit_ledger["fit_complete"].all() + + +@requires_real_bundle +def test_real_nyc_graph_benchmark_is_deterministic_and_records_selection() -> None: + config = NYCGraphBenchmarkConfig( + replications=3, + n_zones=12, + n_periods=12, + seed=551, + ) + first = run_nyc_graph_benchmark(REAL_BUNDLE, config) + second = run_nyc_graph_benchmark(REAL_BUNDLE, config) + + pd.testing.assert_frame_equal(first.records, second.records) + pd.testing.assert_frame_equal(first.summary, second.summary) + pd.testing.assert_frame_equal(first.fit_ledger, second.fit_ledger) + pd.testing.assert_frame_equal(first.failures, second.failures) + assert first.metadata == second.metadata + subset = first.metadata["zone_subset"] + assert subset["selection_uses_only_pre_treatment_graph_fields"] is True + assert len(subset["selected_zone_ids_in_order"]) == config.n_zones + assert len(subset["subset_raw_mapping_sha256"]) == 64 + assert "not spillover strength" in first.metadata["graph_weight_role"] + assert first.metadata["causal_claim_from_nyc_data"] is False + assert ( + first.metadata["calibration_bundle"]["directory_name"] + == "artifacts/nyc_full/calibration_network" + ) + + +def test_bundle_validation_rejects_mapping_tampering(tmp_path: Path) -> None: + bundle = _synthetic_bundle(tmp_path) + mapping_path = bundle / "exposure_mapping_edges.csv" + tampered = mapping_path.read_bytes().replace( + b"descriptive_real_data", + b"xescriptive_real_data", + 1, + ) + mapping_path.write_bytes(tampered) + + with pytest.raises(ValueError, match="SHA-256 mismatch"): + validate_nyc_graph_bundle(bundle) + + +def test_bundle_validation_rejects_non_descriptive_evidence(tmp_path: Path) -> None: + bundle = _synthetic_bundle(tmp_path) + manifest_path = bundle / "manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + manifest["evidence_label"] = "causal_estimate" + _write_json(manifest_path, manifest) + + with pytest.raises(ValueError, match="descriptive_real_data"): + validate_nyc_graph_bundle(bundle) + + +@requires_real_bundle +def test_real_nyc_geometry_recovers_controlled_targets_and_withholds_naive_total() -> None: + config = NYCGraphBenchmarkConfig( + replications=8, + n_zones=16, + n_periods=20, + seed=991, + ) + result = run_nyc_graph_benchmark(REAL_BUNDLE, config) + truth = known_nyc_graph_estimands(config) + mapped = result.summary.loc[result.summary["identified"]].set_index( + "target_estimand" + ) + + assert mapped.loc[ + "controlled_zone_direct_effect", "mean_estimate" + ] == pytest.approx(truth.controlled_zone_direct_effect, abs=0.10) + assert mapped.loc["spillover_effect", "mean_estimate"] == pytest.approx( + truth.spillover_effect, abs=0.12 + ) + assert mapped.loc[ + "controlled_history_exposure_response", "mean_estimate" + ] == pytest.approx( + truth.controlled_history_exposure_response, abs=0.10 + ) + assert mapped["inference_valid_for_target"].all() + assert mapped["controlled_exposure_not_market_total"].all() + assert not mapped["graph_weight_is_spillover_strength"].any() + + naive = result.summary.loc[ + result.summary["estimator"].eq( + "nyc_graph_naive_assignment_cluster_regression" + ) + ].iloc[0] + assert naive["target_estimand"] == "market_total_effect" + assert naive["comparison_status"] == "target_mismatch" + assert not bool(naive["identified"]) + assert naive["diagnostic_mean_gap_to_market_total"] < -1.0 + assert np.isnan(naive["bias"]) + assert np.isnan(naive["rmse"]) + assert np.isnan(naive["coverage"]) + assert np.isnan(naive["power"]) + assert "withheld" in naive["withheld_reason"] + assert truth.market_total_effect != truth.controlled_zone_direct_effect + + +def test_config_requires_history_identifying_saturation_support() -> None: + with pytest.raises(ValueError, match="interior arm"): + NYCGraphBenchmarkConfig(saturation_levels=(0.0, 1.0)) + + +def test_nyc_graph_artifact_bundle_is_atomic_portable_and_hashed( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + bundle = _synthetic_bundle(tmp_path) + result = run_nyc_graph_benchmark( + bundle, + NYCGraphBenchmarkConfig( + replications=2, + n_zones=12, + n_periods=12, + seed=731, + ), + ) + output = tmp_path / "published" / "nyc_graph_benchmark" + paths = write_nyc_graph_benchmark_artifacts( + result, + output, + project_root=tmp_path, + ) + + assert set(paths) == { + "output_directory", + "records", + "summary", + "fit_ledger", + "failures", + "metadata", + "manifest", + } + assert all(path.is_file() for key, path in paths.items() if key != "output_directory") + manifest = json.loads(paths["manifest"].read_text(encoding="utf-8")) + metadata = json.loads(paths["metadata"].read_text(encoding="utf-8")) + assert manifest["artifact_type"] == "nyc_graph_interference_benchmark" + assert manifest["portable_paths"] is True + assert manifest["causal_claim"] is False + assert manifest["causal_claim_from_nyc_data"] is False + assert manifest["input_graph_evidence_label"] == "descriptive_real_data" + assert manifest["artifact_directory"] == "published/nyc_graph_benchmark" + artifact_metadata = metadata["artifact_bundle"] + assert artifact_metadata["portable_paths"] is True + assert artifact_metadata["causal_claim_from_nyc_data"] is False + assert artifact_metadata["input_graph_evidence_label"] == "descriptive_real_data" + assert artifact_metadata["inputs"] == manifest["inputs"] + assert "not spillover strength" in metadata["graph_weight_role"] + assert str(tmp_path) not in json.dumps({"manifest": manifest, "metadata": metadata}) + + input_entries = {entry["role"]: entry for entry in manifest["inputs"]} + assert set(input_entries) == {"calibration_manifest", "exposure_mapping"} + for role, source in ( + ("calibration_manifest", bundle / "manifest.json"), + ("exposure_mapping", bundle / "exposure_mapping_edges.csv"), + ): + entry = input_entries[role] + assert entry["path"] == source.relative_to(tmp_path).as_posix() + assert entry["bytes"] == source.stat().st_size + assert entry["sha256"] == sha256_file(source) + assert not Path(entry["path"]).is_absolute() + + tables = { + "records": result.records, + "summary": result.summary, + "fit_ledger": result.fit_ledger, + "failures": result.failures, + } + entries = {entry["role"]: entry for entry in manifest["files"]} + assert set(entries) == {*tables, "metadata"} + for role, frame in tables.items(): + entry = entries[role] + path = paths[role] + assert entry["path"] == f"{role}.csv" + assert entry["rows"] == len(frame) + assert entry["bytes"] == path.stat().st_size + assert entry["sha256"] == sha256_file(path) + assert Path(entry["path"]).name == entry["path"] + assert entries["metadata"]["bytes"] == paths["metadata"].stat().st_size + assert entries["metadata"]["sha256"] == sha256_file(paths["metadata"]) + + first_hashes = { + key: sha256_file(path) + for key, path in paths.items() + if key != "output_directory" + } + rewritten = write_nyc_graph_benchmark_artifacts( + result, + output, + project_root=tmp_path, + ) + assert first_hashes == { + key: sha256_file(path) + for key, path in rewritten.items() + if key != "output_directory" + } + + sentinel = output / "previous_bundle_sentinel.txt" + sentinel.write_text("preserve\n", encoding="utf-8") + original_manifest = paths["manifest"].read_bytes() + + def fail_staged_write(*_args: object, **_kwargs: object) -> Path: + raise RuntimeError("synthetic staged write failure") + + monkeypatch.setattr( + nyc_graph_benchmark_module, + "_artifact_write_table", + fail_staged_write, + ) + with pytest.raises(RuntimeError, match="synthetic staged write failure"): + write_nyc_graph_benchmark_artifacts(result, output, project_root=tmp_path) + assert sentinel.read_text(encoding="utf-8") == "preserve\n" + assert paths["manifest"].read_bytes() == original_manifest + assert not list(output.parent.glob(f".{output.name}-stage-*")) + + mapping_path = bundle / "exposure_mapping_edges.csv" + mapping_path.write_bytes( + mapping_path.read_bytes().replace( + b"descriptive_real_data", + b"xescriptive_real_data", + 1, + ) + ) + with pytest.raises(ValueError, match="SHA-256 mismatch"): + write_nyc_graph_benchmark_artifacts(result, output, project_root=tmp_path) + assert sentinel.read_text(encoding="utf-8") == "preserve\n" + assert paths["manifest"].read_bytes() == original_manifest + assert not list(output.parent.glob(f".{output.name}-stage-*")) diff --git a/CasualLab/tests/test_nyc_income.py b/CasualLab/tests/test_nyc_income.py new file mode 100644 index 0000000000000000000000000000000000000000..f6f680cad372bbc6c55d2891bc774763bebb8def --- /dev/null +++ b/CasualLab/tests/test_nyc_income.py @@ -0,0 +1,635 @@ +import json +import zipfile +from datetime import date +from pathlib import Path + +import pandas as pd +import pytest +import shapefile + +from casuallab.data import sha256_file +from casuallab.nyc_income import ( + BIN_ESTIMATE_COLUMNS, + ESTIMATE_COLUMNS, + INCOME_EVIDENCE_LABEL, + MOE_COLUMNS, + NYCIncomeConfig, + aggregate_acs_b19001_to_nta, + allocate_nta_income_to_taxi_zones, + build_taxi_zone_nta_crosswalk, + income_trip_descriptions, + write_nyc_income_bundle, +) + +RAW_INCOME = Path(__file__).resolve().parents[1] / "data/nyc_income/raw" + + +@pytest.mark.skipif( + not (RAW_INCOME / "source_manifest.json").exists(), + reason="raw NYC income sources are gitignored (rights unknown); they ship only in the HF dataset", +) +def test_committed_income_sources_match_pins_and_source_manifest() -> None: + raw = RAW_INCOME + config = NYCIncomeConfig() + expected = { + "taxi_zones.zip": config.expected_taxi_sha256, + "nyc_nta2020.geojson": config.expected_nta_sha256, + "nyc_tract2020_to_nta2020.csv": config.expected_tract_to_nta_sha256, + "acs_2022_5yr_b19001_nyc_tracts.dat": config.expected_acs_sha256, + } + manifest = json.loads((raw / "source_manifest.json").read_text(encoding="utf-8")) + entries = {Path(entry["path"]).name: entry for entry in manifest["sources"]} + + assert manifest["causal_claim"] is False + assert manifest["evidence_label"] == INCOME_EVIDENCE_LABEL + assert set(entries) == set(expected) + for filename, digest in expected.items(): + path = raw / filename + assert path.is_file() + assert sha256_file(path) == digest == entries[filename]["sha256"] + assert path.stat().st_size == entries[filename]["bytes"] + assert entries[filename]["url"].startswith("https://") + + +def _write_taxi_zip(path: Path) -> None: + source = path.parent / "taxi_shape" + source.mkdir(parents=True) + base = source / "taxi_zones" + writer = shapefile.Writer(str(base), shapeType=shapefile.POLYGON) + writer.field("OBJECTID", "N", decimal=0) + writer.field("Shape_Leng", "F", decimal=6) + writer.field("Shape_Area", "F", decimal=6) + writer.field("zone", "C", size=50) + writer.field("LocationID", "N", decimal=0) + writer.field("borough", "C", size=30) + for location_id, left, name in ((1, 0.0, "West"), (2, 1.0, "East")): + writer.poly( + [ + [ + [left, 0.0], + [left, 1.0], + [left + 1.0, 1.0], + [left + 1.0, 0.0], + [left, 0.0], + ] + ] + ) + writer.record(location_id, 4.0, 1.0, name, location_id, "Fixture") + writer.close() + path.parent.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as archive: + for suffix in ("shp", "shx", "dbf"): + archive.write(base.with_suffix(f".{suffix}"), f"taxi_zones/taxi_zones.{suffix}") + + +def _write_nta(path: Path) -> None: + features = [] + for code, left, name in (("BX0001", 0.0, "Low NTA"), ("BX0002", 1.0, "High NTA")): + features.append( + { + "type": "Feature", + "properties": { + "nta2020": code, + "ntaname": name, + "ntatype": "0", + "boroname": "Fixture", + }, + "geometry": { + "type": "Polygon", + "coordinates": [ + [ + [left, 0.0], + [left + 1.0, 0.0], + [left + 1.0, 1.0], + [left, 1.0], + [left, 0.0], + ] + ], + }, + } + ) + path.write_text( + json.dumps({"type": "FeatureCollection", "features": features}), + encoding="utf-8", + ) + + +def _write_tract_map(path: Path) -> None: + pd.DataFrame( + { + "geoid": ["36005000100", "36005000200"], + "nta2020": ["BX0001", "BX0002"], + "ntaname": ["Low NTA", "High NTA"], + "borocode": ["2", "2"], + "boroname": ["Bronx", "Bronx"], + } + ).to_csv(path, index=False) + + +def _acs_row(geoid: str, *, under_10k: int, at_least_100k: int) -> dict[str, int | str]: + row: dict[str, int | str] = {"GEO_ID": f"1400000US{geoid}"} + total = under_10k + at_least_100k + for column in ESTIMATE_COLUMNS: + row[column] = 0 + for column in MOE_COLUMNS: + row[column] = 1 + row[ESTIMATE_COLUMNS[0]] = total + row["B19001_E002"] = under_10k + row["B19001_E014"] = at_least_100k + return row + + +def _write_acs(path: Path) -> None: + columns = ["GEO_ID"] + for estimate, moe in zip(ESTIMATE_COLUMNS, MOE_COLUMNS, strict=True): + columns.extend([estimate, moe]) + pd.DataFrame( + [ + _acs_row("36005000100", under_10k=60, at_least_100k=40), + _acs_row("36005000200", under_10k=20, at_least_100k=80), + ] + )[columns].to_csv(path, sep="|", index=False) + + +def _write_panel(path: Path) -> pd.DataFrame: + rows = [] + for service_date in (date(2024, 1, 1), date(2024, 1, 2)): + for hour in range(24): + rows.extend( + [ + { + "service_date": service_date, + "hour": hour, + "zone_id": "1", + "trip_count": 10, + }, + { + "service_date": service_date, + "hour": hour, + "zone_id": "2", + "trip_count": 20, + }, + ] + ) + frame = pd.DataFrame(rows) + frame.to_parquet(path, index=False) + return frame + + +def _write_data_manifest(root: Path, panel_path: Path, trip_sum: int) -> Path: + manifest = root / "data/nyc_full/manifest.json" + manifest.parent.mkdir(parents=True, exist_ok=True) + manifest.write_text( + json.dumps( + { + "config": {"source": "nyc_hvfhv", "mode": "full"}, + "metadata": { + "evidence_label": "descriptive_real_data", + "causal_claim": False, + "full_month_processing": { + "row_conservation": {"zone_time_trip_sum": trip_sum} + }, + }, + "files": [ + { + "path": str(panel_path.relative_to(root)), + "bytes": panel_path.stat().st_size, + "sha256": sha256_file(panel_path), + } + ], + } + ), + encoding="utf-8", + ) + return manifest + + +def _fixture(root: Path) -> tuple[dict[str, Path], NYCIncomeConfig]: + raw = root / "data/nyc_income/raw" + raw.mkdir(parents=True) + taxi = raw / "taxi_zones.zip" + nta = raw / "nta.geojson" + tract = raw / "tract.csv" + acs = raw / "acs.dat" + _write_taxi_zip(taxi) + _write_nta(nta) + _write_tract_map(tract) + _write_acs(acs) + panel_dir = root / "data/nyc_full/panel/zone_time" + panel_dir.mkdir(parents=True) + panel = panel_dir / "part.parquet" + frame = _write_panel(panel) + manifest = _write_data_manifest(root, panel, int(frame["trip_count"].sum())) + config = NYCIncomeConfig( + expected_taxi_sha256=sha256_file(taxi), + expected_nta_sha256=sha256_file(nta), + expected_tract_to_nta_sha256=sha256_file(tract), + expected_acs_sha256=sha256_file(acs), + expected_taxi_features=2, + expected_nta_features=2, + expected_tract_rows=2, + expected_acs_rows=2, + taxi_source_crs="EPSG:4326", + nta_source_crs="EPSG:4326", + minimum_residential_nta_area_coverage=0.999, + start_date=date(2024, 1, 1), + end_date=date(2024, 1, 2), + ) + return { + "taxi": taxi, + "nta": nta, + "tract": tract, + "acs": acs, + "panel_dir": panel_dir, + "panel": panel, + "manifest": manifest, + }, config + + +def test_tract_bins_are_aggregated_before_grouped_medians(tmp_path: Path) -> None: + paths, config = _fixture(tmp_path) + nta, diagnostics = aggregate_acs_b19001_to_nta( + paths["tract"], + paths["acs"], + ["BX0001", "BX0002"], + config, + ) + + assert diagnostics["median_of_medians_used"] is False + assert diagnostics["acs_total_households"] == 200 + assert diagnostics["mapped_total_households"] == 200 + assert int(nta[ESTIMATE_COLUMNS[0]].sum()) == 200 + assert int(nta[list(BIN_ESTIMATE_COLUMNS)].to_numpy().sum()) == 200 + assert set(nta["evidence_label"]) == {INCOME_EVIDENCE_LABEL} + assert not nta["causal_claim"].any() + + +def test_equal_area_crosswalk_is_complete_and_normalized(tmp_path: Path) -> None: + paths, config = _fixture(tmp_path) + crosswalk, diagnostics = build_taxi_zone_nta_crosswalk( + paths["taxi"], + paths["nta"], + config, + ) + + assert len(crosswalk) == 2 + assert set(crosswalk["location_id"]) == {1, 2} + assert crosswalk["is_dominant_nta"].all() + assert crosswalk.groupby("nta2020")["nta_allocation_weight"].sum().eq(1).all() + assert diagnostics["equal_area_crs"] == "EPSG:6933" + assert diagnostics["taxi_zones_without_nta_overlap"] == 0 + + +def test_nonresidential_dominant_zone_is_primary_unclassified_but_sensitivity_kept() -> None: + crosswalk = pd.DataFrame( + [ + { + "location_id": 1, + "taxi_zone_name": "Fixture Airport", + "taxi_borough": "Fixture", + "nta2020": "AIR001", + "nta_name": "Airport", + "nta_type": "8", + "taxi_zone_area_m2": 100.0, + "intersection_area_m2": 90.0, + "taxi_zone_area_share": 0.9, + "nta_area_share": 1.0, + "nta_allocation_weight": 1.0, + "is_dominant_nta": True, + }, + { + "location_id": 1, + "taxi_zone_name": "Fixture Airport", + "taxi_borough": "Fixture", + "nta2020": "RES001", + "nta_name": "Residential", + "nta_type": "0", + "taxi_zone_area_m2": 100.0, + "intersection_area_m2": 10.0, + "taxi_zone_area_share": 0.1, + "nta_area_share": 0.1, + "nta_allocation_weight": 0.1, + "is_dominant_nta": False, + }, + { + "location_id": 2, + "taxi_zone_name": "Fixture Residential", + "taxi_borough": "Fixture", + "nta2020": "RES001", + "nta_name": "Residential", + "nta_type": "0", + "taxi_zone_area_m2": 90.0, + "intersection_area_m2": 90.0, + "taxi_zone_area_share": 1.0, + "nta_area_share": 0.9, + "nta_allocation_weight": 0.9, + "is_dominant_nta": True, + }, + ] + ) + rows = [] + for nta2020, total, low, high in ( + ("AIR001", 0, 0, 0), + ("RES001", 100, 40, 60), + ): + row: dict[str, float | str] = {"nta2020": nta2020} + row.update({column: 0.0 for column in ESTIMATE_COLUMNS}) + row[ESTIMATE_COLUMNS[0]] = float(total) + row["B19001_E002"] = float(low) + row["B19001_E014"] = float(high) + rows.append(row) + nta_income = pd.DataFrame(rows) + + zones, diagnostics = allocate_nta_income_to_taxi_zones( + crosswalk, + nta_income, + citywide_grouped_median_usd=100_000.0, + config=NYCIncomeConfig( + minimum_allocated_households=1.0, + minimum_residential_taxi_zone_area_share=0.5, + ), + ) + indexed = zones.set_index("location_id") + + assert indexed.loc[1, "dominant_nta_type"] == "8" + assert not bool(indexed.loc[1, "dominant_nta_residential_eligible"]) + assert indexed.loc[1, "residential_taxi_zone_area_share"] == pytest.approx(0.1) + assert indexed.loc[1, "area_allocated_residential_households"] == pytest.approx(10) + assert indexed.loc[1, "income_group"] == "unclassified" + assert ( + indexed.loc[1, "income_group_all_zone_area_allocation_sensitivity"] + == "high_income_area" + ) + assert indexed.loc[2, "income_group"] == "high_income_area" + assert diagnostics["dominant_nonresidential_zone_rows"] == 1 + assert diagnostics[ + "dominant_nonresidential_zones_classified_only_in_sensitivity" + ] == 1 + + +def test_primary_gate_requires_half_of_taxi_zone_area_to_be_residential() -> None: + crosswalk_rows = [] + for code, nta_type, area, dominant in ( + ("RES001", "0", 40.0, True), + ("AIR001", "8", 30.0, False), + ("PARK01", "9", 30.0, False), + ): + crosswalk_rows.append( + { + "location_id": 1, + "taxi_zone_name": "Mixed Special Area", + "taxi_borough": "Fixture", + "nta2020": code, + "nta_name": code, + "nta_type": nta_type, + "taxi_zone_area_m2": 100.0, + "intersection_area_m2": area, + "taxi_zone_area_share": area / 100.0, + "nta_area_share": 1.0, + "nta_allocation_weight": 1.0, + "is_dominant_nta": dominant, + } + ) + nta_rows = [] + for code, total in (("RES001", 100.0), ("AIR001", 0.0), ("PARK01", 0.0)): + row: dict[str, float | str] = {"nta2020": code} + row.update({column: 0.0 for column in ESTIMATE_COLUMNS}) + row[ESTIMATE_COLUMNS[0]] = total + row["B19001_E002"] = total * 0.4 + row["B19001_E014"] = total * 0.6 + nta_rows.append(row) + + zones, diagnostics = allocate_nta_income_to_taxi_zones( + pd.DataFrame(crosswalk_rows), + pd.DataFrame(nta_rows), + citywide_grouped_median_usd=100_000.0, + config=NYCIncomeConfig( + minimum_allocated_households=1.0, + minimum_residential_taxi_zone_area_share=0.5, + ), + ) + zone = zones.iloc[0] + + assert zone["dominant_nta_type"] == "0" + assert bool(zone["dominant_nta_residential_eligible"]) + assert zone["residential_taxi_zone_area_share"] == pytest.approx(0.4) + assert not bool(zone["primary_income_classification_eligible"]) + assert zone["income_group"] == "unclassified" + assert zone["income_group_all_zone_area_allocation_sensitivity"] == "high_income_area" + assert diagnostics["classified_zone_rows"] == 0 + + +def test_trip_summary_counts_only_actual_nonresidential_zones(tmp_path: Path) -> None: + zone_income = pd.DataFrame( + { + "location_id": [1, 2, 3], + "taxi_zone_name": ["Low", "High", "Airport"], + "taxi_borough": ["Fixture"] * 3, + "income_group": [ + "low_income_area", + "high_income_area", + "unclassified", + ], + "income_group_all_zone_area_allocation_sensitivity": [ + "low_income_area", + "high_income_area", + "high_income_area", + ], + "primary_income_classification_eligible": [True, True, False], + "grouped_median_household_income_usd": [50_000.0, 100_000.0, 120_000.0], + "grouped_median_top_coded": [False, False, False], + "citywide_grouped_median_threshold_usd": [75_000.0] * 3, + "nta_covered_area_share": [1.0, 1.0, 1.0], + "dominant_nta2020": ["RESLOW", "RESHIGH", "AIRPORT"], + "dominant_nta_name": ["Low", "High", "Airport"], + "dominant_nta_type": ["0", "0", "8"], + "dominant_nta_residential_eligible": [True, True, False], + "residential_intersection_area_m2": [100.0, 100.0, 5.0], + "residential_taxi_zone_area_share": [1.0, 1.0, 0.05], + "residential_nta_count": [1, 1, 1], + "area_allocated_residential_households": [100.0, 100.0, 5.0], + ESTIMATE_COLUMNS[0]: [100.0, 100.0, 5.0], + } + ) + rows = [] + for hour in range(24): + for location_id, trips in ((1, 10), (2, 20), (3, 30)): + rows.append( + { + "service_date": date(2024, 1, 1), + "hour": hour, + "zone_id": str(location_id), + "trip_count": trips, + } + ) + panel = tmp_path / "panel.parquet" + pd.DataFrame(rows).to_parquet(panel, index=False) + + _zone, _daily, _monthly, summary = income_trip_descriptions( + [panel], + zone_income, + NYCIncomeConfig( + start_date=date(2024, 1, 1), + end_date=date(2024, 1, 1), + ), + ) + + assert summary["coverage"]["dominant_nonresidential_panel_zones"] == 1 + assert summary["coverage"]["dominant_nonresidential_published_completed_trips"] == 720 + assert summary["conservation"]["primary_nonresidential_classified_zones"] == 0 + sensitivity = summary["sensitivity"]["all_zone_area_allocation"] + assert sensitivity["dominant_nonresidential_zones_classified"] == 1 + assert sensitivity[ + "dominant_nonresidential_classified_published_completed_trips" + ] == 720 + + +def test_income_bundle_is_ecological_atomic_portable_and_conserving(tmp_path: Path) -> None: + paths, config = _fixture(tmp_path) + output = tmp_path / "artifacts/nyc_full/income" + + artifacts = write_nyc_income_bundle( + paths["taxi"], + paths["nta"], + paths["tract"], + paths["acs"], + paths["panel_dir"], + paths["manifest"], + output, + project_root=tmp_path, + config=config, + ) + + assert all(path.is_file() for path in artifacts.paths()) + assert not (output / "NYC_INCOME_INCOMPLETE.json").exists() + manifest = json.loads(artifacts.manifest_path.read_text(encoding="utf-8")) + assert manifest["evidence_label"] == INCOME_EVIDENCE_LABEL + assert manifest["causal_claim"] is False + assert manifest["checks"]["median_of_medians_used"] is False + assert manifest["checks"]["household_distribution_conserved"] is True + assert manifest["checks"]["dominant_nonresidential_primary_unclassified"] is True + assert manifest["checks"]["all_zone_classification_is_sensitivity_only"] is True + assert all(not Path(entry["path"]).is_absolute() for entry in manifest["files"]) + assert all(not Path(entry["path"]).is_absolute() for entry in manifest["inputs"]) + panel_inputs = [ + entry for entry in manifest["inputs"] if entry["role"] == "nyc_full_zone_time_panel" + ] + assert len(panel_inputs) == 1 + assert panel_inputs[0]["path"] == str(paths["panel"].relative_to(tmp_path)) + assert panel_inputs[0]["sha256"] == sha256_file(paths["panel"]) + summary = json.loads(artifacts.summary_path.read_text(encoding="utf-8")) + assert summary["conservation"]["zone_trip_sum"] == 1_440 + assert summary["conservation"]["passes"] is True + assert summary["coverage"]["classified_trip_coverage"] == 1.0 + assert summary["causal_claim"] is False + assert summary["conservation"]["primary_nonresidential_classified_zones"] == 0 + assert summary["sensitivity"]["all_zone_area_allocation"]["primary_result"] is False + assert set(summary["sensitivity"]["all_zone_area_allocation"]["groups"]) == { + "high_income_area", + "low_income_area", + "unclassified", + } + assert summary["classification_uncertainty"]["zone_level_margin_of_error_propagated"] is False + limitations = " ".join(summary["limitations"]) + assert "ecological" in limitations + assert "Neither income effects" in limitations + monthly = pd.read_csv(artifacts.monthly_path) + assert set(monthly["income_group"]) == {"low_income_area", "high_income_area"} + assert int(monthly["published_completed_trips"].sum()) == 1_440 + + paths["panel"].write_bytes(paths["panel"].read_bytes() + b"post-bundle-tamper") + assert sha256_file(paths["panel"]) != panel_inputs[0]["sha256"] + + +def test_income_bundle_leaves_marker_on_source_tamper(tmp_path: Path) -> None: + paths, config = _fixture(tmp_path) + paths["acs"].write_text(paths["acs"].read_text(encoding="utf-8") + "\n", encoding="utf-8") + output = tmp_path / "artifacts/nyc_full/income" + + with pytest.raises(ValueError, match="SHA-256"): + write_nyc_income_bundle( + paths["taxi"], + paths["nta"], + paths["tract"], + paths["acs"], + paths["panel_dir"], + paths["manifest"], + output, + project_root=tmp_path, + config=config, + ) + assert (output / "NYC_INCOME_INCOMPLETE.json").is_file() + assert not (output / "manifest.json").exists() + + +def test_income_bundle_rejects_stale_panel_lineage(tmp_path: Path) -> None: + paths, config = _fixture(tmp_path) + paths["panel"].write_bytes(paths["panel"].read_bytes() + b"tamper") + output = tmp_path / "artifacts/nyc_full/income" + + with pytest.raises(ValueError, match="lineage mismatch"): + write_nyc_income_bundle( + paths["taxi"], + paths["nta"], + paths["tract"], + paths["acs"], + paths["panel_dir"], + paths["manifest"], + output, + project_root=tmp_path, + config=config, + ) + assert (output / "NYC_INCOME_INCOMPLETE.json").is_file() + assert not (output / "manifest.json").exists() + + +def test_income_bundle_rejects_parent_traversal_in_source_manifest(tmp_path: Path) -> None: + paths, config = _fixture(tmp_path) + manifest = json.loads(paths["manifest"].read_text(encoding="utf-8")) + manifest["files"][0]["path"] = "../outside.parquet" + paths["manifest"].write_text(json.dumps(manifest), encoding="utf-8") + output = tmp_path / "artifacts/nyc_full/income" + + with pytest.raises(ValueError, match="must not contain"): + write_nyc_income_bundle( + paths["taxi"], + paths["nta"], + paths["tract"], + paths["acs"], + paths["panel_dir"], + paths["manifest"], + output, + project_root=tmp_path, + config=config, + ) + assert (output / "NYC_INCOME_INCOMPLETE.json").is_file() + assert not (output / "manifest.json").exists() + + +def test_acs_distribution_total_mismatch_fails_closed(tmp_path: Path) -> None: + paths, config = _fixture(tmp_path) + acs = pd.read_csv(paths["acs"], sep="|") + acs.loc[0, ESTIMATE_COLUMNS[0]] += 1 + acs.to_csv(paths["acs"], sep="|", index=False) + invalid_config = NYCIncomeConfig( + expected_taxi_sha256=config.expected_taxi_sha256, + expected_nta_sha256=config.expected_nta_sha256, + expected_tract_to_nta_sha256=config.expected_tract_to_nta_sha256, + expected_acs_sha256=sha256_file(paths["acs"]), + expected_taxi_features=2, + expected_nta_features=2, + expected_tract_rows=2, + expected_acs_rows=2, + taxi_source_crs="EPSG:4326", + nta_source_crs="EPSG:4326", + start_date=date(2024, 1, 1), + end_date=date(2024, 1, 2), + ) + + with pytest.raises(ValueError, match="totals"): + aggregate_acs_b19001_to_nta( + paths["tract"], + paths["acs"], + ["BX0001", "BX0002"], + invalid_config, + ) diff --git a/CasualLab/tests/test_nyc_simulation.py b/CasualLab/tests/test_nyc_simulation.py new file mode 100644 index 0000000000000000000000000000000000000000..a0a968faca27cda48d9993f6253321fc4d3109b8 --- /dev/null +++ b/CasualLab/tests/test_nyc_simulation.py @@ -0,0 +1,392 @@ +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +import pytest + +from casuallab import nyc_simulation as nyc_simulation_module +from casuallab.config import SimulationConfig +from casuallab.data import sha256_file +from casuallab.nyc_simulation import ( + ANCHOR_EVIDENCE_LABEL, + CAUSAL_ASSUMPTION_FIELDS, + NYCSimulationAnchorSettings, + build_nyc_simulation_anchor, +) +from casuallab.simulator import simulate_market + + +def _write_json(path: Path, payload: object) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + json.dumps(payload, indent=2, sort_keys=True, allow_nan=False) + "\n", + encoding="utf-8", + ) + + +def _entry(path: Path, root: Path) -> dict[str, object]: + return { + "path": str(path.relative_to(root)), + "bytes": path.stat().st_size, + "sha256": sha256_file(path), + } + + +def _declared_digest(entries: list[dict[str, object]]) -> str: + canonical = json.dumps( + [ + { + "path": str(entry["path"]), + "bytes": int(entry["bytes"]), + "sha256": str(entry["sha256"]), + } + for entry in entries + ], + sort_keys=True, + separators=(",", ":"), + ).encode() + return hashlib.sha256(canonical).hexdigest() + + +def write_nyc_calibration_test_bundle( + tmp_path: Path, *, calibration_schema: str = "1.0.0" +) -> dict[str, Path]: + source_file = tmp_path / "data" / "completed_trip_input.txt" + source_file.parent.mkdir(parents=True) + source_file.write_text("immutable-source\n", encoding="utf-8") + source_entries = [_entry(source_file, tmp_path)] + source_manifest = tmp_path / "data" / "manifest.json" + _write_json( + source_manifest, + { + "schema_version": "1.0.0", + "config": { + "source": "nyc_hvfhv", + "mode": "full", + "project_root": ".", + "manifest_path": "data/manifest.json", + "panel_frequency": "1h", + "complete_panel_grid": True, + "nyc_year": 2024, + "nyc_months": [1], + }, + "metadata": { + "evidence_label": "descriptive_real_data", + "causal_claim": False, + "full_month_processing": { + "complete_calendar_coverage": True, + "configured_date_hours": 744, + "observed_date_hours": 744, + "row_conservation": {"passes": True}, + }, + }, + "files": source_entries, + }, + ) + lineage = { + "path": "data/manifest.json", + "sha256": sha256_file(source_manifest), + "entries": len(source_entries), + "declared_file_set_sha256": _declared_digest(source_entries), + "hashes_recomputed": True, + "queried_files_listed": True, + "scope_is_full_nyc_descriptive": True, + "mismatches": [], + "all_valid": True, + } + + output = tmp_path / "artifacts" / "calibration_network" + output.mkdir(parents=True) + temporal = output / "temporal_autocorrelation.csv" + temporal.write_text( + ( + "lag_hours,exact_lag_support_pairs,support_share," + "pooled_trip_count_correlation,within_zone_centered_correlation," + "evidence_label,interpretation_warning\n" + "1,1486,1.0,0.8,0.7,descriptive_real_data," + "Observed exact-lag association; not a causal persistence parameter.\n" + "24,1440,1.0,0.6,0.5,descriptive_real_data," + "Observed exact-lag association; not a causal persistence parameter.\n" + ), + encoding="utf-8", + ) + calibration = output / "calibration.json" + checks = { + "graph_conserves_od": True, + "od_conserves_clean": True, + "od_counts_positive": True, + "od_keys_unique": True, + "raw_equals_clean": True, + "raw_rows_declared": True, + "source_manifest_valid": True, + "variance_trip_sum_conserves": True, + "zone_conserves_clean": True, + "zone_keys_unique": True, + } + _write_json( + calibration, + { + "schema_version": calibration_schema, + "bundle_valid": True, + "evidence_label": "descriptive_real_data", + "causal_claim": False, + "scope": { + "source": "nyc_hvfhv", + "population_claim": False, + "unit": "published_completed_trip_record_and_pickup_zone_hour", + "pickup_min": "2024-01-01T00:00:00", + "pickup_max": "2024-01-31T23:59:59", + }, + "checks": checks, + "conservation": { + "raw_rows_declared": 7440, + "clean_rows": 7440, + "zone_trip_sum": 7440, + "od_trip_sum": 7440, + "zones": 2, + "periods": 744, + "zone_rows": 1488, + }, + "trip_level_descriptive_moments": { + "trip_rows": 7440, + "fare": { + "mean": 20.0, + "evidence_label": "descriptive_real_data", + }, + "request_to_pickup_wait_minutes": { + "available": True, + "mean": 4.5, + "p50": 4.0, + "evidence_label": "descriptive_real_data", + }, + }, + "zone_hour_variance_decomposition": { + "evidence_label": "descriptive_real_data", + "zones": 2, + "periods": 744, + "panel_cells": 1488, + "occupied_cells": 1400, + "total_completed_trips": 7440, + "mean_completed_trips_per_zone_hour": 5.0, + "between_zone_component": 4.0, + "between_hour_of_day_component": 1.0, + "total_cell_variance": 10.0, + "icc_like_between_zone_share": 0.4, + "between_hour_of_day_share": 0.1, + }, + "temporal_associations": { + "evidence_label": "descriptive_real_data", + "file": "temporal_autocorrelation.csv", + "lags_hours": [1, 24], + }, + "provenance": {"source_data_manifest": lineage}, + }, + ) + bundle_manifest = output / "manifest.json" + _write_json( + bundle_manifest, + { + "schema_version": "1.0.0", + "evidence_label": "descriptive_real_data", + "causal_claim": False, + "portable_paths": True, + "source_data_manifest": lineage, + "files": [ + _entry(calibration, output), + _entry(temporal, output), + ], + }, + ) + return { + "root": tmp_path, + "source_file": source_file, + "source_manifest": source_manifest, + "calibration": calibration, + "bundle_manifest": bundle_manifest, + } + + +def test_derives_only_observable_initializers_and_preserves_assumptions( + tmp_path: Path, +) -> None: + paths = write_nyc_calibration_test_bundle(tmp_path) + template = SimulationConfig( + base_demand=80.0, + base_supply=40.0, + direct_demand_effect=0.31, + direct_supply_effect=0.27, + spillover_strength=0.19, + persistence=0.41, + rider_substitution=0.17, + driver_mobility=0.23, + rider_value=35.0, + operating_cost_per_trip=11.0, + wait_disutility_per_minute=0.8, + ) + anchor = build_nyc_simulation_anchor( + paths["calibration"], + project_root=tmp_path, + settings=NYCSimulationAnchorSettings( + target_n_zones=2, + target_n_periods=168, + seed=99, + ), + assumption_template=template, + ) + + config = anchor["simulation_config"] + assert anchor["evidence_label"] == ANCHOR_EVIDENCE_LABEL + assert anchor["causal_claim"] is False + assert anchor["integrity"]["all_valid"] is True + assert anchor["integrity"]["bundle_files_verified"] == 2 + assert anchor["integrity"]["source_files_verified"] == 1 + assert anchor["target_panel"]["observed"]["panel_cells"] == 1488 + assert anchor["target_panel"]["simulation"]["panel_cells"] == 336 + assert anchor["target_panel"]["sample_scaling"]["cell_fraction"] == pytest.approx( + 336 / 1488 + ) + assert anchor["target_panel"]["sample_scaling"]["selection_performed"] is False + + assert config["n_zones"] == 2 + assert config["n_periods"] == 168 + assert config["periods_per_day"] == 24 + assert config["base_demand"] > 5.0 + assert config["base_supply"] / config["base_demand"] == pytest.approx(0.5) + assert config["base_fare"] == pytest.approx(20.0) + assert config["base_wait_minutes"] > 0 + assert config["zone_heterogeneity_sd"] >= 0 + assert config["time_pattern_strength"] >= 0 + assert config["seed"] == 99 + assert config["design"]["seed"] == 100 + control_validation = anchor["control_path_scale_validation"] + assert control_validation[ + "target_mean_published_completed_trips_per_zone_hour" + ] == pytest.approx(5.0) + assert control_validation[ + "achieved_simulated_control_completed_trips" + ] == pytest.approx(5.0) + assert control_validation["calibration_error"] == pytest.approx(0.0, abs=1e-10) + assert control_validation[ + "achieved_simulated_control_mean_wait_minutes" + ] == pytest.approx(4.5) + assert control_validation["wait_calibration_error"] == pytest.approx(0.0, abs=1e-10) + assert control_validation["achieved_between_zone_variance_share"] == pytest.approx( + 0.4, abs=0.01 + ) + assert control_validation[ + "achieved_between_hour_of_day_variance_share" + ] == pytest.approx(0.1, abs=0.01) + assert control_validation["broad_moment_match_passed"] is True + assert control_validation["causal_claim"] is False + + for field in CAUSAL_ASSUMPTION_FIELDS: + assert config[field] == template.to_dict()[field] + assert anchor["field_provenance"]["explicit_assumptions"][field][ + "evidence_label" + ] == "explicit_assumption" + assert anchor["field_provenance"]["partition_complete"] is True + assert anchor["field_provenance"]["explicit_assumptions"]["seed"]["source"] == ( + "NYCSimulationAnchorSettings.seed" + ) + assert "NYCSimulationAnchorSettings.seed" in anchor["field_provenance"][ + "explicit_assumptions" + ]["design"]["source"] + assert anchor["observable_anchor"]["temporal_associations"][0][ + "assigned_to_simulator_persistence" + ] is False + json.dumps(anchor, allow_nan=False) + + +def test_rejects_calibration_tampering_before_derivation(tmp_path: Path) -> None: + paths = write_nyc_calibration_test_bundle(tmp_path) + original = paths["calibration"].read_text(encoding="utf-8") + tampered = original.replace('"mean": 20.0', '"mean": 21.0', 1) + assert len(tampered.encode()) == len(original.encode()) + paths["calibration"].write_text(tampered, encoding="utf-8") + + with pytest.raises(ValueError, match="SHA-256 mismatch"): + build_nyc_simulation_anchor(paths["calibration"], project_root=tmp_path) + + +def test_rejects_unsupported_schema_even_when_manifest_hash_matches( + tmp_path: Path, +) -> None: + paths = write_nyc_calibration_test_bundle( + tmp_path, calibration_schema="2.0.0" + ) + + with pytest.raises(ValueError, match="unsupported schema_version"): + build_nyc_simulation_anchor(paths["calibration"], project_root=tmp_path) + + +def test_rejects_source_file_tampering_through_full_hash_chain(tmp_path: Path) -> None: + paths = write_nyc_calibration_test_bundle(tmp_path) + tampered = bytearray(paths["source_file"].read_bytes()) + tampered[0] ^= 1 + paths["source_file"].write_bytes(tampered) + + with pytest.raises(ValueError, match="source-data manifest SHA-256 mismatch"): + build_nyc_simulation_anchor(paths["calibration"], project_root=tmp_path) + + +def test_control_path_broad_moment_gate_fails_closed(tmp_path: Path) -> None: + paths = write_nyc_calibration_test_bundle(tmp_path) + + with pytest.raises(ValueError, match="control-path broad-moment gate failed"): + build_nyc_simulation_anchor( + paths["calibration"], + project_root=tmp_path, + settings=NYCSimulationAnchorSettings( + target_n_zones=1, + target_n_periods=168, + ), + ) + + +def test_fast_control_specialization_matches_public_simulator_control() -> None: + config = SimulationConfig(n_zones=3, n_periods=48, seed=3811) + actual = nyc_simulation_module._simulated_control_moments(config) + control = simulate_market(config).counterfactuals["control"] + trips = control["trips"].astype(float) + grand_mean = float(trips.mean()) + total_variance = float(trips.var(ddof=0)) + + def share(group: str) -> float: + grouped = control.groupby(group, observed=True)["trips"].agg(["size", "mean"]) + component = float( + (grouped["size"] * (grouped["mean"] - grand_mean) ** 2).sum() + / len(control) + ) + return component / total_variance + + assert actual == pytest.approx( + { + "mean_completed_trips": grand_mean, + "mean_wait_minutes": float(control["wait_minutes"].mean()), + "between_zone_share": share("zone_id"), + "between_hour_of_day_share": share("hour"), + }, + rel=1e-12, + abs=1e-12, + ) + + +def test_causal_fields_never_appear_as_empirically_derived(tmp_path: Path) -> None: + paths = write_nyc_calibration_test_bundle(tmp_path) + anchor = build_nyc_simulation_anchor(paths["calibration"], project_root=tmp_path) + + derived = anchor["field_provenance"]["derived_initializers"] + assumptions = anchor["field_provenance"]["explicit_assumptions"] + assert set(CAUSAL_ASSUMPTION_FIELDS).isdisjoint(derived) + assert set(CAUSAL_ASSUMPTION_FIELDS).issubset(assumptions) + assert ( + anchor["causal_parameter_assumptions"]["status"] + == "explicit_assumptions_not_estimated_from_nyc_trip_records" + ) + assert anchor["causal_parameter_assumptions"][ + "calibration_embedded_template_assumptions_used" + ] is False + assert anchor["simulation_config"]["persistence"] == SimulationConfig().persistence + assert "do not identify treatment response" in anchor["warnings"][0] diff --git a/CasualLab/tests/test_nyc_weather.py b/CasualLab/tests/test_nyc_weather.py new file mode 100644 index 0000000000000000000000000000000000000000..13b4fb206a081ec6b2823cf89be950f6f02d3966 --- /dev/null +++ b/CasualLab/tests/test_nyc_weather.py @@ -0,0 +1,197 @@ +import hashlib +import json +from datetime import date +from pathlib import Path + +import pandas as pd +import pytest + +from casuallab.data import sha256_file +from casuallab.nyc_weather import ( + WEATHER_EVIDENCE_LABEL, + NYCWeatherConfig, + normalize_noaa_daily_weather, + weather_demand_associations, + write_nyc_weather_bundle, +) + + +def _raw_weather(path: Path) -> NYCWeatherConfig: + frame = pd.DataFrame( + { + "STATION": ["USW00094728", "USW00094728"], + "DATE": ["2024-01-01", "2024-01-02"], + "AWND": [1.5, None], + "AWND_ATTRIBUTES": [",,W", ""], + "PRCP": [0.0, 12.0], + "PRCP_ATTRIBUTES": [",,W,2400", ",,W,2400"], + "SNOW": [0.0, 5.0], + "SNOW_ATTRIBUTES": [",,W,2400", ",,W,2400"], + "SNWD": [0.0, 0.0], + "SNWD_ATTRIBUTES": [",,W,2400", ",,W,2400"], + "TMAX": [8.0, 1.0], + "TMAX_ATTRIBUTES": [",,W", ",,W"], + "TMIN": [2.0, -3.0], + "TMIN_ATTRIBUTES": [",,W", ",,W"], + } + ) + frame.to_csv(path, index=False) + digest = hashlib.sha256(path.read_bytes()).hexdigest() + return NYCWeatherConfig( + start_date=date(2024, 1, 1), + end_date=date(2024, 1, 2), + expected_rows=2, + expected_sha256=digest, + ) + + +def _panel(path: Path) -> pd.DataFrame: + rows = [] + for day, base in ((date(2024, 1, 1), 10), (date(2024, 1, 2), 15)): + for hour in range(24): + for zone in ("1", "2"): + rows.append( + { + "service_date": day, + "hour": hour, + "zone_id": zone, + "trip_count": base + hour + int(zone), + } + ) + frame = pd.DataFrame(rows) + frame.to_parquet(path, index=False) + return frame + + +def _data_manifest(root: Path, panel_path: Path, trip_sum: int) -> Path: + manifest = root / "data/nyc_full/manifest.json" + manifest.parent.mkdir(parents=True, exist_ok=True) + relative = panel_path.relative_to(root) + manifest.write_text( + json.dumps( + { + "config": {"source": "nyc_hvfhv", "mode": "full"}, + "metadata": { + "evidence_label": "descriptive_real_data", + "causal_claim": False, + "full_month_processing": { + "row_conservation": {"zone_time_trip_sum": trip_sum} + }, + }, + "files": [ + { + "path": str(relative), + "bytes": panel_path.stat().st_size, + "sha256": sha256_file(panel_path), + } + ], + } + ), + encoding="utf-8", + ) + return manifest + + +def test_normalize_noaa_weather_preserves_measurement_flags_and_definitions( + tmp_path: Path, +) -> None: + raw = tmp_path / "weather.csv" + config = _raw_weather(raw) + weather = normalize_noaa_daily_weather(raw, config) + + assert list(weather["service_date"]) == [date(2024, 1, 1), date(2024, 1, 2)] + assert weather["temperature_midrange_c"].tolist() == [5.0, -1.0] + assert weather["wet_day"].tolist() == [False, True] + assert weather["snow_day"].tolist() == [False, True] + assert weather["freezing_day"].tolist() == [False, True] + assert weather["average_wind_mps"].isna().sum() == 1 + assert set(weather["evidence_label"]) == {WEATHER_EVIDENCE_LABEL} + assert not weather["causal_claim"].any() + + +def test_noaa_weather_hash_and_calendar_fail_closed(tmp_path: Path) -> None: + raw = tmp_path / "weather.csv" + config = _raw_weather(raw) + raw.write_text(raw.read_text(encoding="utf-8") + "\n", encoding="utf-8") + with pytest.raises(ValueError, match="SHA-256"): + normalize_noaa_daily_weather(raw, config) + + +def test_weather_demand_associations_are_descriptive_and_conserve_trips( + tmp_path: Path, +) -> None: + raw = tmp_path / "weather.csv" + config = _raw_weather(raw) + weather = normalize_noaa_daily_weather(raw, config) + panel_path = tmp_path / "panel.parquet" + panel = _panel(panel_path) + + daily, hourly, summary = weather_demand_associations( + [panel_path], weather, config + ) + + assert len(daily) == 2 + assert len(hourly) == 24 + assert summary["causal_claim"] is False + assert summary["coverage"]["wet_days"] == 1 + assert summary["coverage"]["dry_days"] == 1 + assert summary["conservation"]["daily_trip_sum"] == int(panel["trip_count"].sum()) + assert summary["associations"][ + "wet_minus_dry_mean_daily_published_completed_trips" + ] > 0 + assert "confounded" in " ".join(summary["limitations"]) + + +def test_weather_bundle_verifies_panel_lineage_and_publishes_atomically( + tmp_path: Path, +) -> None: + raw = tmp_path / "data/nyc_weather/raw/noaa.csv" + raw.parent.mkdir(parents=True) + config = _raw_weather(raw) + panel_dir = tmp_path / "data/nyc_full/panel/zone_time" + panel_dir.mkdir(parents=True) + panel_path = panel_dir / "part.parquet" + panel = _panel(panel_path) + manifest = _data_manifest(tmp_path, panel_path, int(panel["trip_count"].sum())) + output = tmp_path / "artifacts/nyc_full/weather" + + artifacts = write_nyc_weather_bundle( + raw, + panel_dir, + manifest, + output, + project_root=tmp_path, + config=config, + ) + + assert all(path.is_file() for path in artifacts.paths()) + assert not (output / "NYC_WEATHER_INCOMPLETE.json").exists() + payload = json.loads(artifacts.manifest_path.read_text(encoding="utf-8")) + assert payload["evidence_label"] == WEATHER_EVIDENCE_LABEL + assert payload["checks"]["trip_conservation"] is True + assert all(not Path(entry["path"]).is_absolute() for entry in payload["files"]) + + +def test_weather_bundle_leaves_marker_when_panel_hash_is_stale(tmp_path: Path) -> None: + raw = tmp_path / "data/nyc_weather/raw/noaa.csv" + raw.parent.mkdir(parents=True) + config = _raw_weather(raw) + panel_dir = tmp_path / "data/nyc_full/panel/zone_time" + panel_dir.mkdir(parents=True) + panel_path = panel_dir / "part.parquet" + panel = _panel(panel_path) + manifest = _data_manifest(tmp_path, panel_path, int(panel["trip_count"].sum())) + panel_path.write_bytes(panel_path.read_bytes() + b"tamper") + output = tmp_path / "artifacts/nyc_full/weather" + + with pytest.raises(ValueError, match="lineage mismatch"): + write_nyc_weather_bundle( + raw, + panel_dir, + manifest, + output, + project_root=tmp_path, + config=config, + ) + assert (output / "NYC_WEATHER_INCOMPLETE.json").is_file() + assert not (output / "manifest.json").exists() diff --git a/CasualLab/tests/test_policy.py b/CasualLab/tests/test_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..d135518bd68758d8606ab3054df39b40869db522 --- /dev/null +++ b/CasualLab/tests/test_policy.py @@ -0,0 +1,44 @@ +import numpy as np +import pandas as pd +import pytest + +from casuallab.policy import ( + PolicyConfig, + allocate_ranked, + evaluate_budget_policies, + generate_policy_learning_sample, + run_policy_benchmark, +) + + +def test_allocate_ranked_obeys_budget_and_value_order() -> None: + allocation = allocate_ranked([1.0, 4.0, 2.0], [2.0, 2.0, 2.0], budget=4.0) + np.testing.assert_array_equal(allocation, [0.0, 1.0, 1.0]) + assert float(np.dot(allocation, [2.0, 2.0, 2.0])) <= 4.0 + + +def test_policy_benchmark_is_deterministic_and_budget_feasible() -> None: + config = PolicyConfig(budget=500.0, model_trees=20, model_replicates=2, seed=71) + first = run_policy_benchmark(config, n_train=300, n_holdout=180) + second = run_policy_benchmark(config, n_train=300, n_holdout=180) + pd.testing.assert_frame_equal(first, second) + assert set(first["policy"]) == { + "no_treatment", + "random", + "uniform", + "rule_based", + "model_based", + } + assert (first["budget_spent"] <= first["budget"] + 1e-8).all() + assert set(first["evidence_type"]) == {"semi_synthetic_causal_holdout"} + + +def test_policy_evaluation_rejects_training_holdout_seed_overlap() -> None: + sample = generate_policy_learning_sample(50, seed=11) + with pytest.raises(ValueError, match="disjoint"): + evaluate_budget_policies( + sample, + sample.copy(), + PolicyConfig(model_trees=10, model_replicates=2), + ) + diff --git a/CasualLab/tests/test_real_nyc_sample_diagnostics.py b/CasualLab/tests/test_real_nyc_sample_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..664cb427a7054c7db34c08cb69897da1fe8ae9f0 --- /dev/null +++ b/CasualLab/tests/test_real_nyc_sample_diagnostics.py @@ -0,0 +1,38 @@ +"""Verify NYC HVFHV 10,000-trip sample diagnostics and CasualLab claim boundary.""" +from __future__ import annotations + +import json +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +CORE_SRC = ROOT.parent / "packages" / "oeq-core" / "src" +if CORE_SRC.exists() and str(CORE_SRC) not in sys.path: + sys.path.insert(0, str(CORE_SRC)) + +from oeq_core import ClaimBoundary, EvidenceGrade, validate_claim_boundary # noqa: E402 + + +class TestRealNycSampleDiagnostics(unittest.TestCase): + def test_nyc_hvfhv_10000_trip_diagnostics(self) -> None: + diag = json.loads((ROOT / "data" / "nyc_sample" / "diagnostics.json").read_text(encoding="utf-8")) + self.assertEqual(int(diag["row_count"]), 10000) + self.assertEqual(diag["sources"], ["nyc_hvfhv"]) + self.assertEqual(int(diag["validity"]["duplicate_trip_id_count"]), 0) + self.assertEqual(int(diag["validity"]["missing_trip_id_count"]), 0) + self.assertEqual(int(diag["validity"]["negative_trip_miles_count"]), 0) + self.assertEqual(int(diag["validity"]["nonpositive_trip_seconds_count"]), 0) + self.assertEqual(diag["suppression_or_nonreporting"]["pickup_indicator_status"], "unavailable") + + boundary = ClaimBoundary( + project_slug="casuallab", + grade=EvidenceGrade.SYNTHETIC_SMOKE, + allows_causal_language=False, + allows_live_profitability_claim=False, + ) + self.assertEqual(validate_claim_boundary(boundary), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/CasualLab/tests/test_reporting.py b/CasualLab/tests/test_reporting.py new file mode 100644 index 0000000000000000000000000000000000000000..56c4aa741df406431530dc2b078e21886e8926d4 --- /dev/null +++ b/CasualLab/tests/test_reporting.py @@ -0,0 +1,268 @@ +from pathlib import Path + +import pandas as pd +import pytest + +from casuallab.reporting import ( + _validate_policy_provenance, + choose_recommendation, + generate_decision_appendix, +) + + +def _safe_benchmark(values: dict[str, list[object]]) -> pd.DataFrame: + frame = pd.DataFrame(values) + rows = len(frame) + defaults: dict[str, object] = { + "identified": True, + "inference_valid": True, + "fit_complete": True, + "applicable": True, + "attempted_fits": 10, + "successful_fits": 10, + "confidence_level": 0.95, + } + for column, value in defaults.items(): + if column not in frame: + frame[column] = [value] * rows + return frame + + +def _safe_policy() -> pd.DataFrame: + policies = ["no_treatment", "random", "uniform", "rule_based", "model_based"] + rows = len(policies) + return pd.DataFrame( + { + "policy": policies, + "expected_incremental_outcome": [0.0, 3.0, 3.5, 4.0, 5.0], + "incremental_outcome_se": [0.0, 0.3, 0.3, 0.35, 0.4], + "incremental_outcome_p10": [0.0, 2.0, 2.4, 3.0, 4.0], + "budget_spent": [0.0, 100.0, 100.0, 100.0, 100.0], + "budget_efficiency": [float("nan"), 0.03, 0.035, 0.04, 0.05], + "budget_feasible": [True] * rows, + "evaluation_complete": [True] * rows, + "policy_eligible": [True] * rows, + "mean_model_instability": [0.0, 0.0, 0.0, 0.0, 0.1], + "decision_instability": [0.0, 0.0, 0.0, 0.0, 0.1], + "training_market_seeds": ["[1, 2]"] * rows, + "holdout_market_seeds": ["[3, 4]"] * rows, + "training_markets": [2] * rows, + "holdout_markets": [2] * rows, + "training_signal": ["randomized outcomes; no structural truth"] * rows, + "evaluation_engine": ["full simulator rerun"] * rows, + "planning_cost_basis": ["pre-treatment; no treated holdout"] * rows, + "target_estimand": ["full_horizon_incremental_trips"] * rows, + "target_population_id": ["two_markets"] * rows, + "n_zones": [4] * rows, + "n_periods": [12] * rows, + "weighting": ["paired holdout means"] * rows, + "simulation_config": ['{"n_zones":4}'] * rows, + "policy_config": ['{"budget":100}'] * rows, + "evidence_type": ["semi_synthetic_causal_holdout"] * rows, + } + ) + + +def test_policy_provenance_rejects_missing_or_spliced_policy_rows() -> None: + policy = _safe_policy() + with pytest.raises(ValueError, match="exactly one row"): + _validate_policy_provenance(policy.iloc[:-1]) + + spliced = policy.copy() + spliced.loc[spliced.index[-1], "holdout_market_seeds"] = "[3, 5]" + with pytest.raises(ValueError, match="differs across rows"): + _validate_policy_provenance(spliced) + + +def test_generated_report_uses_computed_results_and_labels_evidence(tmp_path: Path) -> None: + benchmark_path = tmp_path / "benchmark.csv" + policy_path = tmp_path / "policy.csv" + output_path = tmp_path / "report.md" + _safe_benchmark( + { + "design": ["individual", "geo_cluster"], + "estimator": ["difference_in_means", "cluster_robust"], + "target_estimand": ["market_total_effect", "market_total_effect"], + "bias": [0.5, 0.1], + "rmse": [0.05, 0.3], + "coverage": [0.7, 0.94], + "power": [0.9, 0.8], + "mean_std_error": [0.2, 0.3], + "information_cost": [2.0, 1.5], + "confidence_level": [0.95, 0.95], + "evidence_type": ["semi_synthetic_causal_monte_carlo"] * 2, + } + ).to_csv(benchmark_path, index=False) + _safe_policy().to_csv(policy_path, index=False) + + generate_decision_appendix( + benchmark_path, + output_path=output_path, + policy_path=policy_path, + target_estimand="market_total_effect", + ) + report = output_path.read_text(encoding="utf-8") + assert "geo_cluster" in report + assert "0.1000" in report + assert "semi-synthetic causal benchmark" in report + assert "Benchmark SHA-256" in report + + +def test_recommendation_uses_worst_case_not_easiest_scenario() -> None: + benchmark = _safe_benchmark( + { + "design": ["geo_cluster", "geo_cluster", "switchback", "switchback"], + "estimator": ["cluster_robust"] * 4, + "target_estimand": ["market_total_effect"] * 4, + "scenario": ["easy", "adverse", "easy", "adverse"], + "rmse": [0.10, 1.20, 0.40, 0.50], + "coverage": [0.95] * 4, + "power": [0.8] * 4, + "bias": [0.0] * 4, + } + ) + selected = choose_recommendation(benchmark, "market_total_effect") + assert selected["design"] == "switchback" + assert selected["scenario"] == "adverse" + + +def test_recommendation_requires_identification_across_every_declared_scenario() -> None: + benchmark = _safe_benchmark( + { + "design": ["geo_cluster", "geo_cluster", "switchback", "switchback"], + "estimator": ["cluster_robust"] * 4, + "target_estimand": ["market_total_effect"] * 4, + "scenario": ["none", "spillover", "none", "spillover"], + "identified": [True, False, True, True], + "inference_valid": [True] * 4, + "rmse": [0.05, float("nan"), 0.30, 0.35], + "coverage": [0.95, float("nan"), 0.94, 0.93], + "power": [0.9, float("nan"), 0.8, 0.8], + "bias": [0.0, float("nan"), 0.1, 0.1], + } + ) + selected = choose_recommendation(benchmark, "market_total_effect") + + assert selected["design"] == "switchback" + assert selected["declared_scenarios"] == 2 + + +def test_recommendation_refuses_partial_scenario_identification() -> None: + benchmark = _safe_benchmark( + { + "design": ["geo_cluster", "geo_cluster"], + "estimator": ["cluster_robust"] * 2, + "target_estimand": ["market_total_effect"] * 2, + "scenario": ["none", "spillover"], + "identified": [True, False], + "inference_valid": [True, True], + "rmse": [0.1, float("nan")], + "coverage": [0.95, float("nan")], + "power": [0.8, float("nan")], + "bias": [0.0, float("nan")], + } + ) + with pytest.raises(ValueError, match="full declared scenario set"): + choose_recommendation(benchmark, "market_total_effect") + + +def test_recommendation_conditional_mode_keeps_declaration_but_allows_exact_subset() -> None: + benchmark = _safe_benchmark( + { + "design": ["geo_cluster", "geo_cluster", "switchback", "switchback"], + "estimator": ["cluster_robust"] * 4, + "target_estimand": ["market_total_effect"] * 4, + "scenario": ["none", "spillover", "none", "spillover"], + "declared_scenario_set": ['["none","spillover"]'] * 4, + "declared_scenario_count": [2] * 4, + "rmse": [0.10, 0.50, 0.20, 0.30], + "coverage": [0.95] * 4, + "power": [0.8] * 4, + "bias": [0.0] * 4, + } + ) + exact_none = benchmark.loc[benchmark["scenario"] == "none"] + + with pytest.raises(ValueError, match="do not cover the declared scenario set"): + choose_recommendation(exact_none, "market_total_effect") + selected = choose_recommendation( + exact_none, + "market_total_effect", + require_declared_scenarios=False, + ) + + assert selected["design"] == "geo_cluster" + assert selected["recommendation_scope"] == "selected_scenario_conditional" + assert selected["declared_scenarios"] == 2 + assert selected["evaluated_scenarios"] == 1 + assert selected["unmatched_declared_scenarios"] == '["spillover"]' + + malformed = exact_none.copy() + malformed["declared_scenario_count"] = 1 + with pytest.raises(ValueError, match="scenario count is inconsistent"): + choose_recommendation( + malformed, + "market_total_effect", + require_declared_scenarios=False, + ) + + +def test_recommendation_excludes_incomplete_fit_ledger_candidates() -> None: + benchmark = _safe_benchmark( + { + "design": ["geo_cluster", "geo_cluster", "switchback", "switchback"], + "estimator": ["cluster_robust"] * 4, + "target_estimand": ["market_total_effect"] * 4, + "scenario": ["none", "adverse", "none", "adverse"], + "identified": [True] * 4, + "inference_valid": [True] * 4, + "fit_complete": [True, False, True, True], + "attempted_fits": [10] * 4, + "successful_fits": [10, 9, 10, 10], + "rmse": [0.05, 0.06, 0.30, 0.35], + "coverage": [0.95] * 4, + "power": [0.8] * 4, + "bias": [0.0] * 4, + } + ) + + selected = choose_recommendation(benchmark, "market_total_effect") + + assert selected["design"] == "switchback" + assert "complete identified fits" in selected["selection_rule"] + + +def test_recommendation_rejects_catastrophic_undercoverage() -> None: + benchmark = _safe_benchmark( + { + "design": ["geo_cluster", "switchback"], + "estimator": ["cluster_robust", "cluster_robust"], + "target_estimand": ["market_total_effect"] * 2, + "scenario": ["default", "default"], + "rmse": [0.01, 1.0], + "coverage": [0.0, 0.95], + "coverage_mcse": [0.0, 0.02], + "power": [1.0, 0.8], + "bias": [0.0, 0.1], + } + ) + + selected = choose_recommendation(benchmark, "market_total_effect") + + assert selected["design"] == "switchback" + + +def test_recommendation_requires_explicit_safety_ledger() -> None: + unsafe = pd.DataFrame( + { + "design": ["geo_cluster"], + "estimator": ["cluster_robust"], + "target_estimand": ["market_total_effect"], + "rmse": [0.1], + "coverage": [0.95], + "power": [0.8], + "bias": [0.0], + } + ) + with pytest.raises(ValueError, match="benchmark results missing columns"): + choose_recommendation(unsafe, "market_total_effect") diff --git a/CasualLab/tests/test_simulator.py b/CasualLab/tests/test_simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..940973d540310080462e3c458982629377c3d7af --- /dev/null +++ b/CasualLab/tests/test_simulator.py @@ -0,0 +1,312 @@ +from __future__ import annotations + +import json +from dataclasses import replace +from pathlib import Path + +import numpy as np +import pandas as pd + +from casuallab.config import DesignConfig, SimulationConfig, TreatmentVersion +from casuallab.simulator import simulate_market + + +def _small_config(**overrides: object) -> SimulationConfig: + base = SimulationConfig( + n_zones=4, + n_periods=16, + individuals_per_cell=80, + seed=123, + design=DesignConfig(name="geo_cluster", cluster_size=1), + ) + return replace(base, **overrides) + + +def test_same_seed_reproduces_panel_assignment_and_truth() -> None: + config = _small_config() + first = simulate_market(config) + second = simulate_market(config) + + pd.testing.assert_frame_equal(first.panel, second.panel) + pd.testing.assert_frame_equal(first.assignment, second.assignment) + assert first.ground_truth.keys() == second.ground_truth.keys() + for key in first.ground_truth: + assert np.isclose( + first.ground_truth[key], + second.ground_truth[key], + equal_nan=True, + ) + assert first.metadata == second.metadata + + +def test_different_seed_changes_exogenous_market() -> None: + first = simulate_market(_small_config(seed=12)) + second = simulate_market(_small_config(seed=13)) + + assert not np.allclose(first.panel["baseline_demand"], second.panel["baseline_demand"]) + + +def test_no_effect_configuration_has_zero_trip_ground_truth() -> None: + config = _small_config( + direct_demand_effect=0.0, + direct_supply_effect=0.0, + spillover_strength=0.0, + rider_substitution=0.0, + driver_mobility=0.0, + persistence=0.0, + ) + result = simulate_market(config) + + for key in ( + "controlled_zone_direct_effect", + "market_total_effect", + "spillover_effect", + "short_run_effect", + "persistent_effect", + "cumulative_effect", + ): + assert np.isclose(result.ground_truth[key], 0.0, atol=1e-12) + assert np.isnan(result.ground_truth["direct_effect"]) + + +def test_substitution_and_driver_movement_reallocate_without_creating_mass() -> None: + result = simulate_market( + _small_config( + direct_demand_effect=0.0, + direct_supply_effect=0.0, + spillover_strength=0.0, + rider_substitution=0.30, + driver_mobility=0.25, + persistence=0.0, + ) + ) + by_period = result.panel.groupby("period_id") + + np.testing.assert_allclose( + by_period["latent_demand"].sum(), + by_period["baseline_demand"].sum(), + ) + np.testing.assert_allclose( + by_period["available_drivers"].sum(), + by_period["baseline_supply"].sum(), + ) + assert result.panel["rider_reallocation_signal"].abs().sum() > 0 + assert result.panel["driver_reallocation_signal"].abs().sum() > 0 + + +def test_canonical_truth_matches_structural_counterfactual_paths() -> None: + config = _small_config( + spillover_strength=0.08, + rider_substitution=0.03, + driver_mobility=0.04, + persistence=0.45, + ) + result = simulate_market(config) + control = result.counterfactuals["control"] + all_treated = result.counterfactuals["all_treated"] + all_treated_short = result.counterfactuals["all_treated_short_run"] + full_effect = all_treated["trips"].to_numpy() - control["trips"].to_numpy() + short_effect = all_treated_short["trips"].to_numpy() - control["trips"].to_numpy() + + assert np.isclose(result.ground_truth["market_total_effect"], full_effect.mean()) + assert np.isclose(result.ground_truth["cumulative_effect"], full_effect.sum()) + assert np.isclose(result.ground_truth["short_run_effect"], short_effect.mean()) + assert np.isclose( + result.ground_truth["persistent_effect"], (full_effect - short_effect).mean() + ) + assert result.ground_truth["persistent_effect"] > 0 + assert "realized_schedule_mean_effect" in result.ground_truth + assert result.metadata["ground_truth_definitions"]["market_total_effect"].startswith( + "all-zone" + ) + + +def test_no_cross_zone_path_has_zero_controlled_spillover() -> None: + result = simulate_market( + _small_config( + spillover_strength=0.0, + rider_substitution=0.0, + driver_mobility=0.0, + ) + ) + + assert np.isclose(result.ground_truth["spillover_effect"], 0.0, atol=1e-12) + # With no cross-zone pathways or persistence, the focal own-only contrast and + # the all-zone policy contrast are the same average cell effect. + assert np.isclose( + result.ground_truth["controlled_zone_direct_effect"], + result.ground_truth["market_total_effect"], + ) + assert result.metadata["itt_available"] is True + assert np.isclose( + result.ground_truth["intent_to_treat"], + result.ground_truth["market_total_effect"], + ) + + +def test_itt_is_unavailable_when_assignment_contrast_is_not_full_policy_contrast() -> None: + result = simulate_market( + _small_config( + spillover_strength=0.1, + rider_substitution=0.02, + driver_mobility=0.03, + persistence=0.2, + ) + ) + + assert result.metadata["itt_available"] is False + assert np.isnan(result.ground_truth["intent_to_treat"]) + assert np.isnan(result.ground_truth["treatment_on_treated"]) + assert result.metadata["ground_truth"]["intent_to_treat"] is None + json.dumps(result.metadata, allow_nan=False) + + +def test_budget_is_binding_without_rewriting_random_assignment() -> None: + unconstrained = simulate_market(_small_config(spillover_strength=0.12)) + constrained = simulate_market( + _small_config(spillover_strength=0.12, budget=250.0) + ) + + pd.testing.assert_series_equal( + unconstrained.assignment["assigned_treatment"], + constrained.assignment["assigned_treatment"], + ) + assert constrained.panel["treatment_cost"].sum() <= 250.0 + 1e-8 + assert constrained.metadata["budget_feasible"] + assert constrained.metadata["budget_scale"] < 1.0 + assert np.isclose( + constrained.ground_truth["controlled_zone_direct_effect"], + unconstrained.ground_truth["controlled_zone_direct_effect"], + ) + assert np.isclose( + constrained.ground_truth["spillover_effect"], + unconstrained.ground_truth["spillover_effect"], + ) + assert constrained.metadata["treatment_version"] == "bundled" + assert "factorial" in constrained.metadata["treatment_version_limitation"] + assert ( + constrained.assignment["treatment"] + <= constrained.assignment["planned_treatment"] + 1e-12 + ).all() + + +def test_treatment_versions_activate_only_the_declared_market_side() -> None: + common = dict( + direct_demand_effect=0.20, + direct_supply_effect=0.20, + spillover_strength=0.0, + rider_substitution=0.0, + driver_mobility=0.0, + persistence=0.0, + ) + rider = simulate_market( + _small_config(treatment_version=TreatmentVersion.RIDER_DISCOUNT, **common) + ) + driver = simulate_market( + _small_config(treatment_version=TreatmentVersion.DRIVER_INCENTIVE, **common) + ) + bundled = simulate_market( + _small_config(treatment_version=TreatmentVersion.BUNDLED, **common) + ) + + rider_treated = rider.panel["treatment"] > 0 + driver_treated = driver.panel["treatment"] > 0 + assert np.allclose( + rider.panel.loc[rider_treated, "available_drivers"], + rider.panel.loc[rider_treated, "baseline_supply"], + ) + assert np.allclose( + driver.panel.loc[driver_treated, "latent_demand"], + driver.panel.loc[driver_treated, "baseline_demand"], + ) + assert np.isclose(rider.panel["driver_incentive_cost"].sum(), 0.0) + assert np.isclose(driver.panel["rider_discount_cost"].sum(), 0.0) + assert bundled.panel["rider_discount_cost"].sum() > 0 + assert bundled.panel["driver_incentive_cost"].sum() > 0 + assert rider.metadata["treatment_version"] == "rider_discount" + assert driver.metadata["treatment_version"] == "driver_incentive" + + +def test_driver_incentive_dose_scales_supply_response_and_zero_has_no_effect() -> None: + common = dict( + treatment_version=TreatmentVersion.DRIVER_INCENTIVE, + direct_demand_effect=0.0, + direct_supply_effect=0.12, + spillover_strength=0.0, + rider_substitution=0.0, + driver_mobility=0.0, + persistence=0.0, + reference_incentive_per_driver=1.5, + ) + zero = simulate_market(_small_config(incentive_per_driver=0.0, **common)) + reference = simulate_market(_small_config(incentive_per_driver=1.5, **common)) + double = simulate_market(_small_config(incentive_per_driver=3.0, **common)) + + assert np.isclose(zero.ground_truth["market_total_effect"], 0.0, atol=1e-12) + assert reference.ground_truth["market_total_effect"] > 0 + assert double.ground_truth["market_total_effect"] > reference.ground_truth[ + "market_total_effect" + ] + assert zero.metadata["driver_incentive_response_scale"] == 0.0 + assert reference.metadata["driver_incentive_response_scale"] == 1.0 + assert double.metadata["driver_incentive_response_scale"] == 2.0 + + +def test_individual_design_exposes_continuous_saturation_for_regression() -> None: + config = _small_config( + design=DesignConfig(name="individual", treatment_probability=0.5) + ) + result = simulate_market(config) + + assert result.panel["assigned_treatment"].nunique() > 2 + assert result.panel["assigned_treatment"].between(0, 1).all() + assert set(result.panel["evidence_type"]) == {"semi_synthetic_causal"} + + +def test_supplied_schedule_is_validated_and_used() -> None: + config = _small_config(n_zones=2, n_periods=5) + assignment = pd.MultiIndex.from_product( + [range(5), range(2)], names=["period_id", "zone_id"] + ).to_frame(index=False) + assignment["assigned_treatment"] = (assignment["zone_id"] == 0).astype(float) + result = simulate_market(config, assignments=assignment) + + assert np.array_equal( + result.panel["assigned_treatment"], assignment["assigned_treatment"] + ) + assert (result.panel.loc[result.panel["zone_id"] == 1, "treatment"] == 0).all() + + +def test_truth_uses_same_washout_population_as_estimators() -> None: + config = _small_config( + design=DesignConfig( + name="switchback", + treatment_duration=3, + washout_periods=1, + ) + ) + result = simulate_market(config) + eligible = result.panel["analysis_eligible"].astype(bool).to_numpy() + control = result.counterfactuals["control"]["trips"].to_numpy() + policy = result.counterfactuals["all_treated"]["trips"].to_numpy() + full_effect = policy - control + + assert eligible.sum() < len(eligible) + assert np.isclose( + result.ground_truth["market_total_effect"], full_effect.mean() + ) + assert np.isclose( + result.ground_truth["analysis_population_market_total_effect"], + full_effect[eligible].mean(), + ) + assert result.metadata["analysis_rows"] == int(eligible.sum()) + assert result.metadata["target_population_id"].startswith("all_4_zones") + + +def test_committed_simulation_config_is_runnable() -> None: + config_path = Path(__file__).parents[1] / "configs" / "simulation.yaml" + config = SimulationConfig.from_yaml(config_path, section="simulation") + result = simulate_market(config) + + assert len(result.panel) == config.n_zones * config.n_periods + assert result.panel["analysis_eligible"].eq(1).all() diff --git a/CryptoFactors/.github/workflows/ci.yml b/CryptoFactors/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..cd2404c2190008d13f99b3dbeab22149b05c0658 --- /dev/null +++ b/CryptoFactors/.github/workflows/ci.yml @@ -0,0 +1,37 @@ +# Synced from open-economic-quant/CryptoFactors/.github/workflows/ci.yml by +# scripts/sync_ecosystem.py; edit it in the monorepo, not here. +name: CI + +on: + push: + branches: ["main"] + pull_request: + branches: ["main"] + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Python 3.12 + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.12" + cache: pip + cache-dependency-path: pyproject.toml + + - name: Install project with test dependencies + run: | + python -m pip install --upgrade pip + python -m pip install -e ".[dev]" + + - name: Run tests + run: python -m pytest diff --git a/CryptoFactors/.gitignore b/CryptoFactors/.gitignore index 03867fe486aef091f1c6b51c7f31c44fc80a95c3..ec398a573be6170410301703694b00007f5a9367 100644 --- a/CryptoFactors/.gitignore +++ b/CryptoFactors/.gitignore @@ -1,4 +1,8 @@ -data/raw/ +data/* +# Small fixtures and published result tables read by the tests. +!data/DATA_ACCESS.md +!data/fixtures/ +!data/results/ data_*/ __pycache__/ *.pyc diff --git a/CryptoFactors/README.md b/CryptoFactors/README.md index a122c58227f3f62d5b4651f7caabe587a03c2403..03f92ba04b5171863ff769be08cf3a390bcc25af 100644 --- a/CryptoFactors/README.md +++ b/CryptoFactors/README.md @@ -27,12 +27,25 @@ live trading or investment advice. Raw data are not in this repository; `binance_pipeline.py`, `perp_pipeline.py`, `fetch_okx.py` and `update_data.py` download them. -**Backtest conventions.** Daily cross-sectional quintile long–short, 5 bp per side; about -five names per leg in the large-coin pool; 365-day annualization. Robustness checks: -two-halves split, parameter sensitivity, rolling windows and the OKX cross-exchange -replication. - -## Results (report of 2026-06-19, data through 2026-05-31) +**Backtest conventions.** Daily cross-sectional quintile long–short, stated cost 5 bp per +side; about five names per leg in the large-coin pool; 365-day annualization. Positions +are filled at the same daily close (00:00 UTC) that completes the signal, with no +execution lag. Robustness checks: two-halves split, parameter sensitivity, rolling +windows and the OKX cross-exchange replication. + +> **Cost erratum (2026-10-26).** Every long–short figure in this README, `README_zh.md` +> and the dated reports was computed with a formula that charged the *average* of the +> two legs' turnover instead of their sum, i.e. about **2.5 bp per side, not the stated +> 5 bp**. The composite overlays in the v2.0 section were also charged nothing for +> re-weighting. The code now charges 5 bp per side on the traded notional of both legs +> and of the overlays (`src/crypto_factors/costs.py`, `tests/test_cost_accounting.py`). +> The factor tables have **not** been regenerated: that needs the raw Binance panels, +> which are not in this repository or in the public Hugging Face dataset (it holds only +> the aggregated `data/results/` tables). Until then, read the long–short Sharpe ratios +> below as upper bounds. Long-only lines and the weekly spot basket of the deliverable +> composite were charged correctly. + +## Results (report of 2026-06-19, data through 2026-05-31; long–short costs under-charged, see erratum) | Factor | Type | 730-day Sharpe | Out-of-sample checks | Verdict | |---|---|---|---|---| @@ -43,7 +56,7 @@ replication. | "Ideal" reversal | price | +0.25 | both halves positive, parameter-fragile | low confidence | | Cross-sectional momentum | price | −0.38 | both halves negative | does not transfer | -Other findings recorded in [`REPORT.md`](REPORT.md): +Other findings recorded in [`reports/REPORT.md`](reports/REPORT.md): - **Short samples manufacture factors.** The best factors on a 120-day window (Sharpe +3.50 and +1.93) turned negative on 730 days. @@ -64,6 +77,13 @@ top 8 large coins, equal weight, weekly rebalance. | Spot long only | 0.59 | −0.54 | −56% | 5% | | Spot long + perpetual index short (market-neutral) | 1.35 | +1.18 | −11% | 5% | +The hedged row subtracts an equal-weight index and charges nothing on the short side. +The 2026-10 audit ([`reports/LIVE_READINESS_AUDIT_2026-10.md`](reports/LIVE_READINESS_AUDIT_2026-10.md) +§3, 537 days through 2026-10-20, 1-minute entry delay) rebuilt it with tradable hedges: +Sharpe **0.81** with a 24-perpetual equal-weight short (funding accrual and rebalance fees +included) and **−0.03** with a BTC/ETH 50/50 perpetual short, against 0.86 for the ideal +index over the same window. This is a research result, not a trading recommendation. + ## After publication The factors are cross-sectional ranks with no fitted parameters, so every day after @@ -94,21 +114,72 @@ coins. Major-coin closes match OKX within 0.04%. One to four months of data say little about Sharpe ratios; the updates report cumulative returns and day counts instead. -### v2.0 Real 785-Day Perpetual Futures Validation (`data/results/equity_perp.csv`) +### v2.0 785-day composite overlays (`data/results/equity_perp.csv`): superseded headline + +These rows combine the daily net returns (2024-06-03 to 2026-07-27) of the three surviving +perpetual-futures factors (`低价位振幅`, `资金费率`, `散户多空比`). **They overstate +performance and are kept only as the published record**: + +- The three factor NAVs carry the under-charged long–short cost (about 2.5 bp per side). +- The published overlay rows charged nothing when the inverse-vol weights, the funding + gate or the vol-target leverage (up to 1.5×) changed the allocation. +- Selection is in-sample. The core factors, their universes and the gate constants + (20-day inverse-vol window, 5-day funding trigger at −1.5%, 0.25× scale) were chosen + on a window that overlaps 728 of the 785 days, and the funding-squeeze gate was added + on 2026-10-22, after the June–August 2026 squeeze it dampens had been observed and + published. Only the last 57 days postdate the 2026-05-31 cutoff, and they are not + independent of the gate's design. +- The Benjamini–Hochberg FDR step in `pipeline.py` runs only on the 10-date sample fixture + (`data/fixtures/sample_perp_panel.csv`); no multiple-testing adjustment covers these + strategies. -Evaluated directly on the 785 daily net return observations (`2024-06-03` to `2026-07-27`) of the three surviving Binance perpetual futures factors (`低价位振幅`, `资金费率`, `散户多空比`, `reports/real_785d_perp_validation.csv`): +As published (`reports/real_785d_perp_validation.csv`, no overlay cost): | Strategy | 785d Cum Return (%) | 785d Sharpe | 785d Max DD (%) | Calmar | NW $t$-stat | Pre-Pub 728d Sharpe | |---|---:|---:|---:|---:|---:|---:| | `static_equal_weight` | +150.75 | 1.87 | -16.26 | 3.28 | 2.95 | 1.89 | | `volatility_targeted_15pct` | +91.00 | 1.85 | -12.54 | 2.80 | 2.79 | 1.91 | -| **`inv_vol_funding_squeeze_gated`** | **+163.88** | **2.19** | -14.88 | 3.83 | **3.23** | **2.23** | -| **`inv_vol_funding_gated_voltarget_15pct`** | +96.95 | **2.12** | **-8.55** | **4.33** | **3.13** | **2.18** | +| `inv_vol_funding_squeeze_gated` | +163.88 | 2.19 | -14.88 | 3.83 | 3.23 | 2.23 | +| `inv_vol_funding_gated_voltarget_15pct` | +96.95 | 2.12 | -8.55 | 4.33 | 3.13 | 2.18 | + +Overlay re-weighting charged at 5 bp per side on |Δ allocation| × gross exposure, on the +same published factor NAVs (`evaluate_real_785d_perp_nav()` in `pipeline.py`, the default +since 2026-10-26; still upper bounds because the factor NAVs are under-charged): + +| Strategy | 785d Cum Return (%) | 785d Sharpe | 785d Max DD (%) | Calmar | Overlay cost (%/yr) | +|---|---:|---:|---:|---:|---:| +| `static_equal_weight` | +150.75 | 1.87 | -16.26 | 3.28 | 0.00 | +| `volatility_targeted_15pct` | +86.41 | 1.79 | -12.83 | 2.62 | 1.13 | +| `inv_vol_funding_squeeze_gated` | +147.52 | 2.05 | -14.93 | 3.51 | 2.98 | +| `inv_vol_funding_gated_voltarget_15pct` | +86.57 | 1.96 | -9.25 | 3.64 | 2.52 | + +The repository's own stress test of `inv_vol_funding_gated_voltarget_15pct` +([`reports/LIVE_READINESS_AUDIT_2026-10.md`](reports/LIVE_READINESS_AUDIT_2026-10.md) §2, +`reports/live_readiness_2026_10/v2_composite_delay_cost_stress.csv`, 835 days through +2026-10-20) is the most conservative published reading of this strategy: + +| Execution | Cost (bp) | 835d Cum (%) | 835d Sharpe | 835d Max DD (%) | +|---|---:|---:|---:|---:| +| Close of the signal day | 5 | +72.34 | 1.48 | -14.32 | +| 1-minute delay (00:01 UTC) | 5 | +70.76 | 1.46 | -15.13 | +| 1-minute delay (00:01 UTC) | 15 | +53.14 | 1.18 | -15.83 | +| 1-minute delay (00:01 UTC) | 30 | +28.26 | 0.72 | -18.39 | +| 1-minute delay (00:01 UTC) | 50 | +1.14 | 0.11 | -24.83 | +| Next-day close | 15 | +54.92 | 1.23 | -14.79 | + +The script that produced the audit is not committed and its cost convention ("bp per +trade") is not documented, so it cannot be reproduced from this repository either; at +5 bp it already sits well below the 1.69 that `reports/latest_oos_2026_10_composite.csv` +reports for the same 835 days. Recomputing all of the above with the corrected cost +formula is pending access to the raw panels. ## Limitations -- Fills at the next close, no market impact, equal weights within quintiles, about five - names per leg in the large-coin pool. +- Fills at the same daily close that completes the signal (no execution lag), no market + impact, equal weights within quintiles, about five names per leg in the large-coin pool. + The 2026-10 audit reruns the main signals with 1-minute, 12-hour and next-day delays. +- Published long–short tables under-charge costs (about 2.5 bp instead of 5 bp per + side; see the erratum above) and have not yet been regenerated. - The 2024–26 sample is an altcoin bear market; part of the range factor's Sharpe is bear-market defence. - OKX funding history via `ccxt` reaches back only about three months, so the @@ -137,8 +208,8 @@ python make_charts_postpub.py # equity_postpub.png ## Files The research write-ups are in Chinese: [`README_zh.md`](README_zh.md) (full detail), -[`REPORT.md`](REPORT.md), [`reports/UPDATE_2026-07.md`](reports/UPDATE_2026-07.md), -[`reports/UPDATE_2026-08.md`](reports/UPDATE_2026-08.md), [`reports/UPDATE_2026-09.md`](reports/UPDATE_2026-09.md) and [`reports/UPDATE_2026-10.md`](reports/UPDATE_2026-10.md). Result tables are in `data/results/` and `reports/`; figures are in `reports/figures/`. +[`reports/REPORT.md`](reports/REPORT.md), [`reports/UPDATE_2026-07.md`](reports/UPDATE_2026-07.md), +[`reports/UPDATE_2026-08.md`](reports/UPDATE_2026-08.md), [`reports/UPDATE_2026-09.md`](reports/UPDATE_2026-09.md) and [`reports/UPDATE_2026-10.md`](reports/UPDATE_2026-10.md); the cost, delay and hedge stress tests are in [`reports/LIVE_READINESS_AUDIT_2026-10.md`](reports/LIVE_READINESS_AUDIT_2026-10.md). Result tables are in `data/results/` and `reports/`; figures are in `reports/figures/`. Research period: June–September 2026. Source series: Kaiyuan Securities (开源证券) financial-engineering *Market Microstructure Research* series; the reports themselves diff --git a/CryptoFactors/README_zh.md b/CryptoFactors/README_zh.md index 2a6f0c6564fce77b4bf2af80ad49c368787f1e19..65f3fb241cfb6e8ec71e7dbb2eb011d84c3b537b 100644 --- a/CryptoFactors/README_zh.md +++ b/CryptoFactors/README_zh.md @@ -3,13 +3,19 @@ 把"开源证券·市场微观结构系列"的因子搬到数字货币市场,验证**数据墙消失**这一结论: A 股复现里卡死的分钟/逐笔/订单簿数据,在 crypto 交易所 API 上**免费**就能拿到。 -> ⚠ **本文数据止于 2026-05-31。已三轮续期: 2026-07-28 见 [`UPDATE_2026-07.md`](UPDATE_2026-07.md); -> 2026-08-15 见 [`UPDATE_2026-08.md`](UPDATE_2026-08.md) (YTD / 七月初 / 近15天); -> 2026-09-29 见 [`UPDATE_2026-09.md`](UPDATE_2026-09.md) (发布后逐月; 产品 B 对冲 6–8 月 +4.6% / −6.9% / −4.0%)。 +> ⚠ **本文数据止于 2026-05-31。已三轮续期: 2026-07-28 见 [`reports/UPDATE_2026-07.md`](reports/UPDATE_2026-07.md); +> 2026-08-15 见 [`reports/UPDATE_2026-08.md`](reports/UPDATE_2026-08.md) (YTD / 七月初 / 近15天); +> 2026-09-29 见 [`reports/UPDATE_2026-09.md`](reports/UPDATE_2026-09.md) (发布后逐月; 产品 B 对冲 6–8 月 +4.6% / −6.9% / −4.0%)。 > 下面的具体数字是更早的快照。** > 增量更新: `python update_data.py all`; 发布后复核: `python report_postpub.py`。 -> 📄 **执行摘要版研究报告见 [`REPORT.md`](REPORT.md)** · 🔬 **实时检测看板**: `python live_monitor.py` +> ⚠ **成本口径勘误 (2026-10-26)**: 本文与各 UPDATE 报告里标注"单边 5bps"的多空回测, 实际按两腿换手的 +> **平均值**而不是两腿之和计提, 只相当于单边约 **2.5bps** (少计一半); 785 天 v2.0 合成层改权重/杠杆也未计成本。 +> 代码已改为按两腿实际成交名义计提单边 5bps (`src/crypto_factors/costs.py`), 但原始 Binance 面板不在仓库与公开 +> 数据集里, 下文多空夏普尚未重算, 应视为上限。纯多头口径与产品的周调仓现货篮子计提无误。成交时点: 按信号当日 +> 收盘价 (00:00 UTC) 成交, 无执行延迟; 延迟与成本压力测试见 [`reports/LIVE_READINESS_AUDIT_2026-10.md`](reports/LIVE_READINESS_AUDIT_2026-10.md)。 + +> 📄 **执行摘要版研究报告见 [`reports/REPORT.md`](reports/REPORT.md)** · 🔬 **实时检测看板**: `python live_monitor.py` > 然后浏览器开 `http://127.0.0.1:8765` (预览 `dashboard_preview.png`)。 ## 环境结论 (本机实测) @@ -100,7 +106,7 @@ python crypto_micro/smart_money_factor.py # 算因子 + IC --- -## 🚀 交付策略书 (`deploy_spot.py`, `equity_deploy.png`) —— "明天能下单"的收口 +## 🚀 交付策略书 (`deploy_spot.py`, `equity_deploy.png`) —— 研究口径的收口 (回测, 非实盘交易) 把"去水分后唯一现货多头能直接吃"的三因子(低价位振幅 + 资金费率 + 散户多空比)合成横截面 z-score 复合分, 每期持最高分 top-k 等权篮子, 定期调仓, 并做工程化压测(冲击成本/调仓频率/持仓数下限)。 @@ -114,14 +120,18 @@ python crypto_micro/smart_money_factor.py # 算因子 + IC **收口三条结论**: 1. **纯现货多头逃不过熊市 beta**: 本窗口是 alt 大熊(基准 −50~−76%), 产品虽**显著跑赢基准** (0.38→0.59、回撤 −69%→−56%)但绝对仍亏。↔ 印证前文"多数 alpha 活在空腿"。 -2. **真正能赚的形态 = 现货多头篮子 + perp 空一个指数对冲掉 beta**: 纯 alpha **夏普 1.18 / 回撤 - 仅 −11% / 周换手 5%**, 即"long top8 大币现货, short 等额指数 perp"。一条腿做空、funding 成本可控。 +2. **回测里唯一赚钱的形态 = 现货多头篮子 + perp 空一个指数对冲掉 beta**: 纯 alpha **夏普 1.18 / 回撤 + 仅 −11% / 周换手 5%**, 即"long top8 大币现货, short 等额指数 perp"。(理想口径: 指数空头不计 funding + 与调仓费; 可执行对冲的重算见下方一句话。) 3. **工程压测**: **周/双周调仓是甜点**(换手 3~5%, 5→30bps 成本几乎无差异); 日调白送成本; top-k 越小收益越高但集中度风险大(top4 更猛但 4 只过于集中), **top8 是收益/分散平衡点**。 产品 B(大币+OI/散户)远胜产品 A(宽池, 含垃圾 alt 被熊市砸穿, 对冲后 alpha 仅夏普 0.51)。 -> 一句话: **这套微观结构 alpha 是真的(对冲后夏普 1.18、回撤 −11%、对成本不敏感), 但必须市场中性 -> (现货多头 + perp 指数空头)才拿得到; 裸多头会被 crypto 的 beta 吃掉。** +> 一句话: **回测中这套微观结构信号只有在市场中性形态 (现货多头 + perp 指数空头) 下才赚钱 (理想对冲口径 +> 夏普 1.18、回撤 −11%); 裸多头会被 crypto 的 beta 吃掉。** 2026-10 实盘可行性审计 +> ([`reports/LIVE_READINESS_AUDIT_2026-10.md`](reports/LIVE_READINESS_AUDIT_2026-10.md) §3, 537 天至 2026-10-20, +> 1 分钟入场延迟) 换成可执行的对冲腿: 24 个永续合约等权空头 (计 funding 与调仓费) 夏普 **0.81**, +> BTC/ETH 50/50 永续空头夏普 **−0.03** (同窗口理想指数口径 0.86)。这是研究结论, 不是实盘交易建议。 --- @@ -210,7 +220,7 @@ python crypto_micro/smart_money_factor.py # 算因子 + IC carry 分量 +13%/年(夏普极高但量小, 近无风险)= 合计净值3.20/夏普1.94。**carry 只占 ~17%, 83% 是真·价格反转** (空拥挤多头→价格回落)。→ funding 因子是**真预测 alpha**, 不是单纯薅资金费。 -> 仍存的理想化(下一步): 次日收盘成交、无冲击成本、分位内等权、大币池每腿仅~5 名。 +> 仍存的理想化(下一步): 按信号当日收盘价成交 (无执行延迟)、无冲击成本、分位内等权、大币池每腿仅~5 名。 --- diff --git a/CryptoFactors/STATUS.md b/CryptoFactors/STATUS.md index e08a1c023b9986e65509c2e2c984bcfc44c8ff41..b915b20935d7bade02bc5ca14a7e99eda25c348e 100644 --- a/CryptoFactors/STATUS.md +++ b/CryptoFactors/STATUS.md @@ -1,10 +1,11 @@ # Status -Last updated: 2026-09-30 +Last updated: 2026-10-26 ## Current evidence - **Evidence grade**: Backtest and post-publication out-of-sample backtest association (`PUBLIC_RESEARCH_SNAPSHOT`). - **Pre-publication panel**: 105 coins x 730 days (2024-06 to 2026-05) on Binance spot and USDT-margined perpetuals, plus OKX cross-exchange replication. - **Surviving signals**: Perpetual funding rate (730d Sharpe +1.42, 91% rolling windows positive, confirmed on OKX), retail long/short ratio (+1.39), and low-price range (+1.63). Cross-sectional momentum (-0.38) and top-trader ratio (-1.36) fail. +- **Cost erratum (2026-10-26)**: The published long-short Sharpe ratios above and in the reports charged about 2.5 bp per side instead of the stated 5 bp (the formula averaged the two legs' turnover instead of summing it), and the v2.0 composite overlays charged nothing for re-weighting. The code now charges both correctly (`src/crypto_factors/costs.py`); the factor tables await a rerun on the raw Binance panels, which are not in the repository or the public dataset. See the README for the v2.0 composite's overlay-charged figures and the 2026-10 audit's cost and delay stress results. - **Post-publication tracking (frozen recipe, no re-fitting)**: Over June-August 2026 (92 days), the market-neutral composite returned +4.6% in June, -6.9% in July, and -4.0% in August (-6.5% cumulative, max drawdown -11.9%). Only retail positioning remained positive (+11.8% L/S through September), while funding (-13.4%) and range (-9.7%) suffered during altcoin short squeezes. diff --git a/CryptoFactors/docs/METHODOLOGY.md b/CryptoFactors/docs/METHODOLOGY.md index f21382134d6c77aa79a1650d5cb81631c6012d0a..2eed5e55377a6fc5ab65ad65e0111020752deb87 100644 --- a/CryptoFactors/docs/METHODOLOGY.md +++ b/CryptoFactors/docs/METHODOLOGY.md @@ -1,5 +1,5 @@ # Methodology & Post-Publication Tracking Protocol -1. **Cross-Market Transfer Design**: Translate 32 equity microstructure factor specifications (originally developed on China A-share minute and order-flow data) to 105 crypto spot and perpetual-futures pairs on Binance (730 days, 2024-06 to 2026-05), charging 5 bp per side on daily quintile portfolios. +1. **Cross-Market Transfer Design**: Translate 32 equity microstructure factor specifications (originally developed on China A-share minute and order-flow data) to 105 crypto spot and perpetual-futures pairs on Binance (730 days, 2024-06 to 2026-05), charging a stated 5 bp per side on daily quintile portfolios, filled at the close that completes the signal. Until 2026-10-26 the long-short cost formula averaged the two legs' turnover instead of summing it, so published long-short tables effectively charged about 2.5 bp per side; the corrected code (`src/crypto_factors/costs.py`) has not yet been rerun on the raw panels. 2. **Multi-Gate Robustness**: Require sign consistency across sample halves, parameter stability across lookback horizons, rolling-window positivity, universe-breadth checks, and cross-exchange confirmation on OKX. 3. **Frozen Post-Publication Out-of-Sample Tracking**: After the 2026-06-19 report cutoff (data through 2026-05-31), freeze the equal-weighted z-score composite (funding rate + retail long/short ratio + low-price range, top 8 large-cap coins, weekly rebalance, 15 bp cost) and track June, July, August, and September 2026 without re-fitting weights. diff --git a/CryptoFactors/project.yaml b/CryptoFactors/project.yaml index 1030bc005835fae9b6ddc803f205d0da4c5bd504..f6c5a419b115272c4d98a059cf4d31b2b9d26846 100644 --- a/CryptoFactors/project.yaml +++ b/CryptoFactors/project.yaml @@ -13,7 +13,7 @@ authors: - Repository owner and maintainer original_source: CryptoFactors workspace project original_sample_period: 2024-06 through 2026-05 (105 coins x 730 days on Binance spot and USDT-margined perpetuals). -updated_sample_period: Post-publication out-of-sample tracking through 2026-09-29 (851 days total; 92-day June-August 2026 composite window). +updated_sample_period: Post-publication out-of-sample tracking through 2026-10-28 (880 days total; 92-day June-August 2026 composite window plus live-readiness daily tracking through October 2026). data_sources: - Binance public archives (data.binance.vision) for 1-minute spot/perpetual klines, funding rates, open interest, and long/short ratios - OKX public market data via ccxt for cross-exchange replication @@ -33,8 +33,8 @@ github_url: https://github.com/YangXiaoShawn/open-economic-quant-crypto-factors site_url: https://yangxiaoshawn.github.io/projects/crypto-factors/ dataset_url: https://huggingface.co/datasets/ShawnChamberlain/open-economic-quant-research-data/tree/main/CryptoFactors space_url: https://huggingface.co/spaces/ShawnChamberlain/open-economic-quant-research-observatory?project=crypto-factors -last_updated: 2026-09-30 -limitations: Backtest and post-publication out-of-sample backtest association, not live trading. Next-close fills omit market impact; about five names per leg in the large-coin pool; the 2024-2026 sample is an altcoin bear market; OKX funding history via ccxt is approximately three months. +last_updated: 2026-10-28 +limitations: Backtest and post-publication out-of-sample backtest association, not live trading. Fills at the close that completes the signal (no execution lag) and omit market impact; published long-short tables charged about 2.5 bp per side instead of the stated 5 bp (corrected in code 2026-10-26; tables not yet rerun); about five names per leg in the large-coin pool; the 2024-2026 sample is an altcoin bear market; OKX funding history via ccxt is approximately three months. catalog: field: crypto-derivatives accent: teal diff --git a/CryptoFactors/pyproject.toml b/CryptoFactors/pyproject.toml index cce98cd2d2f341523c4272a21c42f43755b930f6..d8e5ef6b15e34a7b0c3401dce6105e30f67bdb7b 100644 --- a/CryptoFactors/pyproject.toml +++ b/CryptoFactors/pyproject.toml @@ -14,6 +14,9 @@ dependencies = [ "ccxt>=4.2", "matplotlib>=3.8", "numpy>=1.26", + # Shared monorepo package, pinned by commit so this project installs standalone; + # inside the monorepo, uv uses the workspace copy (root tool.uv.sources). + "oeq-core @ git+https://github.com/YangXiaoShawn/open-economic-quant@3d309b7e90ca7b970bb5396d3bb781c92de4ea7e#subdirectory=packages/oeq-core", "pandas>=2.1", "pyarrow>=15.0", "scipy>=1.11", @@ -28,6 +31,9 @@ dev = [ [project.scripts] crypto-factors = "crypto_factors.cli:main" +[tool.hatch.metadata] +allow-direct-references = true + [tool.hatch.build.targets.wheel] packages = ["src/crypto_factors"] diff --git a/CryptoFactors/reports/live_readiness_2026_10/crypto_day_by_day_comparison_2026_10_27.csv b/CryptoFactors/reports/live_readiness_2026_10/crypto_day_by_day_comparison_2026_10_27.csv index 8f41bc9a1df257294fcb7476c90afeddc88235c9..533bbc3c8fda759739a10f55d4a2c84be0bc762d 100644 --- a/CryptoFactors/reports/live_readiness_2026_10/crypto_day_by_day_comparison_2026_10_27.csv +++ b/CryptoFactors/reports/live_readiness_2026_10/crypto_day_by_day_comparison_2026_10_27.csv @@ -1,19 +1,19 @@ -strategy_or_factor,10-20(信号10-19),10-21(信号10-20),10-22(信号10-21),10-23(信号10-22),10-24(信号10-23),10-25(信号10-24),10-26(信号10-25),10-27(信号10-26),10-28(信号10-27)*,近7日已收盘(10-21~10-27),近8日含最新(10-21~10-28*),10月累计(至10-27收盘),9/29复核至今(至10-27),9/01费率截止至今(至10-27) -基准·BTC,1.33,1.28,-3.18,-0.28,-0.37,-0.91,-0.0,0.95,0.72,-2.55,-1.85,-4.68,-3.29,4.48 -基准·ETH,1.71,1.0,-3.42,-0.06,-1.21,-1.23,-0.23,1.11,1.06,-4.04,-3.02,-13.16,-12.23,-2.82 -基准·大币池24等权,1.84,0.54,-4.72,-1.03,-1.56,-0.68,0.29,0.49,1.63,-6.58,-5.06,-11.28,-11.66,19.88 -基准·宽池105等权,3.06,1.16,-5.94,-0.91,-1.81,-1.69,0.33,0.82,2.17,-7.95,-5.95,-13.85,-13.35,16.8 -产品B·大币top8·纯现货多头,0.4,0.7,-3.2,-1.03,-1.92,-1.15,0.19,-0.14,1.36,-6.41,-5.14,-11.29,-11.0,22.01 -产品B·大币top8·对冲beta(市场中性),-1.45,0.16,1.52,0.0,-0.35,-0.47,-0.1,-0.64,-0.27,0.11,-0.15,-0.56,0.2,0.91 -v2.0·四因子静态等权,-0.91,-0.04,0.14,-0.03,-0.59,-0.09,-0.22,-1.06,-0.31,-1.87,-2.17,-0.43,-0.04,-1.87 -v2.0·逆波动率+费率门控,-0.88,0.1,-0.24,-0.32,-0.75,-0.21,0.18,-0.99,0.05,-2.22,-2.16,0.89,0.65,-2.66 -v2.0·门控+15%目标波动率,-1.08,0.12,-0.29,-0.42,-0.97,-0.29,0.26,-1.48,0.07,-3.03,-2.96,-0.55,-0.72,-3.31 -单因子·低价位振幅(宽),-0.57,-1.14,4.31,2.46,0.65,0.15,-1.07,-0.35,-2.69,4.99,2.17,5.44,6.46,-4.56 -单因子·理想反转(宽),-0.05,0.79,2.01,-0.31,-0.52,0.58,1.0,0.02,1.34,3.6,4.99,8.35,8.46,10.5 -单因子·主动买入率(大),0.48,0.02,0.2,0.58,-0.03,-0.79,0.55,0.85,-1.73,1.38,-0.38,1.16,1.04,-11.21 -单因子·大额主动买(大),-0.34,0.44,0.3,-0.1,-0.1,-1.07,0.55,1.27,-1.73,1.28,-0.47,6.28,4.95,-14.37 -单因子·持仓量变化(大),-1.42,0.03,-1.72,0.21,-0.01,-0.41,1.46,-0.37,-0.35,-0.83,-1.18,-12.11,-11.33,-18.34 -单因子·截面动量(宽),1.02,-0.21,-0.66,-0.34,1.05,0.02,-0.89,0.63,-1.13,-0.41,-1.54,3.13,1.06,-6.81 -单因子·大户多空比(大),2.25,0.09,-1.67,-0.77,-0.35,-0.39,1.12,0.6,-0.82,-1.39,-2.2,-7.7,-7.59,16.42 -单因子·散户多空比(大),-0.34,1.02,-1.7,-0.8,-1.74,-0.24,-0.28,-1.38,1.03,-5.02,-4.05,2.23,0.28,5.11 -单因子·资金费率(大),-1.32,-0.06,-0.33,-1.98,-1.27,0.15,-0.99,-2.14,0.79,-6.45,-5.71,2.26,3.9,7.47 +strategy_or_factor,10-20(信号10-19),10-21(信号10-20),10-22(信号10-21),10-23(信号10-22),10-24(信号10-23),10-25(信号10-24),10-26(信号10-25),10-27(信号10-26),10-28(信号10-27),近8日已收盘(10-21~10-28),近8日含最新(10-21~10-28),10月累计(至10-28收盘),9/29复核至今(至10-28),9/01费率截止至今(至10-28) +基准·BTC,1.33,1.28,-3.18,-0.28,-0.37,-0.91,-0.0,0.95,0.53,-2.04,-2.04,-4.17,-2.78,5.04 +基准·ETH,1.71,1.0,-3.42,-0.06,-1.21,-1.23,-0.23,1.11,0.39,-3.66,-3.66,-12.82,-11.89,-2.44 +基准·大币池24等权,1.84,0.54,-4.72,-1.03,-1.56,-0.68,0.29,0.49,0.68,-5.95,-5.95,-10.68,-11.07,20.69 +基准·宽池105等权,3.06,1.16,-5.94,-0.91,-1.81,-1.69,0.33,0.82,0.82,-7.19,-7.19,-13.14,-12.64,17.76 +产品B·大币top8·纯现货多头,0.4,0.7,-3.2,-1.03,-1.92,-1.15,0.19,-0.14,0.33,-6.1,-6.1,-11.0,-10.7,22.41 +产品B·大币top8·对冲beta(市场中性),-1.45,0.16,1.52,0.0,-0.35,-0.47,-0.1,-0.64,-0.35,-0.24,-0.24,-0.91,-0.15,0.55 +v2.0·四因子静态等权,-0.94,-0.06,0.12,-0.05,-0.62,-0.1,-0.24,-1.09,-0.34,-2.35,-2.35,-1.23,-0.88,-3.28 +v2.0·逆波动率+费率门控,-0.91,0.08,-0.26,-0.35,-0.77,-0.22,0.16,-1.02,-0.08,-2.45,-2.45,0.36,0.09,-3.72 +v2.0·门控+15%目标波动率,-1.11,0.09,-0.31,-0.45,-0.99,-0.32,0.23,-1.52,-0.11,-3.33,-3.33,-1.12,-1.31,-4.25 +单因子·低价位振幅(宽),-0.57,-1.15,4.31,2.45,0.65,0.14,-1.08,-0.36,-1.71,3.15,3.15,3.43,4.42,-6.63 +单因子·理想反转(宽),-0.08,0.75,1.97,-0.34,-0.55,0.55,0.97,-0.01,0.97,4.37,4.37,8.54,8.58,9.66 +单因子·主动买入率(大),0.46,-0.01,0.18,0.55,-0.07,-0.81,0.52,0.83,-1.21,-0.05,-0.05,-0.77,-0.95,-13.62 +单因子·大额主动买(大),-0.38,0.41,0.27,-0.14,-0.12,-1.09,0.52,1.25,-1.21,-0.14,-0.14,4.18,2.82,-16.83 +单因子·持仓量变化(大),-1.48,-0.02,-1.77,0.15,-0.08,-0.45,1.41,-0.44,0.12,-1.1,-1.1,-13.13,-12.43,-20.4 +单因子·截面动量(宽),0.99,-0.23,-0.69,-0.36,1.02,-0.01,-0.9,0.6,-0.3,-0.87,-0.87,2.11,-0.0,-8.46 +单因子·大户多空比(大),2.24,0.08,-1.67,-0.77,-0.35,-0.4,1.12,0.59,-0.59,-2.0,-2.0,-8.35,-8.25,15.37 +单因子·散户多空比(大),-0.34,1.01,-1.71,-0.81,-1.74,-0.24,-0.28,-1.39,0.19,-4.89,-4.89,2.23,0.28,4.87 +单因子·资金费率(大),-1.35,-0.08,-0.34,-2.0,-1.29,0.12,-1.0,-2.16,0.05,-6.52,-6.52,2.1,3.68,6.62 diff --git a/CryptoFactors/reports/live_readiness_2026_10/crypto_day_by_day_comparison_2026_10_28.csv b/CryptoFactors/reports/live_readiness_2026_10/crypto_day_by_day_comparison_2026_10_28.csv index 8f41bc9a1df257294fcb7476c90afeddc88235c9..533bbc3c8fda759739a10f55d4a2c84be0bc762d 100644 --- a/CryptoFactors/reports/live_readiness_2026_10/crypto_day_by_day_comparison_2026_10_28.csv +++ b/CryptoFactors/reports/live_readiness_2026_10/crypto_day_by_day_comparison_2026_10_28.csv @@ -1,19 +1,19 @@ -strategy_or_factor,10-20(信号10-19),10-21(信号10-20),10-22(信号10-21),10-23(信号10-22),10-24(信号10-23),10-25(信号10-24),10-26(信号10-25),10-27(信号10-26),10-28(信号10-27)*,近7日已收盘(10-21~10-27),近8日含最新(10-21~10-28*),10月累计(至10-27收盘),9/29复核至今(至10-27),9/01费率截止至今(至10-27) -基准·BTC,1.33,1.28,-3.18,-0.28,-0.37,-0.91,-0.0,0.95,0.72,-2.55,-1.85,-4.68,-3.29,4.48 -基准·ETH,1.71,1.0,-3.42,-0.06,-1.21,-1.23,-0.23,1.11,1.06,-4.04,-3.02,-13.16,-12.23,-2.82 -基准·大币池24等权,1.84,0.54,-4.72,-1.03,-1.56,-0.68,0.29,0.49,1.63,-6.58,-5.06,-11.28,-11.66,19.88 -基准·宽池105等权,3.06,1.16,-5.94,-0.91,-1.81,-1.69,0.33,0.82,2.17,-7.95,-5.95,-13.85,-13.35,16.8 -产品B·大币top8·纯现货多头,0.4,0.7,-3.2,-1.03,-1.92,-1.15,0.19,-0.14,1.36,-6.41,-5.14,-11.29,-11.0,22.01 -产品B·大币top8·对冲beta(市场中性),-1.45,0.16,1.52,0.0,-0.35,-0.47,-0.1,-0.64,-0.27,0.11,-0.15,-0.56,0.2,0.91 -v2.0·四因子静态等权,-0.91,-0.04,0.14,-0.03,-0.59,-0.09,-0.22,-1.06,-0.31,-1.87,-2.17,-0.43,-0.04,-1.87 -v2.0·逆波动率+费率门控,-0.88,0.1,-0.24,-0.32,-0.75,-0.21,0.18,-0.99,0.05,-2.22,-2.16,0.89,0.65,-2.66 -v2.0·门控+15%目标波动率,-1.08,0.12,-0.29,-0.42,-0.97,-0.29,0.26,-1.48,0.07,-3.03,-2.96,-0.55,-0.72,-3.31 -单因子·低价位振幅(宽),-0.57,-1.14,4.31,2.46,0.65,0.15,-1.07,-0.35,-2.69,4.99,2.17,5.44,6.46,-4.56 -单因子·理想反转(宽),-0.05,0.79,2.01,-0.31,-0.52,0.58,1.0,0.02,1.34,3.6,4.99,8.35,8.46,10.5 -单因子·主动买入率(大),0.48,0.02,0.2,0.58,-0.03,-0.79,0.55,0.85,-1.73,1.38,-0.38,1.16,1.04,-11.21 -单因子·大额主动买(大),-0.34,0.44,0.3,-0.1,-0.1,-1.07,0.55,1.27,-1.73,1.28,-0.47,6.28,4.95,-14.37 -单因子·持仓量变化(大),-1.42,0.03,-1.72,0.21,-0.01,-0.41,1.46,-0.37,-0.35,-0.83,-1.18,-12.11,-11.33,-18.34 -单因子·截面动量(宽),1.02,-0.21,-0.66,-0.34,1.05,0.02,-0.89,0.63,-1.13,-0.41,-1.54,3.13,1.06,-6.81 -单因子·大户多空比(大),2.25,0.09,-1.67,-0.77,-0.35,-0.39,1.12,0.6,-0.82,-1.39,-2.2,-7.7,-7.59,16.42 -单因子·散户多空比(大),-0.34,1.02,-1.7,-0.8,-1.74,-0.24,-0.28,-1.38,1.03,-5.02,-4.05,2.23,0.28,5.11 -单因子·资金费率(大),-1.32,-0.06,-0.33,-1.98,-1.27,0.15,-0.99,-2.14,0.79,-6.45,-5.71,2.26,3.9,7.47 +strategy_or_factor,10-20(信号10-19),10-21(信号10-20),10-22(信号10-21),10-23(信号10-22),10-24(信号10-23),10-25(信号10-24),10-26(信号10-25),10-27(信号10-26),10-28(信号10-27),近8日已收盘(10-21~10-28),近8日含最新(10-21~10-28),10月累计(至10-28收盘),9/29复核至今(至10-28),9/01费率截止至今(至10-28) +基准·BTC,1.33,1.28,-3.18,-0.28,-0.37,-0.91,-0.0,0.95,0.53,-2.04,-2.04,-4.17,-2.78,5.04 +基准·ETH,1.71,1.0,-3.42,-0.06,-1.21,-1.23,-0.23,1.11,0.39,-3.66,-3.66,-12.82,-11.89,-2.44 +基准·大币池24等权,1.84,0.54,-4.72,-1.03,-1.56,-0.68,0.29,0.49,0.68,-5.95,-5.95,-10.68,-11.07,20.69 +基准·宽池105等权,3.06,1.16,-5.94,-0.91,-1.81,-1.69,0.33,0.82,0.82,-7.19,-7.19,-13.14,-12.64,17.76 +产品B·大币top8·纯现货多头,0.4,0.7,-3.2,-1.03,-1.92,-1.15,0.19,-0.14,0.33,-6.1,-6.1,-11.0,-10.7,22.41 +产品B·大币top8·对冲beta(市场中性),-1.45,0.16,1.52,0.0,-0.35,-0.47,-0.1,-0.64,-0.35,-0.24,-0.24,-0.91,-0.15,0.55 +v2.0·四因子静态等权,-0.94,-0.06,0.12,-0.05,-0.62,-0.1,-0.24,-1.09,-0.34,-2.35,-2.35,-1.23,-0.88,-3.28 +v2.0·逆波动率+费率门控,-0.91,0.08,-0.26,-0.35,-0.77,-0.22,0.16,-1.02,-0.08,-2.45,-2.45,0.36,0.09,-3.72 +v2.0·门控+15%目标波动率,-1.11,0.09,-0.31,-0.45,-0.99,-0.32,0.23,-1.52,-0.11,-3.33,-3.33,-1.12,-1.31,-4.25 +单因子·低价位振幅(宽),-0.57,-1.15,4.31,2.45,0.65,0.14,-1.08,-0.36,-1.71,3.15,3.15,3.43,4.42,-6.63 +单因子·理想反转(宽),-0.08,0.75,1.97,-0.34,-0.55,0.55,0.97,-0.01,0.97,4.37,4.37,8.54,8.58,9.66 +单因子·主动买入率(大),0.46,-0.01,0.18,0.55,-0.07,-0.81,0.52,0.83,-1.21,-0.05,-0.05,-0.77,-0.95,-13.62 +单因子·大额主动买(大),-0.38,0.41,0.27,-0.14,-0.12,-1.09,0.52,1.25,-1.21,-0.14,-0.14,4.18,2.82,-16.83 +单因子·持仓量变化(大),-1.48,-0.02,-1.77,0.15,-0.08,-0.45,1.41,-0.44,0.12,-1.1,-1.1,-13.13,-12.43,-20.4 +单因子·截面动量(宽),0.99,-0.23,-0.69,-0.36,1.02,-0.01,-0.9,0.6,-0.3,-0.87,-0.87,2.11,-0.0,-8.46 +单因子·大户多空比(大),2.24,0.08,-1.67,-0.77,-0.35,-0.4,1.12,0.59,-0.59,-2.0,-2.0,-8.35,-8.25,15.37 +单因子·散户多空比(大),-0.34,1.01,-1.71,-0.81,-1.74,-0.24,-0.28,-1.39,0.19,-4.89,-4.89,2.23,0.28,4.87 +单因子·资金费率(大),-1.35,-0.08,-0.34,-2.0,-1.29,0.12,-1.0,-2.16,0.05,-6.52,-6.52,2.1,3.68,6.62 diff --git a/CryptoFactors/reports/live_readiness_2026_10/preregistered_book_realized_10_23_to_10_27.csv b/CryptoFactors/reports/live_readiness_2026_10/preregistered_book_realized_10_23_to_10_27.csv index 3f85740e57fda285eb40b9cf716705e1e0bfa478..aa07c0f5d8850143daed32f02a84f7455bf61ae2 100644 --- a/CryptoFactors/reports/live_readiness_2026_10/preregistered_book_realized_10_23_to_10_27.csv +++ b/CryptoFactors/reports/live_readiness_2026_10/preregistered_book_realized_10_23_to_10_27.csv @@ -1,7 +1,7 @@ date_utc,BTC_pct,ETH_pct,Big24_EW_pct,Wide_EW_pct,ProdB_Long8_pct,ProdB_MktNeutral_pct,ProdB_Top8_vs_Bot5_pct,GLS_LS_pct,FUND_LS_pct,AMP_LS_pct,REV_LS_pct -2026-10-23,-0.28,-0.07,-0.76,-0.69,-1.14,-0.38,-0.31,-0.63,-1.69,1.49,-0.16 -2026-10-24,-0.37,-1.22,-1.48,-1.74,-2.02,-0.54,-0.75,-2.14,-1.27,0.37,-0.58 -2026-10-25,-0.9,-1.22,-0.7,-1.71,-0.96,-0.26,-0.25,-0.59,0.55,0.32,0.41 -2026-10-26,0.01,-0.22,0.41,0.28,-0.04,-0.45,-0.97,-0.19,-0.82,-0.19,-1.28 -2026-10-27,0.94,1.11,0.27,0.73,-0.17,-0.44,-0.82,-1.49,-1.38,-0.07,-0.45 -2026-10-28 (Live),0.72,1.06,1.63,2.17,2.07,0.44,0.33,0.54,1.02,-0.72,-0.03 +2026-10-23,-0.28,-0.07,-0.76,-0.72,-1.14,-0.38,-0.31,-0.63,-1.69,1.49,-0.16 +2026-10-24,-0.37,-1.22,-1.48,-1.73,-2.02,-0.54,-0.75,-2.14,-1.27,0.37,-0.58 +2026-10-25,-0.9,-1.22,-0.7,-1.65,-0.96,-0.26,-0.25,-0.59,0.55,0.32,0.41 +2026-10-26,0.01,-0.22,0.41,0.34,-0.04,-0.45,-0.97,-0.19,-0.82,-0.19,-1.28 +2026-10-27,0.94,1.11,0.27,0.74,-0.17,-0.44,-0.82,-1.49,-1.38,-0.07,-0.45 +2026-10-28,0.53,0.39,0.68,0.82,0.68,-0.0,-0.08,-0.32,0.07,-0.14,0.08 diff --git a/CryptoFactors/reports/live_readiness_2026_10/preregistered_book_realized_10_23_to_10_28.csv b/CryptoFactors/reports/live_readiness_2026_10/preregistered_book_realized_10_23_to_10_28.csv index 3f85740e57fda285eb40b9cf716705e1e0bfa478..aa07c0f5d8850143daed32f02a84f7455bf61ae2 100644 --- a/CryptoFactors/reports/live_readiness_2026_10/preregistered_book_realized_10_23_to_10_28.csv +++ b/CryptoFactors/reports/live_readiness_2026_10/preregistered_book_realized_10_23_to_10_28.csv @@ -1,7 +1,7 @@ date_utc,BTC_pct,ETH_pct,Big24_EW_pct,Wide_EW_pct,ProdB_Long8_pct,ProdB_MktNeutral_pct,ProdB_Top8_vs_Bot5_pct,GLS_LS_pct,FUND_LS_pct,AMP_LS_pct,REV_LS_pct -2026-10-23,-0.28,-0.07,-0.76,-0.69,-1.14,-0.38,-0.31,-0.63,-1.69,1.49,-0.16 -2026-10-24,-0.37,-1.22,-1.48,-1.74,-2.02,-0.54,-0.75,-2.14,-1.27,0.37,-0.58 -2026-10-25,-0.9,-1.22,-0.7,-1.71,-0.96,-0.26,-0.25,-0.59,0.55,0.32,0.41 -2026-10-26,0.01,-0.22,0.41,0.28,-0.04,-0.45,-0.97,-0.19,-0.82,-0.19,-1.28 -2026-10-27,0.94,1.11,0.27,0.73,-0.17,-0.44,-0.82,-1.49,-1.38,-0.07,-0.45 -2026-10-28 (Live),0.72,1.06,1.63,2.17,2.07,0.44,0.33,0.54,1.02,-0.72,-0.03 +2026-10-23,-0.28,-0.07,-0.76,-0.72,-1.14,-0.38,-0.31,-0.63,-1.69,1.49,-0.16 +2026-10-24,-0.37,-1.22,-1.48,-1.73,-2.02,-0.54,-0.75,-2.14,-1.27,0.37,-0.58 +2026-10-25,-0.9,-1.22,-0.7,-1.65,-0.96,-0.26,-0.25,-0.59,0.55,0.32,0.41 +2026-10-26,0.01,-0.22,0.41,0.34,-0.04,-0.45,-0.97,-0.19,-0.82,-0.19,-1.28 +2026-10-27,0.94,1.11,0.27,0.74,-0.17,-0.44,-0.82,-1.49,-1.38,-0.07,-0.45 +2026-10-28,0.53,0.39,0.68,0.82,0.68,-0.0,-0.08,-0.32,0.07,-0.14,0.08 diff --git a/CryptoFactors/reports/postpub_composite_summary.csv b/CryptoFactors/reports/postpub_composite_summary.csv index 124ee9e054488e717eb40fc11e61b5f6df62d503..b868d9140deeae796f24a016e98d9ccbddeffe37 100644 --- a/CryptoFactors/reports/postpub_composite_summary.csv +++ b/CryptoFactors/reports/postpub_composite_summary.csv @@ -1,5 +1,5 @@ window,days,start_date,end_date,market_neutral_return_pct,spot_long_only_return_pct,max_drawdown_pct,regime_note -"Pre-publication (730d sample, 515d live panel)",515,2025-01-01,2026-05-31,35.0,-41.0,-11.5,In-sample / pre-publication reference (Sharpe 1.18) +"Pre-publication (730d sample, 515d backtest panel)",515,2025-01-01,2026-05-31,35.0,-41.0,-11.5,In-sample / pre-publication reference (Sharpe 1.18) June 2026 (OOS Month 1),30,2026-06-01,2026-06-30,4.57,-16.88,-2.0,Funding reversed in sell-off; retail ratio and range gained July 2026 (OOS Month 2),31,2026-07-01,2026-07-31,-6.93,-6.11,-5.6,Range and retail ratio turned negative August 2026 (OOS Month 3),31,2026-08-01,2026-08-31,-3.97,15.00,-5.4,Altcoin rally (+21%); funding short leg lost -10.1% diff --git a/CryptoFactors/src/crypto_factors/backtest.py b/CryptoFactors/src/crypto_factors/backtest.py index 3fddcb461f18b3ef68f03cfac2639a737608c45b..befae47371210e7787d8c3bf07569e9850196865 100644 --- a/CryptoFactors/src/crypto_factors/backtest.py +++ b/CryptoFactors/src/crypto_factors/backtest.py @@ -6,12 +6,13 @@ - 每个 UTC 日: 按因子排序,做 分位组合 (默认五分位)。 - 方向按"研报预期"定向(反转类 long低 short高),故展示的是"按原文方向交易"的结果。 - 多空 = 多组等权 − 空组等权; 多头 = 仅多组(贴近实盘只做多)。 - - 成本: 单边 COST_BPS, 按当日换手计提。 + - 成本: 单边 COST_BPS, 按当日实际成交名义 sum|Δw| 计提 (多空两腿合计, 见 costs.py)。 - 7×24, 每日调仓; 年化按 365 天。 """ import os, warnings import numpy as np import pandas as pd +from crypto_factors.costs import cost_from_traded, leg_traded_notional from crypto_factors.factor_library import build_panel warnings.filterwarnings("ignore", message="Mean of empty slice") @@ -34,10 +35,15 @@ FACTORS = [ def backtest_factor(panel, col, direction): - """返回每日 多空/多头 收益序列 + 换手。""" + """返回每日 多空/多头 收益序列 + 换手。 + + traded = 多空两腿实际成交名义 sum|Δw| (每腿毛敞口 1), 成本 = traded × COST_BPS (单边); + turnover = traded / 2 (两腿平均, 与 2026-10-26 前的换手口径一致)。 + 2026-10-26 前成本按 turnover 而非 traded 计提, 多空成本少计一半 (实际约单边 2.5bps)。 + """ df = panel.dropna(subset=[col, "fwd_ret"]).copy() df["sig"] = df[col] * direction # 按方向转成"越大越看多" - ls_ret, long_ret, days, turns = [], [], [], [] + ls_ret, long_ret, days, turns, traded_list = [], [], [], [], [] prev_long, prev_short = set(), set() for day, g in df.groupby("day"): if g["sym"].nunique() < QUANTILE * 2: @@ -47,16 +53,16 @@ def backtest_factor(panel, col, direction): longs = g[g["q"] == QUANTILE - 1] # 信号最高(看多) shorts = g[g["q"] == 0] # 信号最低(看空) lr, sr = longs["fwd_ret"].mean(), shorts["fwd_ret"].mean() - # 换手(多头腿) + # 实际成交名义: 多头腿 + 空头腿 (各自 sum|Δw|) cur_long = set(longs["sym"]); cur_short = set(shorts["sym"]) - to = (len(cur_long ^ prev_long) + len(cur_short ^ prev_short)) / \ - max(len(cur_long) + len(cur_short), 1) - cost = to * COST_BPS / 1e4 - ls_ret.append((lr - sr) - cost) - long_ret.append(lr - (len(cur_long ^ prev_long) / max(len(cur_long),1)) * COST_BPS/1e4) - days.append(day); turns.append(to) + traded_l = leg_traded_notional(prev_long, cur_long) + traded = traded_l + leg_traded_notional(prev_short, cur_short) + ls_ret.append((lr - sr) - cost_from_traded(traded, COST_BPS)) + long_ret.append(lr - cost_from_traded(traded_l, COST_BPS)) + days.append(day); turns.append(traded / 2.0); traded_list.append(traded) prev_long, prev_short = cur_long, cur_short - return pd.DataFrame({"day": days, "ls": ls_ret, "long": long_ret, "turnover": turns}) + return pd.DataFrame({"day": days, "ls": ls_ret, "long": long_ret, "turnover": turns, + "traded": traded_list}) def metrics(r): diff --git a/CryptoFactors/src/crypto_factors/backtest_real.py b/CryptoFactors/src/crypto_factors/backtest_real.py index fac574e9c07b9d39e27a501de6ad9eea4ad722fa..256f5cd9ec328226794c1d9950d3f6bbb6fdc58a 100644 --- a/CryptoFactors/src/crypto_factors/backtest_real.py +++ b/CryptoFactors/src/crypto_factors/backtest_real.py @@ -18,6 +18,7 @@ import os import numpy as np import pandas as pd from crypto_factors.backtest import metrics, QUANTILE, COST_BPS +from crypto_factors.costs import cost_from_traded, leg_traded_notional from crypto_factors.backtest_perp import build_panel, BIG_POOL, FACTORS, pool_panel @@ -36,9 +37,9 @@ def backtest_real(panel, col, direction, pool): lr, sr = longs["fwd_ret"].mean(), shorts["fwd_ret"].mean() mkt = g["fwd_ret"].mean() cl, cs = set(longs["sym"]), set(shorts["sym"]) - to = (len(cl ^ prev_l) + len(cs ^ prev_s)) / max(len(cl) + len(cs), 1) - to_l = len(cl ^ prev_l) / max(len(cl), 1) - cost = to * COST_BPS / 1e4 + # 成本按两腿实际成交名义 sum|Δw| 计提 (单边 COST_BPS); 2026-10-26 前少计一半 + to_l = leg_traded_notional(prev_l, cl) + cost = cost_from_traded(to_l + leg_traded_notional(prev_s, cs), COST_BPS) # funding 计提 lf = longs["fwd_fund"].mean() if has_fund else 0.0 sf = shorts["fwd_fund"].mean() if has_fund else 0.0 @@ -47,7 +48,7 @@ def backtest_real(panel, col, direction, pool): fund_pnl = sf - lf # 空腿收 + 多腿付 ls_price = (lr - sr) - cost ls_real = ls_price + fund_pnl - long_only = (lr - mkt) - to_l * COST_BPS / 1e4 # 纯多头超额(不做空) + long_only = (lr - mkt) - cost_from_traded(to_l, COST_BPS) # 纯多头超额(不做空) rows.append(dict(day=day, ls_price=ls_price, ls_real=ls_real, long_only=long_only, fund_pnl=fund_pnl, price=lr - sr)) prev_l, prev_s = cl, cs diff --git a/CryptoFactors/src/crypto_factors/costs.py b/CryptoFactors/src/crypto_factors/costs.py new file mode 100644 index 0000000000000000000000000000000000000000..be6d5eb3b2fd59aa32a4a0cf2584ca11ea0be57e --- /dev/null +++ b/CryptoFactors/src/crypto_factors/costs.py @@ -0,0 +1,81 @@ +"""Transaction-cost accounting shared by the CryptoFactors backtests. + +Convention: ``cost_bps`` is charged **per side**, i.e. on every unit of notional +bought or sold. A position change is therefore charged on the traded notional +``sum_i |w_new_i - w_old_i|``, not on a count of names. + +The quintile long-short books hold $1 long (equal weight) and $1 short (equal +weight) per $1 of capital, so they carry gross exposure 2. Rotating every name in +both legs trades 4 units of notional (sell 1 + buy 1 on each leg). + +Before 2026-10-26 the long-short backtests charged ``to * cost`` with +``to = (|dL| + |dS|) / (|L| + |S|)``, the *average* of the two legs' traded +notional, which is half of what the book actually trades. Published tables +computed with that formula therefore charged roughly 2.5 bp per side, not the +stated 5 bp. This module is pure Python so that it can be tested without pandas. +""" +from __future__ import annotations + +from collections.abc import Iterable, Mapping, Sequence + + +def leg_traded_notional(prev: Iterable[str], cur: Iterable[str]) -> float: + """Traded notional of one equal-weight leg with gross exposure 1.0. + + Each leg holds ``1 / len(leg)`` per name. The result is + ``sum_i |w_cur_i - w_prev_i|`` over the union of both name sets, so a full + replacement trades 2.0 and a change in the number of names also charges the + re-weighting of names that stay in the leg. + """ + prev_set, cur_set = set(prev), set(cur) + w_prev = 1.0 / len(prev_set) if prev_set else 0.0 + w_cur = 1.0 / len(cur_set) if cur_set else 0.0 + traded = 0.0 + for name in prev_set | cur_set: + traded += abs((w_cur if name in cur_set else 0.0) - (w_prev if name in prev_set else 0.0)) + return traded + + +def long_short_traded_notional( + prev_long: Iterable[str], + cur_long: Iterable[str], + prev_short: Iterable[str], + cur_short: Iterable[str], +) -> float: + """Traded notional of a $1-long / $1-short equal-weight book (sum over both legs).""" + return leg_traded_notional(prev_long, cur_long) + leg_traded_notional(prev_short, cur_short) + + +def cost_from_traded(traded_notional: float, cost_bps_per_side: float) -> float: + """Cost as a fraction of capital for a given traded notional (per unit of capital).""" + return float(traded_notional) * float(cost_bps_per_side) / 1e4 + + +def overlay_rebalance_costs( + exposures: Sequence[Mapping[str, float]], + cost_bps_per_side: float, + gross_per_unit: float = 2.0, +) -> list[float]: + """Daily cost of changing sleeve allocations in a composite of long-short sleeves. + + ``exposures[t][sleeve]`` is the fraction of capital allocated to a sleeve on + day ``t`` (overlay weight times any leverage multiplier). Each unit allocated to + a dollar-neutral sleeve carries ``gross_per_unit`` of gross notional (2.0 for + $1 long + $1 short), so moving an allocation by ``d`` trades + ``|d| * gross_per_unit`` of notional. + + Day 0 is not charged: the sleeve return series already include the cost of + building their own positions. Re-balancing for intraday drift and netting + against the sleeves' own trades or across sleeves are not modelled. + """ + costs: list[float] = [] + prev: Mapping[str, float] | None = None + for cur in exposures: + if prev is None: + costs.append(0.0) + else: + names = set(prev) | set(cur) + delta = sum(abs(float(cur.get(k, 0.0)) - float(prev.get(k, 0.0))) for k in names) + costs.append(cost_from_traded(delta * gross_per_unit, cost_bps_per_side)) + prev = cur + return costs diff --git a/CryptoFactors/src/crypto_factors/funding_deep.py b/CryptoFactors/src/crypto_factors/funding_deep.py index 34580bb44632eb3375d03947c765d8fc71967e0b..ec64ec13863ae5cf525359f2f9476574eed84fb1 100644 --- a/CryptoFactors/src/crypto_factors/funding_deep.py +++ b/CryptoFactors/src/crypto_factors/funding_deep.py @@ -15,6 +15,7 @@ import os import numpy as np import pandas as pd from crypto_factors.backtest import metrics, QUANTILE, COST_BPS +from crypto_factors.costs import cost_from_traded, long_short_traded_notional from crypto_factors.backtest_perp import build_panel, BIG_POOL ANN = 365 @@ -57,11 +58,11 @@ def conditional_sort(panel): if len(L) == 0 or len(S) == 0: continue cl, cs = set(L["sym"]), set(S["sym"]) - to = (len(cl ^ pl) + len(cs ^ ps)) / max(len(cl) + len(cs), 1) + traded = long_short_traded_notional(pl, cl, ps, cs) # 两腿实际成交名义 ff = lambda d: (0.0 if pd.isna(d["fwd_fund"].mean()) else d["fwd_fund"].mean()) fund_pnl = ff(S) - ff(L) # 空腿收, 多腿付 (计提资金费) rows.append((L["fwd_ret"].mean() - S["fwd_ret"].mean()) - - to * COST_BPS / 1e4 + fund_pnl) + - cost_from_traded(traded, COST_BPS) + fund_pnl) pl, ps = cl, cs return np.array(rows) diff --git a/CryptoFactors/src/crypto_factors/pipeline.py b/CryptoFactors/src/crypto_factors/pipeline.py index 7f4d2a896c4238c1a5f31a54b6478a276c4b021c..140dccc387fd2967861aaaa1b6f9e24bb33a3aee 100644 --- a/CryptoFactors/src/crypto_factors/pipeline.py +++ b/CryptoFactors/src/crypto_factors/pipeline.py @@ -13,6 +13,7 @@ from crypto_factors.config import ( DEFAULT_TARGET_VOL, PROJECT_ROOT, ) +from crypto_factors.costs import overlay_rebalance_costs MONOREPO_CORE = PROJECT_ROOT.parent / "packages" / "oeq-core" / "src" if MONOREPO_CORE.exists() and str(MONOREPO_CORE) not in sys.path: @@ -61,8 +62,21 @@ def _series_metrics(returns: list[float]) -> dict[str, float]: } -def evaluate_real_785d_perp_nav(root: Path = PROJECT_ROOT) -> dict[str, object]: - """Evaluate 785-day real Binance perpetual futures factor NAV series (2024-06-03 to 2026-07-27).""" +def evaluate_real_785d_perp_nav( + root: Path = PROJECT_ROOT, + rebalance_cost_bps_per_side: float = DEFAULT_COST_BPS_PER_SIDE, +) -> dict[str, object]: + """Evaluate 785-day real Binance perpetual futures factor NAV series (2024-06-03 to 2026-07-27). + + The three sleeve NAVs in ``equity_perp.csv`` are taken as published. The overlays + (inverse-vol weights, funding-squeeze gate, vol target up to 1.5x) are charged + ``rebalance_cost_bps_per_side`` on the gross notional they trade when sleeve + allocations change (see ``costs.overlay_rebalance_costs``). Before 2026-10-26 the + overlays were charged nothing; ``rebalance_cost_bps_per_side=0`` reproduces the + published table. Caveat: the sleeve NAVs themselves were produced by the + pre-2026-10-26 long-short cost formula, which charged about half of the stated + 5 bp per side, so every figure here is still an upper bound. + """ nav_path = root / "data" / "results" / "equity_perp.csv" with nav_path.open("r", encoding="utf-8") as fh: rows = list(csv.DictReader(fh)) @@ -75,9 +89,13 @@ def evaluate_real_785d_perp_nav(root: Path = PROJECT_ROOT) -> dict[str, object]: n = len(rets[core3[0]]) ew_daily = [sum(rets[c][t] for c in core3) / 3.0 for t in range(n)] vw_ew = volatility_target_weights(ew_daily, target_vol=0.15, lookback=20, max_leverage=1.5, annualization=365.0) - ew_vt = [ew_daily[t] * vw_ew[t] for t in range(n)] + ew_vt_cost = overlay_rebalance_costs( + [{c: vw_ew[t] / 3.0 for c in core3} for t in range(n)], rebalance_cost_bps_per_side + ) + ew_vt = [ew_daily[t] * vw_ew[t] - ew_vt_cost[t] for t in range(n)] - inv_gated: list[float] = [] + inv_gross: list[float] = [] + inv_weights: list[dict[str, float]] = [] for t in range(n): if t < 20: w = {c: 1.0 / 3.0 for c in core3} @@ -88,10 +106,17 @@ def evaluate_real_785d_perp_nav(root: Path = PROJECT_ROOT) -> dict[str, object]: w["资金费率"] *= 0.25 s = sum(w.values()) w = {c: w[c] / s for c in core3} - inv_gated.append(sum(w[c] * rets[c][t] for c in core3)) + inv_weights.append(w) + inv_gross.append(sum(w[c] * rets[c][t] for c in core3)) - vw_ig = volatility_target_weights(inv_gated, target_vol=0.15, lookback=20, max_leverage=1.5, annualization=365.0) - inv_gated_vt = [inv_gated[t] * vw_ig[t] for t in range(n)] + # The vol target is sized on the gross overlay series, exactly as published. + vw_ig = volatility_target_weights(inv_gross, target_vol=0.15, lookback=20, max_leverage=1.5, annualization=365.0) + inv_cost = overlay_rebalance_costs(inv_weights, rebalance_cost_bps_per_side) + inv_vt_cost = overlay_rebalance_costs( + [{c: vw_ig[t] * inv_weights[t][c] for c in core3} for t in range(n)], rebalance_cost_bps_per_side + ) + inv_gated = [inv_gross[t] - inv_cost[t] for t in range(n)] + inv_gated_vt = [inv_gross[t] * vw_ig[t] - inv_vt_cost[t] for t in range(n)] st_ew = _series_metrics(ew_daily) st_vt = _series_metrics(ew_vt) @@ -100,14 +125,27 @@ def evaluate_real_785d_perp_nav(root: Path = PROJECT_ROOT) -> dict[str, object]: return { "real_perp_days": n, + "real_785d_overlay_cost_bps_per_side": float(rebalance_cost_bps_per_side), "real_785d_static_sharpe": st_ew["sharpe"], "real_785d_static_max_dd_pct": st_ew["max_dd_pct"], "real_785d_voltarget_sharpe": st_vt["sharpe"], + "real_785d_voltarget_cum_ret_pct": st_vt["cum_ret_pct"], + "real_785d_voltarget_max_dd_pct": st_vt["max_dd_pct"], + "real_785d_voltarget_calmar": st_vt["calmar"], "real_785d_inv_vol_gated_sharpe": st_ig["sharpe"], "real_785d_inv_vol_gated_cum_ret_pct": st_ig["cum_ret_pct"], + "real_785d_inv_vol_gated_max_dd_pct": st_ig["max_dd_pct"], + "real_785d_inv_vol_gated_calmar": st_ig["calmar"], "real_785d_inv_vol_vt_sharpe": st_ig_vt["sharpe"], + "real_785d_inv_vol_vt_cum_ret_pct": st_ig_vt["cum_ret_pct"], "real_785d_inv_vol_vt_max_dd_pct": st_ig_vt["max_dd_pct"], "real_785d_inv_vol_vt_calmar": st_ig_vt["calmar"], + "real_785d_inv_vol_vt_nw_t": st_ig_vt["nw_t"], + "real_785d_overlay_cost_ann_pct": { + "volatility_targeted_15pct": round(sum(ew_vt_cost) / n * 365.0 * 100.0, 2), + "inv_vol_funding_squeeze_gated": round(sum(inv_cost) / n * 365.0 * 100.0, 2), + "inv_vol_funding_gated_voltarget_15pct": round(sum(inv_vt_cost) / n * 365.0 * 100.0, 2), + }, } @@ -187,7 +225,11 @@ def run_sample_pipeline(root: Path = PROJECT_ROOT) -> dict[str, object]: max_leverage=1.5, annualization=365.0, ) - vol_targeted_returns = [r * w for r, w in zip(static_comp_returns, vol_weights)] + # Leverage changes of the vol target trade the whole long-short composite (gross 2 per unit). + leverage_costs = overlay_rebalance_costs( + [{"composite": w} for w in vol_weights], DEFAULT_COST_BPS_PER_SIDE + ) + vol_targeted_returns = [r * w - c for r, w, c in zip(static_comp_returns, vol_weights, leverage_costs)] boundary = ClaimBoundary( project_slug="crypto-factors", @@ -218,7 +260,7 @@ def run_sample_pipeline(root: Path = PROJECT_ROOT) -> dict[str, object]: for i, name in enumerate(factor_names) } - regime_vol_targeted = [r * w for r, w in zip(regime_comp_returns, vol_weights)] + regime_vol_targeted = [r * w - c for r, w, c in zip(regime_comp_returns, vol_weights, leverage_costs)] real_perp_summary = evaluate_real_785d_perp_nav(root=root) return { diff --git a/CryptoFactors/tests/test_cost_accounting.py b/CryptoFactors/tests/test_cost_accounting.py new file mode 100644 index 0000000000000000000000000000000000000000..a6e3faa8693bb7cc76241f5053038fbb25f68684 --- /dev/null +++ b/CryptoFactors/tests/test_cost_accounting.py @@ -0,0 +1,94 @@ +"""Transaction-cost accounting: long-short books are charged on traded notional of both legs, +and composite overlays are charged when they change sleeve allocations.""" +from __future__ import annotations + +import importlib.util +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "src")) + +from crypto_factors.costs import ( # noqa: E402 + cost_from_traded, + leg_traded_notional, + long_short_traded_notional, + overlay_rebalance_costs, +) + +HAS_PANDAS = importlib.util.find_spec("pandas") is not None + + +class TestTradedNotional(unittest.TestCase): + def test_one_swap_per_leg_trades_two_units(self) -> None: + # Two names per leg; one name swapped in each leg: sell 0.5 + buy 0.5 per leg. + traded = long_short_traded_notional({"A", "B"}, {"A", "C"}, {"X", "Y"}, {"X", "Z"}) + self.assertAlmostEqual(traded, 2.0) + # 5 bp per side on 2 units of notional = 10 bp of capital. + self.assertAlmostEqual(cost_from_traded(traded, 5.0), 0.0010) + # The pre-2026-10-26 formula charged the average of the two legs: half of this. + old_to = (len({"A", "B"} ^ {"A", "C"}) + len({"X", "Y"} ^ {"X", "Z"})) / 4 + self.assertAlmostEqual(cost_from_traded(traded, 5.0), 2.0 * old_to * 5.0 / 1e4) + + def test_initial_build_and_full_rotation(self) -> None: + self.assertAlmostEqual(leg_traded_notional(set(), {"A", "B"}), 1.0) + self.assertAlmostEqual(leg_traded_notional({"A", "B"}, {"C", "D"}), 2.0) + self.assertAlmostEqual(leg_traded_notional({"A", "B"}, {"A", "B"}), 0.0) + + def test_leg_size_change_reweights_names_that_stay(self) -> None: + # 1/2 -> 1/3 on A and B (2 x 1/6) plus buying 1/3 of C. + self.assertAlmostEqual(leg_traded_notional({"A", "B"}, {"A", "B", "C"}), 2.0 / 3.0) + + +class TestOverlayRebalanceCosts(unittest.TestCase): + def test_weight_change_charges_gross_notional(self) -> None: + exposures = [{"a": 0.5, "b": 0.5}, {"a": 0.75, "b": 0.25}, {"a": 0.75, "b": 0.25}] + costs = overlay_rebalance_costs(exposures, cost_bps_per_side=5.0) + # sum |dw| = 0.5 of capital in $1-long/$1-short sleeves -> 1.0 notional -> 5 bp. + self.assertEqual(len(costs), 3) + self.assertAlmostEqual(costs[0], 0.0) + self.assertAlmostEqual(costs[1], 0.0005) + self.assertAlmostEqual(costs[2], 0.0) + + def test_leverage_change_is_charged(self) -> None: + costs = overlay_rebalance_costs([{"c": 1.0}, {"c": 1.5}, {"c": 1.2}], cost_bps_per_side=5.0) + self.assertAlmostEqual(costs[1], 0.5 * 2.0 * 5.0 / 1e4) + self.assertAlmostEqual(costs[2], 0.3 * 2.0 * 5.0 / 1e4) + self.assertEqual(overlay_rebalance_costs([{"c": 1.0}, {"c": 1.5}], cost_bps_per_side=0.0), [0.0, 0.0]) + + +@unittest.skipUnless(HAS_PANDAS, "pandas is required for the backtest toy example") +class TestBacktestFactorToyPanel(unittest.TestCase): + def test_long_short_cost_is_charged_on_both_legs(self) -> None: + import pandas as pd + + from crypto_factors.backtest import COST_BPS, backtest_factor + + syms = [f"S{i}" for i in range(10)] + # Quintiles of 10 names hold 2 names per leg. All forward returns are zero, + # so each day's long-short return is minus the cost charged that day. + day_signals = { + "2026-01-01": list(range(10)), # long S8,S9 short S0,S1 + "2026-01-02": [0, 2, 1, 3, 4, 5, 6, 9, 8, 7], # long S7,S8 short S0,S2 + "2026-01-03": [0, 2, 1, 3, 4, 5, 6, 9, 8, 7], # unchanged + } + rows = [ + {"day": pd.Timestamp(day), "sym": sym, "sig_col": float(sig[i]), "fwd_ret": 0.0} + for day, sig in day_signals.items() + for i, sym in enumerate(syms) + ] + bt = backtest_factor(pd.DataFrame(rows), "sig_col", +1) + unit = COST_BPS / 1e4 + # Day 1 builds both legs (1 + 1 units), day 2 swaps one name per leg (1 + 1 units). + self.assertEqual(list(bt["traded"].round(12)), [2.0, 2.0, 0.0]) + self.assertEqual(list(bt["turnover"].round(12)), [1.0, 1.0, 0.0]) + for got, want in zip(bt["ls"], [-2.0 * unit, -2.0 * unit, 0.0]): + self.assertAlmostEqual(got, want) + # Long-only line: one leg of gross 1. + for got, want in zip(bt["long"], [-1.0 * unit, -1.0 * unit, 0.0]): + self.assertAlmostEqual(got, want) + + +if __name__ == "__main__": + unittest.main() diff --git a/CryptoFactors/tests/test_published_results.py b/CryptoFactors/tests/test_published_results.py index f3d3d5e2760d55995255e939f9858b01128c59fd..81829b759989fda63a5963345f0e059c5112fc6e 100644 --- a/CryptoFactors/tests/test_published_results.py +++ b/CryptoFactors/tests/test_published_results.py @@ -10,6 +10,7 @@ ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT / "src")) from crypto_factors import config, run_sample_pipeline +from crypto_factors.pipeline import evaluate_real_785d_perp_nav from crypto_factors.cli import main @@ -49,11 +50,26 @@ class TestCryptoPublishedResults(unittest.TestCase): self.assertGreater(result["sample_vol_targeted_mean_net"], 0.0) self.assertGreater(result["sample_regime_conditioned_mean_net"], 0.0) self.assertEqual(result["real_perp_days"], 785) + # Overlays now pay 5 bp per side on the notional they trade (published sleeve NAVs unchanged). + self.assertEqual(result["real_785d_overlay_cost_bps_per_side"], config.DEFAULT_COST_BPS_PER_SIDE) self.assertAlmostEqual(result["real_785d_static_sharpe"], 1.87, places=2) - self.assertAlmostEqual(result["real_785d_inv_vol_gated_sharpe"], 2.19, places=2) - self.assertAlmostEqual(result["real_785d_inv_vol_vt_sharpe"], 2.12, places=2) - self.assertAlmostEqual(result["real_785d_inv_vol_vt_max_dd_pct"], -8.55, places=2) - self.assertAlmostEqual(result["real_785d_inv_vol_vt_calmar"], 4.33, places=2) + self.assertAlmostEqual(result["real_785d_voltarget_sharpe"], 1.79, places=2) + self.assertAlmostEqual(result["real_785d_inv_vol_gated_sharpe"], 2.05, places=2) + self.assertAlmostEqual(result["real_785d_inv_vol_vt_sharpe"], 1.96, places=2) + self.assertAlmostEqual(result["real_785d_inv_vol_vt_max_dd_pct"], -9.25, places=2) + self.assertAlmostEqual(result["real_785d_inv_vol_vt_calmar"], 3.64, places=2) + + def test_real_785d_overlays_without_rebalancing_cost_reproduce_published_table(self) -> None: + published = evaluate_real_785d_perp_nav(root=ROOT, rebalance_cost_bps_per_side=0.0) + self.assertAlmostEqual(published["real_785d_static_sharpe"], 1.87, places=2) + self.assertAlmostEqual(published["real_785d_voltarget_sharpe"], 1.85, places=2) + self.assertAlmostEqual(published["real_785d_inv_vol_gated_sharpe"], 2.19, places=2) + self.assertAlmostEqual(published["real_785d_inv_vol_vt_sharpe"], 2.12, places=2) + self.assertAlmostEqual(published["real_785d_inv_vol_vt_max_dd_pct"], -8.55, places=2) + self.assertAlmostEqual(published["real_785d_inv_vol_vt_calmar"], 4.33, places=2) + charged = evaluate_real_785d_perp_nav(root=ROOT) + for key in ("real_785d_voltarget_sharpe", "real_785d_inv_vol_gated_sharpe", "real_785d_inv_vol_vt_sharpe"): + self.assertLess(charged[key], published[key], msg=key) def test_real_785d_perp_validation_table(self) -> None: path = ROOT / "reports" / "real_785d_perp_validation.csv" diff --git a/EMFactorTiming/.github/workflows/ci.yml b/EMFactorTiming/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..6160022e40be4465aea49a34b49b6921a6adce3e --- /dev/null +++ b/EMFactorTiming/.github/workflows/ci.yml @@ -0,0 +1,37 @@ +# Synced from open-economic-quant/EMFactorTiming/.github/workflows/ci.yml by +# scripts/sync_ecosystem.py; edit it in the monorepo, not here. +name: CI + +on: + push: + branches: ["main"] + pull_request: + branches: ["main"] + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Python 3.12 + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.12" + cache: pip + cache-dependency-path: pyproject.toml + + - name: Install project with test dependencies + run: | + python -m pip install --upgrade pip + python -m pip install -e ".[dev]" + + - name: Run tests + run: python -m pytest diff --git a/EMFactorTiming/README.md b/EMFactorTiming/README.md index 445abc0bd1393d79980cc7bf3a620346eec225f7..7f8fc60a2e91406ef2d2171bfdae5865d356a374 100644 --- a/EMFactorTiming/README.md +++ b/EMFactorTiming/README.md @@ -99,7 +99,18 @@ Evaluated directly on the 312 monthly out-of-sample portfolio return series acro | `shrink_mean:rule` ($\kappa = 240$) | +1.3564 | 2.1325 | 2.0522 | 0.0558 | -3.60 | 9.15 | | `eb_shrink_mean:rule` (36m adaptive $\kappa_t$) | +1.2116 | 2.0113 | 1.9186 | 0.0605 | -3.43 | 8.81 | | `gbrt_rs:own` (forecast-shrunk GBRT) | +1.1835 | 2.0937 | 1.7050 | 0.2436 | -3.80 | 7.63 | -| **`turnover_damped_blend` (75% $\kappa=240$ + 25% `gbrt_rs`)** | **+1.3131** | **2.1719** | **2.0122** | **0.1028** | **-3.64** | **8.95** | +| `turnover_damped_blend` (75% $\kappa=240$ + 25% `gbrt_rs`) | +1.3131 | 2.1719 | 2.0122 | 0.1028 | -3.64 | 8.95 | + +Three caveats. The turnover-damped blend has the highest gross Sharpe but not the highest +net Sharpe: at 20 bp it reaches 2.0122, below $\kappa = 240$ alone (2.0522), because it +turns over 0.1028 a month against 0.0558. The blend's $\kappa = 240$ and its 75/25 weight +were chosen after seeing these same 312 out-of-sample months, so differences between rows +are in-sample model selection, not an out-of-sample test. And no committed script writes +`reports/jkp_em/eb_and_long_only_summary.csv`, or the `reports/post_2025_oos_2026_10/` and +`reports/live_readiness_2026_10/` tables used below and in the 2026-10 audit: the blend is +not implemented in `src/`, and the committed `eb_shrink_mean` rule sets $\kappa_t$ from an +expanding within/between-variance ratio clipped to [12, 600] (`src/emft/features.py`), not +the "36m rolling inverse-vol adaptive kappa in {60,120,240}" described in that CSV. ### Post-2025 Out-of-Sample Extension Through Latest Trading Day (`2026-01` to `2026-10-21`, 10 Months / 202 Trading Days) @@ -122,7 +133,7 @@ Extended from the JKP `2025-12` cutoff through `2026-10-21` using 49 daily MSCI | Layer | State | |---|---| -| Pipeline, tests, synthetic validation | complete — 15 tests pass; size/power in `reports/validation/` | +| Pipeline, tests, synthetic validation | complete — 19 tests pass (2026-10-26); size/power in `reports/validation/` | | Real-data run on JKP factors | complete — `reports/jkp_em/` (OLS, elastic net, trees, neural net) | | Robustness | complete for κ, OOS start, factor weighting, time-varying classification, costs, break-even costs; size-dependent costs pending | | Extensions | real-time forecast shrinkage and U.S. state variables (exploratory) | @@ -132,7 +143,7 @@ Extended from the JKP `2025-12` cutoff through `2026-10-21` using 49 daily MSCI ```bash pip install -e ".[dev]" # or: pip install numpy pandas scikit-learn scipy matplotlib pyyaml pyarrow pytest -make test # 15 tests: loader, macro, leakage, market history, recovery, null, transfer, real-time shrinkage +make test # 19 tests: loader, macro, leakage, market history, recovery, null, transfer, real-time shrinkage, published-table checks make validate # size/power simulation (~3 min) make demo # full pipeline on synthetic data (~8 min) make run # main real-data run incl. neural net (~17 min); files in data/raw/ diff --git a/EMFactorTiming/STATUS.md b/EMFactorTiming/STATUS.md index 2a43678bbb489eca23e99955ff8789584a9e9bfa..2e13cadf77621bfb1b8b8ae41e8a755fa0c57e79 100644 --- a/EMFactorTiming/STATUS.md +++ b/EMFactorTiming/STATUS.md @@ -11,8 +11,8 @@ - Expanding-window annual refits with three training scopes (EM, DM-only, pooled); OLS, elastic net, gradient-boosted trees, neural-net ensemble; rules: own mean, shrinkage mean, factor momentum. -- 15 tests pass (loader, macro loader, leakage, market history, signal recovery, null, transfer, - real-time forecast shrinkage). +- 19 tests pass as of 2026-10-26 (loader, macro loader, leakage, market history, signal recovery, + null, transfer, real-time forecast shrinkage, published JKP result tables). Size/power: 87.5% null rejection vs the own mean, 5.0% vs the shrinkage mean. - **Main run** `reports/jkp_em/` (JKP all countries, 153 factors, monthly, capped VW; downloaded 2026-09-29, data to 2025-12; 22 EM markets; incl. neural net). diff --git a/EMFactorTiming/project.yaml b/EMFactorTiming/project.yaml index 80ed4345b4a8f91249714125903f442b815d7cdc..9b40b26ae7d012741f7422eaffac007891b2bb4c 100644 --- a/EMFactorTiming/project.yaml +++ b/EMFactorTiming/project.yaml @@ -13,7 +13,7 @@ authors: - Repository owner and maintainer original_source: EMFactorTiming workspace project original_sample_period: JKP factor returns from 1926 (United States) and 1986 onward for international developed and emerging markets. -updated_sample_period: Data through 2025-12 (downloaded 2026-09-29); out-of-sample evaluation across 312 months (2000-01 through 2025-12) covering 801,536 country-factor-months in 22 emerging markets. +updated_sample_period: JKP panel through 2025-12 (312 OOS months, 801,536 country-factor-months in 22 emerging markets) plus tradable 49-ETF out-of-sample daily tracking through 2026-10-28. data_sources: - Jensen, Kelly, and Pedersen (2023) global factor returns (jkpfactors.com, 153 factors across 93 countries) - MSCI market classification and historical reclassification announcements @@ -35,7 +35,7 @@ github_url: https://github.com/YangXiaoShawn/open-economic-quant-em-factor-timin site_url: https://yangxiaoshawn.github.io/projects/em-factor-timing/ dataset_url: https://huggingface.co/datasets/ShawnChamberlain/open-economic-quant-research-data/tree/main/EMFactorTiming space_url: https://huggingface.co/spaces/ShawnChamberlain/open-economic-quant-research-observatory?project=em-factor-timing -last_updated: 2026-09-29 +last_updated: 2026-10-28 limitations: Evidence is out-of-sample predictive comparison, not causal identification. Factor returns are gross of their own stock-level rebalancing costs and signed by the original studies, so Sharpe levels must be read comparatively. Results depend on factor weighting (equal-weighted factors show positive R2_OS vs shrinkage mean, whereas capped value-weighted factors do not). catalog: field: emerging-markets diff --git a/EMFactorTiming/pyproject.toml b/EMFactorTiming/pyproject.toml index b8b0f2b0a5af6ca8dcb4123a6126a5512c5beefa..b984e35c4b87601ec38d4bc7456825a9a9442573 100644 --- a/EMFactorTiming/pyproject.toml +++ b/EMFactorTiming/pyproject.toml @@ -13,6 +13,9 @@ authors = [{ name = "Yang Xiao" }] dependencies = [ "matplotlib>=3.8", "numpy>=1.26", + # Shared monorepo package, pinned by commit so this project installs standalone; + # inside the monorepo, uv uses the workspace copy (root tool.uv.sources). + "oeq-core @ git+https://github.com/YangXiaoShawn/open-economic-quant@3d309b7e90ca7b970bb5396d3bb781c92de4ea7e#subdirectory=packages/oeq-core", "pandas>=2.1", "pyyaml>=6.0", "scikit-learn>=1.4", @@ -25,6 +28,9 @@ dev = ["pytest>=8", "ruff>=0.8"] [project.scripts] emft = "emft.cli:main" +[tool.hatch.metadata] +allow-direct-references = true + [tool.hatch.build.targets.wheel] packages = ["src/emft"] diff --git a/Macroeconomics/.github/workflows/ci.yml b/Macroeconomics/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..eddab2e6c710508ec8d9a0570c1f7efce126112f --- /dev/null +++ b/Macroeconomics/.github/workflows/ci.yml @@ -0,0 +1,37 @@ +# Synced from open-economic-quant/Macroeconomics/.github/workflows/ci.yml by +# scripts/sync_ecosystem.py; edit it in the monorepo, not here. +name: CI + +on: + push: + branches: ["main"] + pull_request: + branches: ["main"] + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Python 3.12 + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.12" + cache: pip + cache-dependency-path: pyproject.toml + + - name: Install project with test dependencies + run: | + python -m pip install --upgrade pip + python -m pip install -e ".[dev]" + + - name: Run tests + run: python -m pytest diff --git a/Macroeconomics/.gitignore b/Macroeconomics/.gitignore index 6cd75870fdeb6f6667a24b538cb0c215b6b10909..39a499cf592afe4494262cbb0df0d4c7dbaf8b1f 100644 --- a/Macroeconomics/.gitignore +++ b/Macroeconomics/.gitignore @@ -1,21 +1,11 @@ -.DS_Store +# upload constraints for macroeconomics +artifacts/ +generated/ +data/generated/ +raw/ +tmp/ +.git/ .venv/ __pycache__/ -*.py[cod] .pytest_cache/ .ruff_cache/ -.coverage -htmlcov/ -build/ -dist/ -*.egg-info/ -data/generated/* -!data/generated/.gitkeep -data/raw/* -reports/generated/* -!reports/generated/.gitkeep -.streamlit/ -tmp/ -api.txt -.env -.env.* diff --git a/Macroeconomics/AGENTS.md b/Macroeconomics/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..21f9fe2e335ca91d9f32b729f813ca4e232e6f40 --- /dev/null +++ b/Macroeconomics/AGENTS.md @@ -0,0 +1,46 @@ +# Repository Instructions + +## Mission + +Build a reproducible real-time macroeconomic nowcasting system that reconstructs the information set available at each historical forecast origin. The core comparison is a valid vintage-aware backtest versus a clearly labeled latest-revised-data backtest. + +## Non-negotiable research rules + +- Never allow an observation whose `availability_date` is later than the requested `as_of_date` into a feature matrix. +- Never substitute latest-revised values for historical vintages unless the output is explicitly labeled `latest_revised`. +- Preserve raw source fields and provenance. Derived values must record the transformation and source vintage. +- Never fabricate releases, vintages, metrics, forecasts, or policy conclusions. +- Fixture-backed outputs must be labeled `synthetic_fixture`; they demonstrate behavior, not empirical findings about the economy. +- When exact intraday release timing is unavailable, use the documented end-of-day convention and do not claim pre-release availability. +- Target definitions must state units and transformation (for example, `persons_change_mom`, `percent_change_mom`, or `percent_change_qoq_saar`). +- Any attribution that is not an exact additive decomposition must be labeled approximate. + +## Architecture and storage + +- Put production logic in the typed `src/macro_nowcast` package, never only in notebooks. +- Use configuration-driven series definitions under `config/`. +- Canonical vintage rows include series ID, observation date, real-time start/end, availability date, value, units, frequency, seasonal adjustment, transformation, download timestamp, and source metadata. +- Use Parquet for durable columnar artifacts and DuckDB for local analytical queries. Keep fixture data small. +- Keep raw downloads immutable. Write derived datasets to separate directories. +- Live FRED/ALFRED access is optional, requires `FRED_API_KEY` plus an explicit authorization gate, and must remain disabled by default under the currently published FRED terms. Unit tests must use committed synthetic fixtures and work offline. Do not persist API-derived content without documented permission. + +## Implementation order + +1. Maintain `docs/PROJECT_PLAN.md`, `docs/DECISION_LOG.md`, and `STATUS.md`. +2. Complete the monthly payroll vertical slice before expanding targets or model families. +3. Add strict as-of and leakage tests before reporting model results. +4. Compare transparent baselines with advanced models using the same forecast origins. +5. Generate reports and the dashboard only from versioned pipeline outputs. + +## Quality workflow + +- Use Python 3.12, type annotations, pytest, and ruff. +- After each major phase, run the narrow tests first and then the full suite. +- Prefer deterministic expanding-window evaluation; never tune on the final evaluation period. +- Each chart or table must identify data mode, series/target, vintage/as-of rule, horizon, and sample period. +- Update `STATUS.md` after material work, including commands run, validated behavior, limitations, and next milestones. +- Record consequential assumptions or design changes in `docs/DECISION_LOG.md`. + +## Common commands + +The supported workflow is exposed through `make setup`, `make download-sample`, `make build-vintages`, `make validate-asof`, `make backtest`, `make test`, `make reproduce-sample`, `make reproduce-multitarget`, `make policy-brief`, `make report`, and `make dashboard`. diff --git a/Macroeconomics/LICENSE b/Macroeconomics/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..93d9c4ee297e613c630043346bd1b5e98c1b28bb --- /dev/null +++ b/Macroeconomics/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Yang Xiao + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Macroeconomics/Makefile b/Macroeconomics/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..1f67b9c509d1770db44ee8070b5ecab08cad5384 --- /dev/null +++ b/Macroeconomics/Makefile @@ -0,0 +1,81 @@ +RUNTIME_PYTHON ?= python3.12 +VENV := .venv +PYTHON := $(VENV)/bin/python +CLI := $(PYTHON) -m macro_nowcast.cli + +.PHONY: setup download-sample build-vintages validate-asof backtest test reproduce-sample reproduce-multitarget index-empsit-clocks acquire-dol-claims acquire-fed-g17 acquire-treasury-rates acquire-bea-nipa-levels audit-bea-nipa-levels acquire-census-retail acquire-census-housing audit-agency-vintages ingest-agency-vintages reproduce-official-pilot policy-brief report dashboard lint clean-generated + +setup: + $(RUNTIME_PYTHON) scripts/check_python.py + $(RUNTIME_PYTHON) -m venv $(VENV) + $(PYTHON) -m pip install --upgrade pip + $(PYTHON) -m pip install -e '.[dev]' + +download-sample: + $(CLI) prepare-sample --config config/sample.toml + +build-vintages: + $(CLI) build-vintages --config config/sample.toml + +validate-asof: + $(CLI) validate-asof --config config/sample.toml + +backtest: + $(CLI) backtest --config config/sample.toml + +test: + $(PYTHON) -m pytest + +lint: + $(PYTHON) -m ruff check . + +reproduce-sample: + $(CLI) reproduce-sample --config config/sample.toml + +reproduce-multitarget: + $(CLI) reproduce-multitarget --config config/targets.toml + +index-empsit-clocks: + $(CLI) index-empsit-clocks --source-dir data/raw/agency_vintages/bls-empsit-clock-txt --release-index data/raw/agency_vintages/empsit-release-index.json + +acquire-dol-claims: + $(CLI) acquire-dol-claims --output-dir data/raw/agency_vintages/dol-ui-claims --start-year 2002 + +acquire-fed-g17: + $(CLI) acquire-fed-g17 --output-dir data/raw/agency_vintages/fed-g17 --start-year 1997 + +acquire-treasury-rates: + $(CLI) acquire-treasury-rates --output-dir data/raw/agency_vintages/treasury-yield-curve --start-year 2002 + +acquire-bea-nipa-levels: + $(CLI) acquire-bea-nipa-levels --output-dir data/raw/agency_vintages/bea-nipa-levels --clock-evidence data/raw/agency_vintages/bea-gdp-news/clock-evidence.json --published-growth data/raw/agency_vintages/gdp-gdi-vintage-history.xlsx + +audit-bea-nipa-levels: + $(CLI) audit-bea-nipa-levels --source-dir data/raw/agency_vintages/bea-nipa-levels --clock-evidence data/raw/agency_vintages/bea-gdp-news/clock-evidence.json --published-growth data/raw/agency_vintages/gdp-gdi-vintage-history.xlsx + +acquire-census-retail: + $(CLI) acquire-census-retail --output-dir data/raw/agency_vintages/census-marts --start-year 2003 + +acquire-census-housing: + $(CLI) acquire-census-housing --output-dir data/raw/agency_vintages/census-nrc --start-year 2003 + +audit-agency-vintages: + $(CLI) audit-agency-vintages --raw-dir data/raw/agency_vintages --output data/generated/agency_vintages/audit_manifest.json + +ingest-agency-vintages: + $(CLI) ingest-agency-vintages --raw-dir data/raw/agency_vintages --output-dir data/generated/official_vintages --overwrite + +reproduce-official-pilot: + $(CLI) reproduce-official-pilot --source-dir data/generated/official_vintages --output-dir data/generated/official_pilot --overwrite + +policy-brief: + $(CLI) policy-brief --config config/sample.toml + +report: + $(CLI) report --config config/sample.toml + +dashboard: + $(PYTHON) -m streamlit run scripts/dashboard_entry.py -- --config config/sample.toml + +clean-generated: + $(CLI) clean-generated --config config/sample.toml diff --git a/Macroeconomics/STATUS.md b/Macroeconomics/STATUS.md index 3fa52dd953d6acc857f6e452ba0217fe7b61405c..90ed5af10334cef7c42e4a396f27456e0fe59d98 100644 --- a/Macroeconomics/STATUS.md +++ b/Macroeconomics/STATUS.md @@ -251,7 +251,8 @@ empirical finding about real forecast accuracy, the U.S. economy, or policy. pre-release forecast origins, 5,766 feature cells, 450 target rows, 1,980 forecasts, 54 metric rows, 893 intentionally leaked naive cells, three news updates, three briefs, and zero strict-mode timing violations. -- `.venv/bin/pytest -q` — **215 passed**, with one non-failing joblib +- `.venv/bin/pytest -q` — **215 passed** when this record was made (the suite now collects 216 + tests, `pytest --collect-only`, 2026-10-26), with one non-failing joblib physical-core detection warning. - `.venv/bin/ruff check .` — passed. - Independent DuckDB artifact/count/timing audit — passed. diff --git a/Macroeconomics/fixtures/synthetic_payroll/README.md b/Macroeconomics/fixtures/synthetic_payroll/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2c5e7b2c79429b34d5cdf0012899428b4ecf211d --- /dev/null +++ b/Macroeconomics/fixtures/synthetic_payroll/README.md @@ -0,0 +1,3 @@ +# Synthetic payroll fixture + +This directory is generated deterministically by `make download-sample`. Every value and release time is artificial and exists only to test vintage, revision, mixed-frequency, and ragged-edge behavior. No file contains FRED, ALFRED, BLS, or other source-provider observations. diff --git a/Macroeconomics/fixtures/synthetic_payroll/manifest.json b/Macroeconomics/fixtures/synthetic_payroll/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..842a2d00f19ec2f8a4601da9dcf97827b6e398e2 --- /dev/null +++ b/Macroeconomics/fixtures/synthetic_payroll/manifest.json @@ -0,0 +1,24 @@ +{ + "description": "Deterministic synthetic FRED/ALFRED-shaped fixture; not economic data", + "fixture_generated_at": "2026-08-07T12:00:00+00:00", + "fixture_label": "synthetic_fixture", + "fred_api_accessed": false, + "network_used": false, + "observation_rows": 5261, + "payload_sha256": "1fe94118b13a22794993c04be0e6c85c4296966f97f5ff5213cd4fc7d827d11d", + "seed": 20260807, + "series": [ + "AWHMAN", + "CCSA", + "DGS10", + "HOUST", + "ICSA", + "INDPRO", + "PAYEMS", + "RSAFS", + "UMCSENT", + "UNRATE" + ], + "vintage_end": "2025-06-06T13:30:00+00:00", + "vintage_start": "2017-01-02T22:00:00+00:00" +} diff --git a/Macroeconomics/fixtures/synthetic_payroll/observation_vintages.parquet b/Macroeconomics/fixtures/synthetic_payroll/observation_vintages.parquet new file mode 100644 index 0000000000000000000000000000000000000000..9062755aa0d8bfbe2ebd001a125ae6eb7b40d3c9 --- /dev/null +++ b/Macroeconomics/fixtures/synthetic_payroll/observation_vintages.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1fe94118b13a22794993c04be0e6c85c4296966f97f5ff5213cd4fc7d827d11d +size 120059 diff --git a/Macroeconomics/fixtures/synthetic_payroll/series_catalog.parquet b/Macroeconomics/fixtures/synthetic_payroll/series_catalog.parquet new file mode 100644 index 0000000000000000000000000000000000000000..6360f45fe3174fd73f4347f1e29763b8b8bd1051 --- /dev/null +++ b/Macroeconomics/fixtures/synthetic_payroll/series_catalog.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:36f2e28b9e3bd5b96881309bd10a7ef4068180aeb4b844819b1f8b219ea7bc64 +size 3751 diff --git a/Macroeconomics/fixtures/synthetic_payroll/target_release_calendar.parquet b/Macroeconomics/fixtures/synthetic_payroll/target_release_calendar.parquet new file mode 100644 index 0000000000000000000000000000000000000000..a0e090b88be803a7777eba1eb883fa7cd41ee6eb --- /dev/null +++ b/Macroeconomics/fixtures/synthetic_payroll/target_release_calendar.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:37c9ebf202f1d81f291db53339fcaac1a2c14280d2ab2653102e65ee3001b681 +size 4982 diff --git a/Macroeconomics/project.yaml b/Macroeconomics/project.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4c2f0d71d26d54fc8acc9af720712facd39a99ad --- /dev/null +++ b/Macroeconomics/project.yaml @@ -0,0 +1,45 @@ +title: Macroeconomics +slug: macroeconomics +summary: Real-time macroeconomic forecasting, vintage reconstruction, and policy-shock analysis with public-source adapters. +research_question: How do release revisions and information available at each vintage affect nowcast and forecast quality? +why_it_matters: Vintage-aware evaluation prevents revised data from leaking into historical forecasts and overstating real-time performance. +research_fields: + - Macroeconomics + - Forecasting + - Policy analytics +project_type: research-replication +status: public-live +authors: + - Repository owner and maintainer +original_source: Macroeconomics workspace project +original_sample_period: Defined by each configured source and vintage archive. +updated_sample_period: Updated when a documented public-data refresh is released. +data_sources: + - FRED and ALFRED public observations + - BLS and BEA public APIs under guarded live-access settings + - Synthetic fixture datasets in data/fixtures/ +data_license: RIGHTS_UNKNOWN for raw third-party snapshots; included fixtures are publishable examples. +code_license: MIT; third-party components retain their own licenses. +reproduction_command: python -m macro_nowcast.pipeline +expected_runtime: Varies by source configuration and backtest horizon. +outputs: + - src/ + - reports/ + - scripts/ + - tests/ + - data/fixtures/ + - config/ +github_url: https://github.com/YangXiaoShawn/open-economic-quant-macroeconomics +site_url: https://yangxiaoshawn.github.io/projects/macroeconomics/ +dataset_url: https://huggingface.co/datasets/ShawnChamberlain/open-economic-quant-research-data/tree/main/Macroeconomics +space_url: https://huggingface.co/spaces/ShawnChamberlain/open-economic-quant-research-observatory +last_updated: 2026-08-10 +limitations: Real-time claims require an audited vintage source. Current BLS and BEA API observations are labeled latest-revised and are not presented as historical first releases. +catalog: + field: macro + accent: blue + tags: + - Nowcasting + - Vintage Data + - Policy Forecasting + metric: Guarded public adapters diff --git a/Macroeconomics/pyproject.toml b/Macroeconomics/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..ffa39d04cfce80bac2119aa22dae6caab579ca36 --- /dev/null +++ b/Macroeconomics/pyproject.toml @@ -0,0 +1,59 @@ +[build-system] +requires = ["hatchling>=1.27"] +build-backend = "hatchling.build" + +[project] +name = "macro-nowcast" +version = "0.1.0" +description = "Vintage-aware real-time macroeconomic nowcasting research engine" +readme = "README.md" +requires-python = ">=3.12" +license = {text = "MIT"} +authors = [{name = "Macroeconomics research project"}] +dependencies = [ + "duckdb>=1.1,<2", + "jinja2>=3.1", + "numpy>=2.0", + "plotly>=6.0", + "polars>=1.20", + "pypdf>=6.0", + "pyarrow>=18.0", + "scikit-learn>=1.6", + "scipy>=1.14", + "statsmodels>=0.14.4", + "streamlit>=1.42", + # Shared monorepo package, pinned by commit so this project installs standalone; + # inside the monorepo, uv uses the workspace copy (root tool.uv.sources). + "oeq-core @ git+https://github.com/YangXiaoShawn/open-economic-quant@3d309b7e90ca7b970bb5396d3bb781c92de4ea7e#subdirectory=packages/oeq-core", +] + +[project.optional-dependencies] +dev = [ + "pytest>=8.3", + "pytest-cov>=6.0", + "ruff>=0.9", +] + +[project.scripts] +macro-nowcast = "macro_nowcast.cli:main" + +[tool.hatch.metadata] +allow-direct-references = true + +[tool.hatch.build.targets.wheel] +packages = ["src/macro_nowcast"] + +[tool.pytest.ini_options] +addopts = "-ra --strict-markers" +testpaths = ["tests"] + +[tool.ruff] +line-length = 100 +target-version = "py312" + +[tool.ruff.lint] +select = ["E", "F", "I", "UP", "B", "SIM", "RUF"] + +[tool.ruff.lint.per-file-ignores] +"scripts/check_python.py" = ["UP036"] +"src/macro_nowcast/reporting.py" = ["E501", "RUF001"] diff --git a/Macroeconomics/scripts/check_python.py b/Macroeconomics/scripts/check_python.py new file mode 100644 index 0000000000000000000000000000000000000000..5b9261c8e5093de0b88e76ea9dbbb556662fd968 --- /dev/null +++ b/Macroeconomics/scripts/check_python.py @@ -0,0 +1,16 @@ +"""Fail early when setup is attempted with an unsupported interpreter.""" + +from __future__ import annotations + +import sys + + +def main() -> None: + if sys.version_info < (3, 12): + version = ".".join(str(part) for part in sys.version_info[:3]) + raise SystemExit(f"Python 3.12+ is required; received {version}") + print(f"Using Python {sys.version.split()[0]}") + + +if __name__ == "__main__": + main() diff --git a/Macroeconomics/scripts/dashboard_entry.py b/Macroeconomics/scripts/dashboard_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..db8bffc2f66ef17c5b4a95c1a461723d01a59f6d --- /dev/null +++ b/Macroeconomics/scripts/dashboard_entry.py @@ -0,0 +1,6 @@ +"""Streamlit entry point kept outside the package to avoid stdlib name shadowing.""" + +from macro_nowcast.dashboard import main + +if __name__ == "__main__": + main() diff --git a/Macroeconomics/src/macro_nowcast/__init__.py b/Macroeconomics/src/macro_nowcast/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cb093b3185a9f15646ab868881a17d8e51fc45e4 --- /dev/null +++ b/Macroeconomics/src/macro_nowcast/__init__.py @@ -0,0 +1,7 @@ +"""Vintage-aware real-time macroeconomic research engine.""" + +from __future__ import annotations + +__all__ = ["__version__"] + +__version__ = "0.1.0" diff --git a/Macroeconomics/src/macro_nowcast/__main__.py b/Macroeconomics/src/macro_nowcast/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..30bfb3619fa2920aaa3048d9ecb04ca6002a0db1 --- /dev/null +++ b/Macroeconomics/src/macro_nowcast/__main__.py @@ -0,0 +1,4 @@ +from macro_nowcast.cli import main + +if __name__ == "__main__": + main() diff --git a/Macroeconomics/src/macro_nowcast/adapters.py b/Macroeconomics/src/macro_nowcast/adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..73debed52f43877aae4992a7d81bd4839cbe473f --- /dev/null +++ b/Macroeconomics/src/macro_nowcast/adapters.py @@ -0,0 +1,720 @@ +"""Offline fixtures and guarded live FRED/ALFRED observation adapters.""" + +from __future__ import annotations + +import hashlib +import json +import os +import threading +import time +from collections.abc import Callable, Iterable, Mapping +from dataclasses import replace +from datetime import UTC, date, datetime +from pathlib import Path +from typing import Any, Protocol, cast +from urllib.error import HTTPError, URLError +from urllib.parse import urlencode +from urllib.request import Request, urlopen + +import polars as pl + +from macro_nowcast.config import FredAPIConfig, SeriesConfig +from macro_nowcast.schema import SchemaValidationError, VintageObservation + + +class AdapterError(RuntimeError): + """Base class for acquisition or source-parsing failures.""" + + +class AdapterAuthorizationError(AdapterError): + """Raised when live source access was not explicitly authorized.""" + + +class AdapterCredentialError(AdapterError): + """Raised when the configured FRED API key environment variable is absent.""" + + +class AdapterResponseError(AdapterError): + """Raised when a source response is malformed or violates the canonical schema.""" + + +class AdapterRequestError(AdapterError): + """Raised when a guarded live request ultimately fails.""" + + +class RetryableAdapterError(AdapterRequestError): + """A transport failure an injected client explicitly marks as retryable.""" + + +type Transport = Callable[[str, float], bytes | str] +type Sleep = Callable[[float], None] +type Clock = Callable[[], float] +type Now = Callable[[], datetime] + + +class ObservationAdapter(Protocol): + def fetch( + self, + series: SeriesConfig, + *, + observation_start: date | None = None, + observation_end: date | None = None, + ) -> list[VintageObservation]: ... + + +def _payload_mapping(payload: Mapping[str, Any] | bytes | str) -> Mapping[str, Any]: + if isinstance(payload, Mapping): + return payload + try: + if isinstance(payload, bytes): + text = payload.decode("utf-8") + elif isinstance(payload, str): + text = payload + else: + raise AdapterResponseError("response payload must be a JSON object") + decoded = json.loads(text) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise AdapterResponseError("response payload is not valid UTF-8 JSON") from exc + if not isinstance(decoded, Mapping): + raise AdapterResponseError("response payload must be a JSON object") + return decoded + + +def _iso_date(value: object, name: str) -> date: + if isinstance(value, datetime): + return value.date() + if isinstance(value, date): + return value + if isinstance(value, str): + candidate = value[:10] if "T" in value else value + try: + return date.fromisoformat(candidate) + except ValueError as exc: + raise AdapterResponseError(f"{name} must be an ISO date") from exc + raise AdapterResponseError(f"{name} must be an ISO date") + + +def _optional_iso_date(value: object, name: str) -> date | None: + if value in (None, ""): + return None + return _iso_date(value, name) + + +def _utc_now() -> datetime: + return datetime.now(UTC) + + +def _download_timestamp(value: object, fallback: datetime) -> datetime: + if value is None: + value = fallback + if isinstance(value, str): + normalized = f"{value[:-1]}+00:00" if value.endswith("Z") else value + try: + value = datetime.fromisoformat(normalized) + except ValueError as exc: + raise AdapterResponseError("download_timestamp must be an ISO datetime") from exc + if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None: + raise AdapterResponseError("download_timestamp must include a timezone") + return value.astimezone(UTC) + + +def _frequency(value: object) -> str: + if not isinstance(value, str) or not value.strip(): + raise AdapterResponseError("frequency metadata is required") + normalized = value.strip().lower() + aliases = { + "d": "daily", + "daily": "daily", + "w": "weekly", + "weekly": "weekly", + "bw": "biweekly", + "biweekly": "biweekly", + "m": "monthly", + "monthly": "monthly", + "q": "quarterly", + "quarterly": "quarterly", + "sa": "semiannual", + "semiannual": "semiannual", + "a": "annual", + "annual": "annual", + } + return aliases.get(normalized, normalized.replace(" ", "_")) + + +def _series_metadata(document: Mapping[str, Any]) -> Mapping[str, Any]: + explicit = document.get("series") + if isinstance(explicit, Mapping): + return explicit + fred_metadata = document.get("seriess") + if isinstance(fred_metadata, list) and fred_metadata: + first = fred_metadata[0] + if isinstance(first, Mapping): + return first + return {} + + +def _metadata_text( + row: Mapping[str, Any], + series_metadata: Mapping[str, Any], + document: Mapping[str, Any], + *names: str, +) -> object | None: + for values in (row, series_metadata, document): + for name in names: + if values.get(name) not in (None, ""): + return values[name] + return None + + +def _release_lookup( + release_dates: Mapping[date | str, date | datetime | str] | None, + observation_date: date, +) -> date | datetime | str | None: + if release_dates is None: + return None + return release_dates.get(observation_date, release_dates.get(observation_date.isoformat())) + + +def parse_fred_observations( + payload: Mapping[str, Any] | bytes | str, + *, + series: SeriesConfig | None = None, + series_id: str | None = None, + units: str | None = None, + frequency: str | None = None, + seasonal_adjustment: str | None = None, + transformation: str | None = None, + source: str | None = None, + provenance_label: str | None = None, + download_timestamp: datetime | None = None, + release_dates: Mapping[date | str, date | datetime | str] | None = None, +) -> list[VintageObservation]: + """Parse a FRED/ALFRED JSON response into canonical vintage observations. + + When an explicit release/availability date is absent, ALFRED's + ``realtime_start`` is used as the availability date and that inference is + recorded in ``source_metadata``. Missing FRED values represented by ``.`` are + retained as nulls rather than silently dropped. + """ + + document = _payload_mapping(payload) + raw_observations = document.get("observations") + if not isinstance(raw_observations, list): + raise AdapterResponseError("response must contain an observations array") + metadata = _series_metadata(document) + downloaded_at = _download_timestamp( + download_timestamp or document.get("download_timestamp", document.get("downloaded_at")), + _utc_now(), + ) + + configured_series_id = series.series_id if series is not None else series_id + configured_units = series.units if series is not None else units + configured_frequency = series.frequency if series is not None else frequency + configured_adjustment = ( + series.seasonal_adjustment if series is not None else seasonal_adjustment + ) + configured_transformation = series.transformation if series is not None else transformation + configured_source = series.source if series is not None else source + + response_metadata = { + key: value + for key, value in document.items() + if key not in {"observations", "seriess", "series", "download_timestamp", "downloaded_at"} + } + parsed: list[VintageObservation] = [] + for index, observation in enumerate(raw_observations): + if not isinstance(observation, Mapping): + raise AdapterResponseError(f"observation {index} must be an object") + row = cast(Mapping[str, Any], observation) + row_series_id = configured_series_id or _metadata_text( + row, + metadata, + document, + "series_id", + "id", + ) + row_units = configured_units or _metadata_text( + row, + metadata, + document, + "units_short", + "units", + ) + row_frequency = configured_frequency or _metadata_text( + row, + metadata, + document, + "frequency_short", + "frequency", + ) + row_adjustment = configured_adjustment or _metadata_text( + row, + metadata, + document, + "seasonal_adjustment_short", + "seasonal_adjustment", + ) + row_transformation = configured_transformation or _metadata_text( + row, + metadata, + document, + "transformation", + ) + row_source = source or configured_source or document.get("source") or "fred_alfred" + row_provenance = ( + provenance_label + or document.get("provenance_label") + or f"{row_source}_api" + ) + if not all( + isinstance(value, str) and value.strip() + for value in ( + row_series_id, + row_units, + row_frequency, + row_adjustment, + ) + ): + raise AdapterResponseError( + f"observation {index} lacks series, units, frequency, or adjustment metadata" + ) + + observation_date = _iso_date( + row.get("observation_date", row.get("date")), + "observation_date", + ) + realtime_start_value = row.get("realtime_start", document.get("realtime_start")) + realtime_start = _iso_date(realtime_start_value, "realtime_start") + realtime_end = _optional_iso_date( + row.get("realtime_end", document.get("realtime_end")), + "realtime_end", + ) + explicit_availability = row.get("availability_date", row.get("release_date")) + if explicit_availability is None: + explicit_availability = _release_lookup(release_dates, observation_date) + availability_basis = "explicit_release_or_availability_date" + if explicit_availability is None: + explicit_availability = realtime_start + availability_basis = "alfred_realtime_start" + availability_date = _iso_date(explicit_availability, "availability_date") + + release_timestamp = row.get("release_timestamp") + availability_timestamp = row.get("availability_timestamp") + if isinstance(explicit_availability, datetime) and availability_timestamp is None: + availability_timestamp = explicit_availability + + source_metadata = { + "adapter": "fred_alfred_json", + "availability_basis": availability_basis, + "raw_observation": dict(row), + "response_metadata": response_metadata, + "series_metadata": dict(metadata), + } + try: + parsed.append( + VintageObservation( + series_id=cast(str, row_series_id), + observation_date=observation_date, + realtime_start=realtime_start, + realtime_end=realtime_end, + availability_date=availability_date, + release_timestamp=release_timestamp, # type: ignore[arg-type] + availability_timestamp=availability_timestamp, # type: ignore[arg-type] + value=row.get("value"), # type: ignore[arg-type] + units=cast(str, row_units), + frequency=_frequency(row_frequency), + seasonal_adjustment=cast(str, row_adjustment), + transformation=( + cast(str, row_transformation) + if isinstance(row_transformation, str) and row_transformation.strip() + else "level" + ), + download_timestamp=downloaded_at, + source=cast(str, row_source), + provenance_label=cast(str, row_provenance), + source_metadata=source_metadata, + ) + ) + except SchemaValidationError as exc: + raise AdapterResponseError(f"observation {index} is invalid: {exc}") from exc + return sorted( + parsed, + key=lambda row: (row.series_id, row.observation_date, row.realtime_start), + ) + + +parse_alfred_observations = parse_fred_observations + + +def _urllib_transport(url: str, timeout_seconds: float) -> bytes: + request = Request(url, headers={"User-Agent": "macro-nowcast/0.1"}) + with urlopen(request, timeout=timeout_seconds) as response: + return response.read() + + +def _retryable_exception(exc: BaseException) -> bool: + if isinstance(exc, HTTPError): + return exc.code in {408, 425, 429, 500, 502, 503, 504} + return isinstance(exc, (RetryableAdapterError, TimeoutError, URLError)) + + +class FredAlfredAdapter: + """A fail-closed live FRED/ALFRED client with injectable I/O. + + The default configuration performs no persistent caching. Unit tests can inject + a transport and clock; none of this project's tests use the network. + """ + + def __init__( + self, + config: FredAPIConfig | None = None, + *, + environ: Mapping[str, str] | None = None, + transport: Transport | None = None, + sleep: Sleep = time.sleep, + clock: Clock = time.monotonic, + now: Now = _utc_now, + ) -> None: + self.config = config or FredAPIConfig() + self._environ = environ if environ is not None else os.environ + self._transport = transport or _urllib_transport + self._sleep = sleep + self._clock = clock + self._now = now + self._last_request_at: float | None = None + self._throttle_lock = threading.Lock() + + def _api_key(self) -> str: + if not self.config.terms_authorized: + raise AdapterAuthorizationError( + "live FRED/ALFRED access is disabled; set terms_authorized=True only " + "after confirming authorization under the applicable source terms" + ) + api_key = self._environ.get(self.config.api_key_env, "").strip() + if not api_key: + raise AdapterCredentialError( + f"live FRED/ALFRED access requires {self.config.api_key_env}" + ) + return api_key + + def _throttle(self) -> None: + with self._throttle_lock: + now = self._clock() + if self._last_request_at is not None: + remaining = self.config.min_interval_seconds - (now - self._last_request_at) + if remaining > 0: + self._sleep(remaining) + now = self._clock() + self._last_request_at = now + + def _cache_path(self, endpoint: str, parameters: Mapping[str, object]) -> Path | None: + if self.config.cache_dir is None: + return None + cache_key = json.dumps( + {"endpoint": endpoint, "parameters": parameters}, + separators=(",", ":"), + sort_keys=True, + ).encode("utf-8") + digest = hashlib.sha256(cache_key).hexdigest() + return self.config.cache_dir / endpoint.replace("/", "_") / f"{digest}.json" + + def _request_json( + self, + endpoint: str, + parameters: Mapping[str, object], + ) -> Mapping[str, Any]: + api_key = self._api_key() + query = { + key: value.isoformat() if isinstance(value, date) else value + for key, value in parameters.items() + if value is not None + } + cache_path = self._cache_path(endpoint, query) + if cache_path is not None and cache_path.exists(): + return _payload_mapping(cache_path.read_bytes()) + + query.update({"api_key": api_key, "file_type": "json"}) + url = f"{self.config.base_url}/{endpoint}?{urlencode(query, doseq=True)}" + backoff = self.config.initial_backoff_seconds + response: bytes | str | None = None + for attempt in range(1, self.config.max_attempts + 1): + self._throttle() + try: + response = self._transport(url, self.config.timeout_seconds) + break + except Exception as exc: + if attempt == self.config.max_attempts or not _retryable_exception(exc): + raise AdapterRequestError( + f"FRED/ALFRED request failed for endpoint {endpoint}" + ) from exc + if backoff: + self._sleep(backoff) + backoff *= self.config.backoff_multiplier + if response is None: # pragma: no cover - loop either succeeds or raises + raise AdapterRequestError(f"FRED/ALFRED request failed for endpoint {endpoint}") + + document = _payload_mapping(response) + source_error = document.get("error_message", document.get("message")) + if document.get("error_code") is not None: + raise AdapterResponseError(f"FRED/ALFRED returned an error: {source_error}") + if cache_path is not None: + cache_path.parent.mkdir(parents=True, exist_ok=True) + try: + with cache_path.open("x", encoding="utf-8", errors="strict") as file_handle: + json.dump(document, file_handle, separators=(",", ":"), sort_keys=True) + except FileExistsError: + pass + return document + + def fetch( + self, + series: SeriesConfig, + *, + observation_start: date | None = None, + observation_end: date | None = None, + realtime_start: date | None = None, + realtime_end: date | None = None, + vintage_dates: Iterable[date] | None = None, + output_type: int = 1, + ) -> list[VintageObservation]: + """Fetch a normalized interval history with bounded pagination. + + The canonical parser supports the row-oriented output types 1 (real-time + intervals) and 4 (initial releases). FRED output types 2 and 3 are + vintage-by-observation cross-tabs and require a different parser, so this + adapter rejects them rather than silently normalizing them incorrectly. + """ + + if output_type not in {1, 4}: + raise AdapterRequestError( + "normalized ingestion supports FRED output_type 1 or 4 only" + ) + if vintage_dates is not None: + raise AdapterRequestError( + "vintage_dates cross-tab ingestion is not supported by the normalized adapter; " + "use realtime_start/realtime_end intervals instead" + ) + + parameters: dict[str, object] = { + "series_id": series.series_id, + "observation_start": observation_start, + "observation_end": observation_end, + "realtime_start": realtime_start or date(1776, 7, 4), + "realtime_end": realtime_end or date(9999, 12, 31), + "output_type": output_type, + "units": "lin", + "sort_order": "asc", + "limit": 100_000, + } + rows: list[VintageObservation] = [] + offset = 0 + while True: + page_parameters = {**parameters, "offset": offset} + document = self._request_json("series/observations", page_parameters) + page_rows = parse_fred_observations( + document, + series=series, + source="fred_alfred", + provenance_label="fred_alfred_api", + download_timestamp=self._now(), + ) + rows.extend(page_rows) + raw_observations = document.get("observations") + page_size = len(raw_observations) if isinstance(raw_observations, list) else 0 + try: + total_count = int(document.get("count", page_size)) + except (TypeError, ValueError) as exc: + raise AdapterResponseError("response count must be an integer") from exc + offset += page_size + if page_size == 0 or offset >= total_count: + break + safe_parameters = { + key: value.isoformat() if isinstance(value, date) else value + for key, value in parameters.items() + if value is not None + } + return [ + replace( + row, + source_metadata={ + **row.source_metadata, + "request_endpoint": "series/observations", + "request_parameters": safe_parameters, + }, + ) + for row in rows + ] + + fetch_observations = fetch + + +class FixtureAdapter: + """Read canonical or FRED-shaped JSON fixtures without network access.""" + + def __init__( + self, + fixture: str + | Path + | pl.DataFrame + | Iterable[VintageObservation | Mapping[str, object]], + *, + series: Iterable[SeriesConfig] = (), + ) -> None: + self._fixture = fixture + self._series = {item.series_id: item for item in series} + + @staticmethod + def _canonical_mapping(row: Mapping[str, object]) -> bool: + required = { + "series_id", + "observation_date", + "realtime_start", + "availability_date", + "units", + "frequency", + "seasonal_adjustment", + "transformation", + } + return required.issubset(row) + + def _label_fixture_row( + self, + row: VintageObservation, + fixture_name: str, + ) -> VintageObservation: + return replace( + row, + provenance_label="synthetic_fixture", + source_metadata={ + **row.source_metadata, + "fixture_name": fixture_name, + "adapter": "fixture", + }, + ) + + def _document_rows( + self, + document: object, + fixture_name: str, + requested_series: SeriesConfig | None, + ) -> list[VintageObservation]: + if isinstance(document, list): + rows: list[VintageObservation] = [] + for index, value in enumerate(document): + if isinstance(value, VintageObservation): + rows.append(self._label_fixture_row(value, fixture_name)) + continue + if not isinstance(value, Mapping) or not self._canonical_mapping(value): + raise AdapterResponseError( + f"fixture row {index} is not a canonical observation" + ) + canonical = {**value, "provenance_label": "synthetic_fixture"} + canonical.setdefault("source", "fixture") + try: + rows.append( + self._label_fixture_row( + VintageObservation.from_mapping(canonical), + fixture_name, + ) + ) + except SchemaValidationError as exc: + raise AdapterResponseError(f"fixture row {index} is invalid: {exc}") from exc + return rows + + if not isinstance(document, Mapping): + raise AdapterResponseError("fixture must be a JSON object or canonical row array") + if "datasets" in document: + datasets = document["datasets"] + if not isinstance(datasets, list): + raise AdapterResponseError("fixture datasets must be an array") + return [ + row + for dataset in datasets + for row in self._document_rows(dataset, fixture_name, requested_series) + ] + + observations = document.get("observations") + if isinstance(observations, list) and all( + isinstance(item, Mapping) and self._canonical_mapping(item) + for item in observations + ): + defaults = { + key: document[key] + for key in ( + "source", + "download_timestamp", + "downloaded_at", + "release_timestamp", + "availability_timestamp", + ) + if key in document + } + canonical_rows = [ + {**defaults, **cast(Mapping[str, object], item)} for item in observations + ] + return self._document_rows(canonical_rows, fixture_name, requested_series) + + selected_series = requested_series + if selected_series is None: + metadata = _series_metadata(cast(Mapping[str, Any], document)) + fixture_series_id = metadata.get("series_id", metadata.get("id")) + if isinstance(fixture_series_id, str): + selected_series = self._series.get(fixture_series_id) + rows = parse_fred_observations( + cast(Mapping[str, Any], document), + series=selected_series, + provenance_label="synthetic_fixture", + source=cast(str | None, document.get("source")) or "fixture", + ) + return [self._label_fixture_row(row, fixture_name) for row in rows] + + def _load(self, requested_series: SeriesConfig | None) -> list[VintageObservation]: + if isinstance(self._fixture, pl.DataFrame): + return self._document_rows( + self._fixture.to_dicts(), + "in_memory_frame", + requested_series, + ) + if isinstance(self._fixture, (str, Path)): + path = Path(self._fixture) + if path.suffix.lower() not in {".json", ".jsonl", ".ndjson"}: + raise AdapterResponseError("fixture files must be JSON or JSON Lines") + try: + text = path.read_text(encoding="utf-8") + except OSError as exc: + raise AdapterResponseError(f"cannot read fixture: {path.name}") from exc + try: + if path.suffix.lower() in {".jsonl", ".ndjson"}: + document: object = [ + json.loads(line) for line in text.splitlines() if line.strip() + ] + else: + document = json.loads(text) + except json.JSONDecodeError as exc: + raise AdapterResponseError(f"fixture is not valid JSON: {path.name}") from exc + return self._document_rows(document, path.name, requested_series) + return self._document_rows(list(self._fixture), "in_memory", requested_series) + + def fetch( + self, + series: SeriesConfig | str | None = None, + *, + observation_start: date | None = None, + observation_end: date | None = None, + ) -> list[VintageObservation]: + requested_series = series if isinstance(series, SeriesConfig) else None + series_id = series.series_id if isinstance(series, SeriesConfig) else series + rows = self._load(requested_series) + return [ + row + for row in rows + if (series_id is None or row.series_id == series_id) + and (observation_start is None or row.observation_date >= observation_start) + and (observation_end is None or row.observation_date <= observation_end) + ] + + fetch_observations = fetch + + +LiveFredAdapter = FredAlfredAdapter +AlfredAdapter = FredAlfredAdapter diff --git a/Macroeconomics/src/macro_nowcast/agency_adapters.py b/Macroeconomics/src/macro_nowcast/agency_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..e2572d07fad19d7e0f869162903265f3df621a47 --- /dev/null +++ b/Macroeconomics/src/macro_nowcast/agency_adapters.py @@ -0,0 +1,1052 @@ +"""Guarded original-provider adapters for current BLS and BEA data. + +The public APIs represented here return current, revised observations. They do +not expose a historical-vintage dimension, so every parsed API row is labeled +``latest_revised`` and becomes available at its retrieval timestamp. Separate +archive contracts deliberately require an explicit, audited opt-in before a +caller can claim historical release provenance. +""" + +from __future__ import annotations + +import json +import os +import re +import threading +import time +from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass, field +from datetime import UTC, date, datetime +from email.utils import parsedate_to_datetime +from enum import StrEnum +from typing import Any, Literal, Protocol, cast +from urllib.error import HTTPError, URLError +from urllib.parse import quote_plus, urlencode +from urllib.request import Request, urlopen + +from macro_nowcast.schema import VintageObservation + +LATEST_REVISED = "latest_revised" + +BLS_REGISTRATION_KEY_ENV = "BLS_REGISTRATION_KEY" +BEA_API_KEY_ENV = "BEA_API_KEY" + +BLS_API_ENDPOINT = "https://api.bls.gov/publicAPI/v2/timeseries/data/" +BEA_API_ENDPOINT = "https://apps.bea.gov/api/data" + + +class AgencyAdapterError(RuntimeError): + """Base error for original-provider access or parsing.""" + + +class AgencyAuthorizationError(AgencyAdapterError): + """Raised when source terms or archive ingestion were not authorized.""" + + +class AgencyCredentialError(AgencyAdapterError): + """Raised when an agency-specific environment credential is missing.""" + + +class AgencyRequestError(AgencyAdapterError): + """Raised when an agency request cannot be completed safely.""" + + +class AgencyResponseError(AgencyAdapterError): + """Raised when an agency response cannot be parsed without guessing.""" + + +class AgencyProvenanceError(AgencyAdapterError): + """Raised when current API data are assigned historical provenance.""" + + +def _nonempty_text(value: object, name: str) -> str: + if not isinstance(value, str) or not value.strip(): + raise ValueError(f"{name} must be a non-empty string") + return value.strip() + + +def _positive_float(value: object, name: str) -> float: + if isinstance(value, bool): + raise ValueError(f"{name} must be greater than zero") + try: + parsed = float(value) # type: ignore[arg-type] + except (TypeError, ValueError) as exc: + raise ValueError(f"{name} must be greater than zero") from exc + if parsed <= 0: + raise ValueError(f"{name} must be greater than zero") + return parsed + + +def _nonnegative_float(value: object, name: str) -> float: + if isinstance(value, bool): + raise ValueError(f"{name} must be non-negative") + try: + parsed = float(value) # type: ignore[arg-type] + except (TypeError, ValueError) as exc: + raise ValueError(f"{name} must be non-negative") from exc + if parsed < 0: + raise ValueError(f"{name} must be non-negative") + return parsed + + +def _positive_int(value: object, name: str) -> int: + if isinstance(value, bool): + raise ValueError(f"{name} must be a positive integer") + try: + parsed = int(value) # type: ignore[arg-type] + except (TypeError, ValueError) as exc: + raise ValueError(f"{name} must be a positive integer") from exc + if parsed < 1: + raise ValueError(f"{name} must be a positive integer") + return parsed + + +def _aware_utc(value: datetime, name: str) -> datetime: + if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None: + raise AgencyResponseError(f"{name} must include a timezone") + return value.astimezone(UTC) + + +def _json_mapping(payload: Mapping[str, Any] | bytes | str) -> Mapping[str, Any]: + if isinstance(payload, Mapping): + return payload + try: + text = payload.decode("utf-8") if isinstance(payload, bytes) else payload + decoded = json.loads(text) + except (UnicodeDecodeError, json.JSONDecodeError, TypeError) as exc: + raise AgencyResponseError("agency response is not valid UTF-8 JSON") from exc + if not isinstance(decoded, Mapping): + raise AgencyResponseError("agency response must be a JSON object") + return cast(Mapping[str, Any], decoded) + + +def _numeric_value(value: object) -> float | None: + if value is None: + return None + if isinstance(value, bool): + raise AgencyResponseError("observation value must be numeric or null") + text = str(value).strip() + if text in {"", ".", "-", "--", "NA", "N/A", "(NA)"}: + return None + try: + return float(text.replace(",", "")) + except ValueError as exc: + raise AgencyResponseError("observation value must be numeric or null") from exc + + +def require_latest_revised(provenance_label: str) -> None: + """Reject a historical-release claim for current-data API output.""" + + if provenance_label != LATEST_REVISED: + raise AgencyProvenanceError( + "current BLS/BEA API rows must be labeled 'latest_revised'; " + "first-release provenance requires an audited archive" + ) + + +@dataclass(frozen=True, slots=True) +class HTTPRequest: + """Transport-neutral HTTP request with a credential-redacted representation.""" + + method: Literal["GET", "POST"] + url: str + headers: Mapping[str, str] = field(default_factory=dict) + body: bytes | None = None + _secrets: tuple[str, ...] = field(default=(), repr=False, compare=False) + + def __post_init__(self) -> None: + if self.method not in {"GET", "POST"}: + raise ValueError("method must be GET or POST") + if not self.url.startswith("https://"): + raise ValueError("agency requests must use HTTPS") + object.__setattr__(self, "headers", dict(self.headers)) + + @property + def redacted_url(self) -> str: + result = self.url + for secret in self._secrets: + result = result.replace(secret, "[REDACTED]") + result = result.replace(quote_plus(secret), "%5BREDACTED%5D") + return result + + def __repr__(self) -> str: + return ( + "HTTPRequest(" + f"method={self.method!r}, url={self.redacted_url!r}, " + f"headers={dict(self.headers)!r}, body_bytes={len(self.body or b'')}" + ")" + ) + + +@dataclass(frozen=True, slots=True) +class HTTPResponse: + """Small response value used by injected and standard-library transports.""" + + status_code: int + body: bytes | str + headers: Mapping[str, str] = field(default_factory=dict) + + def __post_init__(self) -> None: + object.__setattr__(self, "headers", dict(self.headers)) + + def __repr__(self) -> str: + return ( + "HTTPResponse(" + f"status_code={self.status_code!r}, body_bytes={len(self.body)}, " + f"header_names={tuple(self.headers)!r}" + ")" + ) + + +class HTTPTransport(Protocol): + def __call__(self, request: HTTPRequest, timeout_seconds: float) -> HTTPResponse: ... + + +type Sleep = Callable[[float], None] +type Clock = Callable[[], float] +type Now = Callable[[], datetime] + + +def urllib_transport(request: HTTPRequest, timeout_seconds: float) -> HTTPResponse: + """Execute an agency request; primarily a live-use default, never needed in tests.""" + + native_request = Request( + request.url, + data=request.body, + headers=dict(request.headers), + method=request.method, + ) + try: + with urlopen(native_request, timeout=timeout_seconds) as response: + return HTTPResponse( + status_code=response.status, + body=response.read(), + headers=dict(response.headers.items()), + ) + except HTTPError as exc: + return HTTPResponse( + status_code=exc.code, + body=exc.read(), + headers=dict(exc.headers.items()) if exc.headers is not None else {}, + ) + except URLError: + raise AgencyRequestError("agency transport failed") from None + + +@dataclass(frozen=True, slots=True) +class AgencyRequestPolicy: + """Configurable throttle and bounded retry behavior.""" + + timeout_seconds: float = 30.0 + min_interval_seconds: float = 0.2 + max_attempts: int = 3 + initial_backoff_seconds: float = 0.5 + backoff_multiplier: float = 2.0 + max_retry_after_seconds: float = 300.0 + + def __post_init__(self) -> None: + object.__setattr__( + self, + "timeout_seconds", + _positive_float(self.timeout_seconds, "timeout_seconds"), + ) + object.__setattr__( + self, + "min_interval_seconds", + _nonnegative_float(self.min_interval_seconds, "min_interval_seconds"), + ) + object.__setattr__(self, "max_attempts", _positive_int(self.max_attempts, "max_attempts")) + object.__setattr__( + self, + "initial_backoff_seconds", + _nonnegative_float(self.initial_backoff_seconds, "initial_backoff_seconds"), + ) + multiplier = _positive_float(self.backoff_multiplier, "backoff_multiplier") + if multiplier < 1: + raise ValueError("backoff_multiplier must be at least one") + object.__setattr__(self, "backoff_multiplier", multiplier) + object.__setattr__( + self, + "max_retry_after_seconds", + _positive_float(self.max_retry_after_seconds, "max_retry_after_seconds"), + ) + + +@dataclass(frozen=True, slots=True) +class BLSLatestConfig: + """BLS current-data access policy; authorization is disabled by default.""" + + terms_authorized: bool = False + endpoint: str = BLS_API_ENDPOINT + request_policy: AgencyRequestPolicy = field(default_factory=AgencyRequestPolicy) + + def __post_init__(self) -> None: + if not isinstance(self.terms_authorized, bool): + raise ValueError("terms_authorized must be a boolean") + if not self.endpoint.startswith("https://"): + raise ValueError("BLS endpoint must use HTTPS") + + +@dataclass(frozen=True, slots=True) +class BEALatestConfig: + """BEA current-data access policy; authorization is disabled by default.""" + + terms_authorized: bool = False + endpoint: str = BEA_API_ENDPOINT + request_policy: AgencyRequestPolicy = field( + default_factory=lambda: AgencyRequestPolicy(min_interval_seconds=0.6) + ) + + def __post_init__(self) -> None: + if not isinstance(self.terms_authorized, bool): + raise ValueError("terms_authorized must be a boolean") + if not self.endpoint.startswith("https://"): + raise ValueError("BEA endpoint must use HTTPS") + + +@dataclass(frozen=True, slots=True) +class BLSSeriesSpec: + """Canonical metadata for one BLS source series.""" + + series_id: str + units: str + seasonal_adjustment: str + frequency: str = "monthly" + transformation: str = "level" + canonical_series_id: str | None = None + + def __post_init__(self) -> None: + object.__setattr__(self, "series_id", _nonempty_text(self.series_id, "series_id")) + object.__setattr__(self, "units", _nonempty_text(self.units, "units")) + object.__setattr__( + self, + "seasonal_adjustment", + _nonempty_text(self.seasonal_adjustment, "seasonal_adjustment"), + ) + object.__setattr__(self, "frequency", _nonempty_text(self.frequency, "frequency")) + object.__setattr__( + self, + "transformation", + _nonempty_text(self.transformation, "transformation"), + ) + if self.canonical_series_id is not None: + object.__setattr__( + self, + "canonical_series_id", + _nonempty_text(self.canonical_series_id, "canonical_series_id"), + ) + + @property + def output_series_id(self) -> str: + return self.canonical_series_id or self.series_id + + +@dataclass(frozen=True, slots=True) +class BEASeriesSpec: + """Canonical metadata for one row of one BEA NIPA table.""" + + table_name: str + line_number: str + series_id: str + units: str + seasonal_adjustment: str + frequency: str = "quarterly" + transformation: str = "level" + + def __post_init__(self) -> None: + object.__setattr__(self, "table_name", _nonempty_text(self.table_name, "table_name")) + object.__setattr__( + self, + "line_number", + _nonempty_text(str(self.line_number), "line_number"), + ) + object.__setattr__(self, "series_id", _nonempty_text(self.series_id, "series_id")) + object.__setattr__(self, "units", _nonempty_text(self.units, "units")) + object.__setattr__( + self, + "seasonal_adjustment", + _nonempty_text(self.seasonal_adjustment, "seasonal_adjustment"), + ) + object.__setattr__(self, "frequency", _nonempty_text(self.frequency, "frequency")) + object.__setattr__( + self, + "transformation", + _nonempty_text(self.transformation, "transformation"), + ) + + +BLS_TOTAL_NONFARM_PAYROLL = BLSSeriesSpec( + series_id="CES0000000001", + units="thousands_of_persons", + seasonal_adjustment="seasonally_adjusted", +) +BLS_CORE_CPI = BLSSeriesSpec( + series_id="CUSR0000SA0L1E", + units="index_1982_1984_100", + seasonal_adjustment="seasonally_adjusted", +) +BLS_HEADLINE_CPI = BLSSeriesSpec( + series_id="CUSR0000SA0", + units="index_1982_1984_100", + seasonal_adjustment="seasonally_adjusted", +) +BEA_REAL_GDP_LEVEL = BEASeriesSpec( + table_name="T10106", + line_number="1", + series_id="GDPC1", + units="billions_of_chained_dollars", + seasonal_adjustment="seasonally_adjusted_annual_rate", + transformation="level", +) +BEA_REAL_GDP_GROWTH = BEASeriesSpec( + table_name="T10101", + line_number="1", + series_id="BEA_REAL_GDP_GROWTH_QOQ_SAAR", + units="percent_change_qoq_saar", + seasonal_adjustment="seasonally_adjusted_annual_rate", + transformation="percent_change_qoq_saar", +) + + +def build_bls_latest_request( + series_ids: Iterable[str], + *, + start_year: int, + end_year: int, + registration_key: str, + endpoint: str = BLS_API_ENDPOINT, +) -> HTTPRequest: + """Build a registered BLS v2 current-data request without performing I/O.""" + + ids = tuple(_nonempty_text(value, "series_id") for value in series_ids) + if not ids or len(ids) > 50: + raise ValueError("a BLS request must contain between 1 and 50 series IDs") + if len(set(ids)) != len(ids): + raise ValueError("BLS series IDs must be unique within a request") + if isinstance(start_year, bool) or isinstance(end_year, bool): + raise ValueError("BLS years must be four-digit integers") + if not (1000 <= start_year <= end_year <= 9999): + raise ValueError("BLS years must be an ordered four-digit range") + if end_year - start_year + 1 > 20: + raise ValueError("registered BLS API requests may span at most 20 years") + key = _nonempty_text(registration_key, "registration_key") + body = json.dumps( + { + "seriesid": list(ids), + "startyear": str(start_year), + "endyear": str(end_year), + "registrationkey": key, + }, + separators=(",", ":"), + sort_keys=True, + ).encode("utf-8") + return HTTPRequest( + method="POST", + url=endpoint, + headers={"Accept": "application/json", "Content-Type": "application/json"}, + body=body, + _secrets=(key,), + ) + + +def _bea_years(years: Iterable[int] | str) -> str: + if isinstance(years, str): + candidate = years.strip() + if candidate.upper() == "X": + return "X" + if not candidate: + raise ValueError("BEA years cannot be empty") + values = candidate.split(",") + if any(not value.strip().isdigit() for value in values): + raise ValueError("BEA years must be four-digit years or 'X'") + parsed = tuple(int(value) for value in values) + else: + parsed = tuple(years) + if not parsed or any(isinstance(value, bool) or not 1000 <= value <= 9999 for value in parsed): + raise ValueError("BEA years must be four-digit years or 'X'") + return ",".join(str(value) for value in parsed) + + +def build_bea_latest_request( + *, + api_key: str, + table_name: str, + years: Iterable[int] | str, + frequency: str = "Q", + endpoint: str = BEA_API_ENDPOINT, +) -> HTTPRequest: + """Build a BEA NIPA current-data request without performing I/O.""" + + key = _nonempty_text(api_key, "api_key") + parameters = { + "UserID": key, + "method": "GetData", + "datasetname": "NIPA", + "TableName": _nonempty_text(table_name, "table_name"), + "Frequency": _nonempty_text(frequency, "frequency").upper(), + "Year": _bea_years(years), + "ResultFormat": "JSON", + } + return HTTPRequest( + method="GET", + url=f"{endpoint}?{urlencode(parameters)}", + headers={"Accept": "application/json"}, + _secrets=(key,), + ) + + +def _normalize_bls_specs( + specs: BLSSeriesSpec | Iterable[BLSSeriesSpec], +) -> tuple[BLSSeriesSpec, ...]: + normalized = (specs,) if isinstance(specs, BLSSeriesSpec) else tuple(specs) + if not normalized: + raise ValueError("at least one BLS series specification is required") + if any(not isinstance(spec, BLSSeriesSpec) for spec in normalized): + raise TypeError("BLS specifications must be BLSSeriesSpec values") + if len({spec.series_id for spec in normalized}) != len(normalized): + raise ValueError("BLS source series IDs must be unique") + return normalized + + +def parse_bls_latest_response( + payload: Mapping[str, Any] | bytes | str, + specs: BLSSeriesSpec | Iterable[BLSSeriesSpec], + *, + retrieved_at: datetime, + provenance_label: str = LATEST_REVISED, +) -> list[VintageObservation]: + """Parse BLS v2 data while refusing to imply historical availability.""" + + require_latest_revised(provenance_label) + retrieved = _aware_utc(retrieved_at, "retrieved_at") + document = _json_mapping(payload) + if document.get("status") != "REQUEST_SUCCEEDED": + raise AgencyResponseError("BLS response did not report REQUEST_SUCCEEDED") + results = document.get("Results") + if not isinstance(results, Mapping) or not isinstance(results.get("series"), list): + raise AgencyResponseError("BLS response must contain Results.series") + + spec_by_id = {spec.series_id: spec for spec in _normalize_bls_specs(specs)} + parsed: list[VintageObservation] = [] + seen_series: set[str] = set() + for raw_series in cast(list[object], results["series"]): + if not isinstance(raw_series, Mapping): + raise AgencyResponseError("each BLS series result must be an object") + source_id = raw_series.get("seriesID") + if not isinstance(source_id, str) or source_id not in spec_by_id: + raise AgencyResponseError("BLS response contains an unrequested series") + spec = spec_by_id[source_id] + seen_series.add(source_id) + data = raw_series.get("data") + if not isinstance(data, list): + raise AgencyResponseError("each BLS series result must contain a data array") + for raw_row in data: + if not isinstance(raw_row, Mapping): + raise AgencyResponseError("each BLS observation must be an object") + period = raw_row.get("period") + year = raw_row.get("year") + if not isinstance(period, str) or not isinstance(year, str): + raise AgencyResponseError("BLS observations require year and period") + if period == "M13": + continue + match = re.fullmatch(r"M(0[1-9]|1[0-2])", period) + if match is None or not year.isdigit() or len(year) != 4: + raise AgencyResponseError("BLS monthly observations require YYYY and M01-M12") + observation_date = date(int(year), int(match.group(1)), 1) + metadata: dict[str, Any] = { + "api_mode": LATEST_REVISED, + "availability_basis": "retrieval_timestamp_not_historical_release", + "source_series_id": source_id, + "period": period, + } + for name in ("periodName", "latest", "footnotes", "aspects"): + if name in raw_row: + metadata[name] = raw_row[name] + parsed.append( + VintageObservation( + series_id=spec.output_series_id, + observation_date=observation_date, + realtime_start=retrieved.date(), + realtime_end=None, + availability_date=retrieved.date(), + release_timestamp=None, + availability_timestamp=retrieved, + value=_numeric_value(raw_row.get("value")), + units=spec.units, + frequency=spec.frequency, + seasonal_adjustment=spec.seasonal_adjustment, + transformation=spec.transformation, + download_timestamp=retrieved, + source="bls_public_data_api_v2", + provenance_label=LATEST_REVISED, + source_metadata=metadata, + ) + ) + missing = set(spec_by_id).difference(seen_series) + if missing: + raise AgencyResponseError("BLS response omitted one or more requested series") + return sorted(parsed, key=lambda row: (row.series_id, row.observation_date)) + + +_QUARTER_PATTERN = re.compile(r"^(?P\d{4})Q(?P[1-4])$") + + +def parse_bea_latest_response( + payload: Mapping[str, Any] | bytes | str, + spec: BEASeriesSpec, + *, + retrieved_at: datetime, + provenance_label: str = LATEST_REVISED, +) -> list[VintageObservation]: + """Parse a current BEA NIPA table row with conservative availability.""" + + require_latest_revised(provenance_label) + retrieved = _aware_utc(retrieved_at, "retrieved_at") + document = _json_mapping(payload) + api = document.get("BEAAPI") + if not isinstance(api, Mapping): + raise AgencyResponseError("BEA response must contain BEAAPI") + results = api.get("Results") + if not isinstance(results, Mapping) or "Error" in results: + raise AgencyResponseError("BEA response did not contain a successful result") + data = results.get("Data") + if not isinstance(data, list): + raise AgencyResponseError("BEA response must contain Results.Data") + + parsed: list[VintageObservation] = [] + for raw_row in data: + if not isinstance(raw_row, Mapping): + raise AgencyResponseError("each BEA observation must be an object") + if str(raw_row.get("TableName", spec.table_name)) != spec.table_name: + continue + if str(raw_row.get("LineNumber", "")) != spec.line_number: + continue + time_period = raw_row.get("TimePeriod") + if not isinstance(time_period, str): + raise AgencyResponseError("BEA observations require TimePeriod") + match = _QUARTER_PATTERN.fullmatch(time_period) + if match is None: + raise AgencyResponseError("quarterly BEA TimePeriod must use YYYYQ1-YYYYQ4") + quarter = int(match.group("quarter")) + observation_date = date(int(match.group("year")), (quarter - 1) * 3 + 1, 1) + metadata: dict[str, Any] = { + "api_mode": LATEST_REVISED, + "availability_basis": "retrieval_timestamp_not_historical_release", + "dataset": "NIPA", + "table_name": spec.table_name, + "line_number": spec.line_number, + } + for name in ( + "SeriesCode", + "LineDescription", + "Metric_Name", + "CL_UNIT", + "UNIT_MULT", + ): + if name in raw_row: + metadata[name] = raw_row[name] + parsed.append( + VintageObservation( + series_id=spec.series_id, + observation_date=observation_date, + realtime_start=retrieved.date(), + realtime_end=None, + availability_date=retrieved.date(), + release_timestamp=None, + availability_timestamp=retrieved, + value=_numeric_value(raw_row.get("DataValue")), + units=spec.units, + frequency=spec.frequency, + seasonal_adjustment=spec.seasonal_adjustment, + transformation=spec.transformation, + download_timestamp=retrieved, + source="bea_data_api_nipa", + provenance_label=LATEST_REVISED, + source_metadata=metadata, + ) + ) + if not parsed: + raise AgencyResponseError("BEA response omitted the requested table line") + return sorted(parsed, key=lambda row: row.observation_date) + + +_RETRYABLE_STATUS_CODES = frozenset({408, 425, 429, 500, 502, 503, 504}) + + +class _LatestAdapter: + def __init__( + self, + *, + provider: str, + credential_env: str, + terms_authorized: bool, + endpoint: str, + policy: AgencyRequestPolicy, + transport: HTTPTransport | None, + environ: Mapping[str, str] | None, + sleep: Sleep, + clock: Clock, + now: Now, + ) -> None: + self._provider = provider + self._credential_env = credential_env + self._terms_authorized = terms_authorized + self._endpoint = endpoint + self._policy = policy + self._transport = transport or urllib_transport + self._environ = os.environ if environ is None else environ + self._sleep = sleep + self._clock = clock + self._now = now + self._last_request_started: float | None = None + self._throttle_lock = threading.Lock() + + def __repr__(self) -> str: + return ( + f"{type(self).__name__}(provider={self._provider!r}, " + f"terms_authorized={self._terms_authorized!r}, endpoint={self._endpoint!r}, " + f"credential_env={self._credential_env!r})" + ) + + def _credential(self) -> str: + if not self._terms_authorized: + raise AgencyAuthorizationError( + f"{self._provider} access is disabled until terms_authorized=True" + ) + value = self._environ.get(self._credential_env) + if not isinstance(value, str) or not value.strip(): + raise AgencyCredentialError( + f"{self._provider} access requires environment variable {self._credential_env}" + ) + return value.strip() + + def _throttle(self) -> None: + with self._throttle_lock: + current = self._clock() + if self._last_request_started is not None: + remaining = self._policy.min_interval_seconds - ( + current - self._last_request_started + ) + if remaining > 0: + self._sleep(remaining) + self._last_request_started = self._clock() + + def _retry_after(self, response: HTTPResponse) -> float | None: + raw_value = next( + (value for name, value in response.headers.items() if name.lower() == "retry-after"), + None, + ) + if raw_value is None: + return None + try: + seconds = float(raw_value) + except ValueError: + try: + retry_at = parsedate_to_datetime(raw_value) + if retry_at.tzinfo is None: + retry_at = retry_at.replace(tzinfo=UTC) + seconds = ( + retry_at.astimezone(UTC) - _aware_utc(self._now(), "now") + ).total_seconds() + except (TypeError, ValueError, OverflowError): + return None + if seconds < 0: + return None + return min(seconds, self._policy.max_retry_after_seconds) + + def _send(self, request: HTTPRequest) -> HTTPResponse: + backoff = self._policy.initial_backoff_seconds + for attempt in range(1, self._policy.max_attempts + 1): + self._throttle() + try: + response = self._transport(request, self._policy.timeout_seconds) + except Exception: + if attempt == self._policy.max_attempts: + raise AgencyRequestError( + f"{self._provider} request failed after {attempt} attempts" + ) from None + self._sleep(backoff) + backoff *= self._policy.backoff_multiplier + continue + if 200 <= response.status_code < 300: + return response + if response.status_code not in _RETRYABLE_STATUS_CODES: + raise AgencyRequestError( + f"{self._provider} request failed with HTTP {response.status_code}" + ) + if attempt == self._policy.max_attempts: + raise AgencyRequestError( + f"{self._provider} request failed after {attempt} attempts " + f"(HTTP {response.status_code})" + ) + retry_after = self._retry_after(response) + self._sleep(backoff if retry_after is None else retry_after) + backoff *= self._policy.backoff_multiplier + raise AssertionError("unreachable") + + +class BLSLatestAdapter(_LatestAdapter): + """Fail-closed adapter for the registered BLS current-data API.""" + + def __init__( + self, + config: BLSLatestConfig | None = None, + *, + transport: HTTPTransport | None = None, + environ: Mapping[str, str] | None = None, + sleep: Sleep = time.sleep, + clock: Clock = time.monotonic, + now: Now = lambda: datetime.now(UTC), + ) -> None: + self.config = config or BLSLatestConfig() + super().__init__( + provider="BLS", + credential_env=BLS_REGISTRATION_KEY_ENV, + terms_authorized=self.config.terms_authorized, + endpoint=self.config.endpoint, + policy=self.config.request_policy, + transport=transport, + environ=environ, + sleep=sleep, + clock=clock, + now=now, + ) + + def fetch( + self, + specs: BLSSeriesSpec | Iterable[BLSSeriesSpec], + *, + start_year: int, + end_year: int, + provenance_label: str = LATEST_REVISED, + ) -> list[VintageObservation]: + credential = self._credential() + require_latest_revised(provenance_label) + normalized = _normalize_bls_specs(specs) + request = build_bls_latest_request( + (spec.series_id for spec in normalized), + start_year=start_year, + end_year=end_year, + registration_key=credential, + endpoint=self.config.endpoint, + ) + response = self._send(request) + return parse_bls_latest_response( + response.body, + normalized, + retrieved_at=self._now(), + provenance_label=provenance_label, + ) + + +class BEALatestAdapter(_LatestAdapter): + """Fail-closed adapter for current BEA NIPA table data.""" + + def __init__( + self, + config: BEALatestConfig | None = None, + *, + transport: HTTPTransport | None = None, + environ: Mapping[str, str] | None = None, + sleep: Sleep = time.sleep, + clock: Clock = time.monotonic, + now: Now = lambda: datetime.now(UTC), + ) -> None: + self.config = config or BEALatestConfig() + super().__init__( + provider="BEA", + credential_env=BEA_API_KEY_ENV, + terms_authorized=self.config.terms_authorized, + endpoint=self.config.endpoint, + policy=self.config.request_policy, + transport=transport, + environ=environ, + sleep=sleep, + clock=clock, + now=now, + ) + + def fetch( + self, + spec: BEASeriesSpec, + *, + years: Iterable[int] | str, + provenance_label: str = LATEST_REVISED, + ) -> list[VintageObservation]: + credential = self._credential() + require_latest_revised(provenance_label) + request = build_bea_latest_request( + api_key=credential, + table_name=spec.table_name, + years=years, + frequency="Q", + endpoint=self.config.endpoint, + ) + response = self._send(request) + return parse_bea_latest_response( + response.body, + spec, + retrieved_at=self._now(), + provenance_label=provenance_label, + ) + + +class ArchiveKind(StrEnum): + BLS_CES_VINTAGE = "bls_ces_vintage" + BLS_CPI_SUPPLEMENTAL = "bls_cpi_supplemental" + BEA_GDP = "bea_gdp_archive" + UMICH_SENTIMENT_PUBLIC_REPORTS = "umich_sentiment_public_reports" + + +@dataclass(frozen=True, slots=True) +class ArchiveManifest: + """Discovery metadata only; a manifest does not authorize ingestion.""" + + kind: ArchiveKind + provider: str + official_index_url: str + formats: tuple[str, ...] + coverage_start: date | None + coverage_note: str + default_enabled: bool = False + coverage_audited: bool = False + + def __post_init__(self) -> None: + if not self.official_index_url.startswith("https://"): + raise ValueError("archive URL must use HTTPS") + if not self.formats: + raise ValueError("archive formats cannot be empty") + if self.default_enabled: + raise ValueError("agency archive ingestion cannot be enabled by default") + + +BLS_CES_VINTAGE_ARCHIVE = ArchiveManifest( + kind=ArchiveKind.BLS_CES_VINTAGE, + provider="BLS", + official_index_url="https://www.bls.gov/web/empsit/cesvindata.htm", + formats=("xlsx", "csv", "zip"), + coverage_start=date(2003, 6, 6), + coverage_note=( + "Published-value snapshots begin with the May 2003 estimate release; " + "older reference observations in a sheet are not older publication snapshots." + ), +) +BLS_CPI_SUPPLEMENTAL_ARCHIVE = ArchiveManifest( + kind=ArchiveKind.BLS_CPI_SUPPLEMENTAL, + provider="BLS", + official_index_url="https://www.bls.gov/cpi/tables/supplemental-files/home.htm", + formats=("xlsx", "zip"), + coverage_start=date(2012, 1, 1), + coverage_note=( + "The official annual ZIP listing starts in 2012; file layouts and missing months " + "must be audited, and later editions can revise seasonally adjusted history." + ), +) +BEA_GDP_ARCHIVE = ArchiveManifest( + kind=ArchiveKind.BEA_GDP, + provider="BEA", + official_index_url="https://apps.bea.gov/histdata/", + formats=("html", "xlsx", "zip"), + coverage_start=None, + coverage_note=( + "Coverage depends on the selected NIPA table and archive product; no complete " + "machine-readable vintage span is asserted until a release-by-release audit." + ), +) +UMICH_SENTIMENT_PUBLIC_REPORTS = ArchiveManifest( + kind=ArchiveKind.UMICH_SENTIMENT_PUBLIC_REPORTS, + provider="University of Michigan Surveys of Consumers", + official_index_url="https://data.sca.isr.umich.edu/", + formats=("html", "pdf"), + coverage_start=date(1991, 1, 1), + coverage_note=( + "Historical preliminary/final release dates are public, but the website usage " + "agreement restricts reproduction, retransmission, distribution, publication, " + "and broadcast without express written consent. Public visibility alone is not " + "treated as permission to build or distribute a historical release archive." + ), +) +ARCHIVE_MANIFESTS = ( + BLS_CES_VINTAGE_ARCHIVE, + BLS_CPI_SUPPLEMENTAL_ARCHIVE, + BEA_GDP_ARCHIVE, + UMICH_SENTIMENT_PUBLIC_REPORTS, +) + + +@dataclass(frozen=True, slots=True) +class ArchiveIngestionApproval: + """Three independent gates required before an archive parser may run.""" + + terms_authorized: bool = False + opt_in: bool = False + coverage_audited: bool = False + + +def require_archive_ingestion_approval(approval: ArchiveIngestionApproval) -> None: + """Fail closed unless terms, operator opt-in, and coverage audit are explicit.""" + + if not approval.terms_authorized: + raise AgencyAuthorizationError("archive source terms have not been authorized") + if not approval.opt_in: + raise AgencyAuthorizationError("archive ingestion requires explicit opt-in") + if not approval.coverage_audited: + raise AgencyAuthorizationError("archive ingestion requires a recorded coverage audit") + + +@dataclass(frozen=True, slots=True) +class UMichSentimentIngestionApproval: + """Source-specific gates for copyrighted Surveys of Consumers materials.""" + + terms_reviewed: bool = False + written_permission_reference: str | None = None + organization_scope_confirmed: bool = False + opt_in: bool = False + coverage_audited: bool = False + + +def require_umich_sentiment_ingestion_approval( + approval: UMichSentimentIngestionApproval, +) -> None: + """Require documented written consent in addition to ordinary archive gates.""" + + if not approval.terms_reviewed: + raise AgencyAuthorizationError("Michigan sentiment usage agreement is not reviewed") + if ( + not isinstance(approval.written_permission_reference, str) + or not approval.written_permission_reference.strip() + ): + raise AgencyAuthorizationError( + "Michigan sentiment ingestion requires an express written permission reference" + ) + if not approval.organization_scope_confirmed: + raise AgencyAuthorizationError( + "Michigan sentiment permission scope has not been matched to this organization" + ) + if not approval.opt_in: + raise AgencyAuthorizationError("Michigan sentiment ingestion requires explicit opt-in") + if not approval.coverage_audited: + raise AgencyAuthorizationError( + "Michigan sentiment ingestion requires a release-by-release coverage audit" + ) + + +class AgencyArchiveParser(Protocol): + """Contract for future audited CES, CPI, and GDP archive parsers.""" + + def parse( + self, + payload: bytes, + *, + manifest: ArchiveManifest, + approval: ArchiveIngestionApproval, + retrieved_at: datetime, + release_timestamp: datetime, + ) -> list[VintageObservation]: ... + + +# Concise aliases for callers that use parser/client terminology. +parse_bls_latest = parse_bls_latest_response +parse_bea_latest = parse_bea_latest_response +BLSLatestAPI = BLSLatestAdapter +BEALatestAPI = BEALatestAdapter diff --git a/Macroeconomics/src/macro_nowcast/archive_audit.py b/Macroeconomics/src/macro_nowcast/archive_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..5368673daf7f1da079b6ab45655ff5f10213b1f0 --- /dev/null +++ b/Macroeconomics/src/macro_nowcast/archive_audit.py @@ -0,0 +1,1212 @@ +"""Auditable validation for downloaded BLS, BEA, Census, DOL, and Fed archives. + +The module deliberately separates local file verification from historical- +provenance authorization. Passing these checks proves container integrity, +expected content, and a small cross-source consistency check. It does not +claim that every release in an archive has been mapped to an exact timestamp. +""" + +from __future__ import annotations + +import csv +import hashlib +import io +import json +import math +import posixpath +import re +import shutil +import subprocess +import tempfile +from datetime import UTC, date, datetime +from pathlib import Path +from typing import Any +from xml.etree import ElementTree +from zipfile import BadZipFile, ZipFile + +from macro_nowcast.bea_gdp_clock_archive import ( + BEA_GDP_CLOCK_DIRECTORY, + BEA_GDP_CLOCK_INDEX_URL, + audit_bea_gdp_clock_archive, +) +from macro_nowcast.bls_cpi_clock_archive import ( + BLS_CPI_CLOCK_DIRECTORY, + audit_bls_cpi_clock_archive, +) +from macro_nowcast.bls_empsit_clock_archive import ( + BLS_EMPSIT_ARCHIVE_INDEX_URL, + BLS_EMPSIT_CLOCK_DIRECTORY, + audit_empsit_text_clock_archive, +) +from macro_nowcast.bls_release_clock import ( + BLS_EMBARGO_CLOCK_TIMING_QUALITY, + BLSReleaseClockError, + parse_empsit_release_clock_archive, +) +from macro_nowcast.calendar import DATE_ONLY_TIMING_QUALITY +from macro_nowcast.census_housing_archive import ( + CENSUS_HOUSING_CITATION_URL, + CENSUS_HOUSING_DIRECTORY, + CENSUS_HOUSING_INDEX_URL, + audit_census_housing_archive, +) +from macro_nowcast.census_retail_archive import ( + CENSUS_RETAIL_CITATION_URL, + CENSUS_RETAIL_DIRECTORY, + CENSUS_RETAIL_INDEX_URL, + audit_census_retail_archive, +) +from macro_nowcast.dol_claims_archive import ( + DOL_CLAIMS_ARCHIVE_URL, + DOL_CLAIMS_DIRECTORY, + DOL_PUBLIC_DOMAIN_URL, + audit_dol_claims_archive, +) +from macro_nowcast.fed_g17_archive import ( + FED_G17_DIRECTORY, + FED_G17_INDEX_URL, + FED_G17_PUBLIC_DOMAIN_URL, + audit_fed_g17_archive, +) +from macro_nowcast.treasury_rates_archive import ( + TREASURY_RATES_DIRECTORY, + TREASURY_RATES_FEED_DOCUMENTATION_URL, + TREASURY_RATES_INDEX_URL, + TREASURY_RATES_METHOD_URL, + audit_treasury_rates_archive, +) + +CES_INDEX_URL = "https://www.bls.gov/web/empsit/cesvindata.htm" +CES_ARCHIVE_URL = "https://www.bls.gov/web/empsit/cesvinall.zip" +CPI_INDEX_URL = "https://www.bls.gov/cpi/tables/supplemental-files/home.htm" +CPI_2024_ARCHIVE_URL = "https://www.bls.gov/cpi/tables/supplemental-files/archive-2024.zip" +BEA_GDP_PAGE_URL = "https://www.bea.gov/data/gdp/gross-domestic-product" +BEA_GDP_VINTAGE_URL = "https://apps.bea.gov/national/xls/gdp-gdi-vintage-history.xlsx" +BEA_NIPA_ARCHIVE_INDEX_URL = "https://apps.bea.gov/histdata/" +BEA_NIPA_SAMPLE_URL = ( + "https://apps.bea.gov/HistData/Files/Releases/GDP_and_PI/2024/Q4/" + "Advance_January-31-2025/Section1all_xls.xlsx" +) +BEA_2024Q4_ADVANCE_RELEASE_URL = ( + "https://www.bea.gov/news/2025/" + "gross-domestic-product-4th-quarter-and-year-2024-advance-estimate" +) +BLS_COPYRIGHT_URL = "https://www.bls.gov/opub/copyright-information.htm" +BEA_PUBLIC_DOMAIN_URL = "https://www.bea.gov/help/faq/147" + +CES_FILENAME = "cesvinall.zip" +CES_RELEASE_INDEX_FILENAME = "empsit-release-index.json" +EMPSIT_DOM_DIRECTORY = "bls-empsit-html" +CPI_FILENAME = "cpi-supplemental-2024.zip" +CPI_RELEASE_INDEX_FILENAME = "cpi-release-index.json" +GDP_VINTAGE_FILENAME = "gdp-gdi-vintage-history.xlsx" +GDP_NIPA_SAMPLE_FILENAME = "bea-nipa-2024q4-advance-section1.xlsx" +CPI_ARCHIVE_YEARS = tuple(range(2012, 2025)) +CPI_CURRENT_PERIODS = ( + *(f"2025{month:02d}" for month in range(1, 10)), + "202511", + "202512", + *(f"2026{month:02d}" for month in range(1, 7)), +) +CPI_DOCUMENTED_MISSING_PERIODS = ("202510",) + +_MAIN_NS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main" +_DOC_REL_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships" +_PKG_REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships" +_CELL_RE = re.compile(r"([A-Z]+)(\d+)") +_QUARTER_RE = re.compile(r"\d{4}Q[1-4]") +_GDP_RELEASE_DATE_RE = re.compile(r"([A-Z][a-z]{2} \d{1,2}, \d{4})") +_CPI_WORKBOOK_RE = re.compile(r"cpi-u[_-](\d{6})\.(xls|xlsx)$", re.IGNORECASE) +_EMPSIT_LABEL_RE = re.compile(r"([A-Za-z]+) (\d{4}) Employment Situation") +_CPI_LABEL_RE = re.compile(r"([A-Za-z]+) (\d{4}) Consumer Price Index") +_MONTH_NUMBERS = { + month: number + for number, month in enumerate( + ( + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", + ), + start=1, + ) +} +_EMPSIT_DOM_FILENAME_RE = re.compile(r"empsit_(\d{8})\.htm") + + +class ArchiveAuditError(RuntimeError): + """Raised when an archive cannot support a required verification claim.""" + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as source: + while chunk := source.read(1024 * 1024): + digest.update(chunk) + return digest.hexdigest() + + +def _file_facts(path: Path) -> dict[str, object]: + return { + "filename": path.name, + "bytes": path.stat().st_size, + "sha256": _sha256(path), + } + + +def _column_number(reference: str) -> int: + match = _CELL_RE.fullmatch(reference) + if match is None: + raise ArchiveAuditError(f"invalid XLSX cell reference: {reference}") + result = 0 + for char in match.group(1): + result = result * 26 + ord(char) - ord("A") + 1 + return result + + +def _column_name(number: int) -> str: + if number < 1: + raise ValueError("column number must be positive") + result = "" + while number: + number, remainder = divmod(number - 1, 26) + result = chr(ord("A") + remainder) + result + return result + + +def _number_or_text(value: str) -> int | float | str: + try: + parsed = float(value) + except ValueError: + return value + return int(parsed) if parsed.is_integer() else parsed + + +def _shared_strings(archive: ZipFile) -> list[str]: + try: + root = ElementTree.fromstring(archive.read("xl/sharedStrings.xml")) + except KeyError: + return [] + return ["".join(node.itertext()) for node in root.findall(f"{{{_MAIN_NS}}}si")] + + +def _sheet_paths(archive: ZipFile) -> dict[str, str]: + workbook = ElementTree.fromstring(archive.read("xl/workbook.xml")) + relationships = ElementTree.fromstring(archive.read("xl/_rels/workbook.xml.rels")) + targets = { + item.attrib["Id"]: item.attrib["Target"] + for item in relationships.findall(f"{{{_PKG_REL_NS}}}Relationship") + } + result: dict[str, str] = {} + for sheet in workbook.findall(f".//{{{_MAIN_NS}}}sheet"): + relationship_id = sheet.attrib[f"{{{_DOC_REL_NS}}}id"] + target = targets[relationship_id] + if target.startswith("/"): + normalized = target.lstrip("/") + else: + normalized = posixpath.normpath(posixpath.join("xl", target)) + result[sheet.attrib["name"]] = normalized + return result + + +def _xlsx_rows(source: Path | bytes, sheet_name: str) -> dict[int, dict[int, Any]]: + archive_source: Path | io.BytesIO + archive_source = io.BytesIO(source) if isinstance(source, bytes) else source + with ZipFile(archive_source) as archive: + bad_member = archive.testzip() + if bad_member is not None: + raise ArchiveAuditError(f"XLSX CRC failure: {bad_member}") + strings = _shared_strings(archive) + paths = _sheet_paths(archive) + if sheet_name not in paths: + raise ArchiveAuditError(f"missing XLSX sheet: {sheet_name}") + root = ElementTree.fromstring(archive.read(paths[sheet_name])) + rows: dict[int, dict[int, Any]] = {} + for row in root.findall(f".//{{{_MAIN_NS}}}row"): + row_number = int(row.attrib["r"]) + values: dict[int, Any] = {} + for cell in row.findall(f"{{{_MAIN_NS}}}c"): + reference = cell.attrib.get("r") + if reference is None: + continue + column = _column_number(reference) + kind = cell.attrib.get("t") + if kind == "inlineStr": + values[column] = "".join(cell.itertext()) + continue + node = cell.find(f"{{{_MAIN_NS}}}v") + if node is None or node.text is None: + continue + raw = node.text + if kind == "s": + values[column] = strings[int(raw)] + elif kind in {"str", "e"}: + values[column] = raw + elif kind == "b": + values[column] = raw == "1" + else: + values[column] = _number_or_text(raw) + rows[row_number] = values + return rows + + +def _xlsx_sheet_names(source: Path | bytes) -> tuple[str, ...]: + archive_source: Path | io.BytesIO + archive_source = io.BytesIO(source) if isinstance(source, bytes) else source + with ZipFile(archive_source) as archive: + bad_member = archive.testzip() + if bad_member is not None: + raise ArchiveAuditError(f"XLSX CRC failure: {bad_member}") + return tuple(_sheet_paths(archive)) + + +def _find_text(source: Path | bytes, text: str) -> list[str]: + matches: list[str] = [] + for sheet in _xlsx_sheet_names(source): + for row_number, values in _xlsx_rows(source, sheet).items(): + for column, value in values.items(): + if str(value).strip() == text: + matches.append(f"{sheet}!{_column_name(column)}{row_number}") + return matches + + +def _zip_facts(path: Path) -> dict[str, object]: + with ZipFile(path) as archive: + bad_member = archive.testzip() + if bad_member is not None: + raise ArchiveAuditError(f"ZIP CRC failure: {bad_member}") + return {"member_count": len(archive.infolist()), "crc_valid": True} + + +def _previous_month(release_date: str) -> tuple[int, int]: + release = datetime.strptime(release_date, "%Y-%m-%d").date() + if release.month == 1: + return release.year - 1, 12 + return release.year, release.month - 1 + + +def _period_from_empsit_event(event: dict[str, object]) -> tuple[tuple[int, int], str]: + label = event.get("observation_label") + if isinstance(label, str): + match = _EMPSIT_LABEL_RE.fullmatch(label) + if match is not None: + return (int(match.group(2)), _MONTH_NUMBERS[match.group(1)]), "official_label" + return _previous_month(str(event["release_date"])), "official_date_prior_month_rule" + + +def _audit_ces_release_mapping( + path: Path, + periods: list[tuple[int, int]], +) -> dict[str, object]: + document = json.loads(path.read_text(encoding="utf-8")) + events = document.get("release_events") + if not isinstance(events, list): + raise ArchiveAuditError("CES release index has no release_events list") + expected = set(periods) + mapped: dict[tuple[int, int], dict[str, str]] = {} + event_by_period: dict[tuple[int, int], dict[str, object]] = {} + for raw_event in events: + if not isinstance(raw_event, dict) or "release_date" not in raw_event: + raise ArchiveAuditError("CES release index contains an invalid event") + period, basis = _period_from_empsit_event(raw_event) + if period not in expected or period in mapped: + continue + release_date = str(raw_event["release_date"]) + mapped[period] = {"release_date": release_date, "mapping_basis": basis} + event_by_period[period] = raw_event + + october_2025 = (2025, 10) + november_2025 = (2025, 11) + if october_2025 in expected and october_2025 not in mapped: + november_event = event_by_period.get(november_2025) + if november_event is None: + raise ArchiveAuditError("CES special October 2025 release mapping is unavailable") + mapped[october_2025] = { + "release_date": str(november_event["release_date"]), + "mapping_basis": "official_november_release_includes_october_ces_initial", + } + + missing = sorted(expected - set(mapped)) + if missing: + formatted = [f"{year:04d}-{month:02d}" for year, month in missing] + raise ArchiveAuditError(f"CES release mapping is incomplete: {formatted}") + + mapping_rows = [ + { + "vintage_period": f"{year:04d}-{month:02d}", + **mapped[(year, month)], + } + for year, month in periods + ] + basis_counts: dict[str, int] = {} + for row in mapping_rows: + basis = str(row["mapping_basis"]) + basis_counts[basis] = basis_counts.get(basis, 0) + 1 + result: dict[str, object] = { + **_file_facts(path), + "official_url": str(document.get("source_url", "")), + "source_release_event_count": len(events), + "mapped_vintage_periods": len(mapping_rows), + "unique_release_dates": len({str(row["release_date"]) for row in mapping_rows}), + "mapping_basis_counts": basis_counts, + "release_date_mapping": mapping_rows, + "exact_intraday_time_mapping_pending": True, + "passed": True, + } + if october_2025 in expected: + result["special_shared_release"] = { + "release_date": "2025-12-16", + "vintage_periods": ["2025-10", "2025-11"], + "evidence_url": ("https://www.bls.gov/news.release/archives/empsit_12162025.htm"), + } + return result + + +def _audit_ces(path: Path, release_index_path: Path) -> dict[str, object]: + facts = _file_facts(path) + facts.update(_zip_facts(path)) + member = "tri_000000_SA.csv" + with ZipFile(path) as archive: + if member not in archive.namelist(): + raise ArchiveAuditError(f"missing CES total-nonfarm member: {member}") + with archive.open(member) as binary: + rows = csv.reader(io.TextIOWrapper(binary, encoding="utf-8-sig", newline="")) + header = next(rows) + if header[:2] != ["year", "month"]: + raise ArchiveAuditError("unexpected CES vintage CSV header") + periods: list[tuple[int, int]] = [] + last_nonempty_observation: list[str] = [] + for row in rows: + if not row: + continue + periods.append((int(row[0]), int(row[1]))) + nonempty = [header[index] for index, value in enumerate(row[2:], start=2) if value] + last_nonempty_observation.append(nonempty[-1]) + if not periods or periods[0] != (2003, 5): + raise ArchiveAuditError("CES vintage coverage does not begin at 2003-05") + if periods != sorted(set(periods)): + raise ArchiveAuditError("CES vintage periods are duplicated or out of order") + release_mapping = _audit_ces_release_mapping(release_index_path, periods) + facts.update( + { + "passed": True, + "official_url": CES_ARCHIVE_URL, + "target_series_id": "CES0000000001", + "verified_member": member, + "observation_columns": len(header) - 2, + "vintage_rows": len(periods), + "first_vintage_period": f"{periods[0][0]:04d}-{periods[0][1]:02d}", + "last_vintage_period": f"{periods[-1][0]:04d}-{periods[-1][1]:02d}", + "first_row_latest_observation": last_nonempty_observation[0], + "release_mapping": release_mapping, + "provenance_status": "content_and_release_dates_verified_intraday_times_pending", + } + ) + return facts + + +def _cpi_archive_filename(year: int) -> str: + return f"cpi-supplemental-{year}.zip" + + +def _cpi_archive_url(year: int) -> str: + return f"https://www.bls.gov/cpi/tables/supplemental-files/archive-{year}.zip" + + +def _cpi_monthly_members(archive: ZipFile, year: int) -> dict[str, str]: + result: dict[str, str] = {} + for name in archive.namelist(): + match = _CPI_WORKBOOK_RE.search(name) + if match is None or not match.group(1).startswith(str(year)): + continue + result[match.group(1)] = name + expected = {f"{year}{month:02d}" for month in range(1, 13)} + missing = sorted(expected - set(result)) + if missing: + raise ArchiveAuditError(f"CPI {year} archive is missing monthly workbooks: {missing}") + return result + + +def _verify_core_cpi_xlsx(payload: bytes, label: str) -> list[str]: + matches = _find_text(payload, "All items less food and energy") + if not matches: + raise ArchiveAuditError(f"core CPI row absent from {label}") + return matches + + +def convert_legacy_xls_to_xlsx( + payloads: dict[str, bytes], +) -> tuple[dict[str, bytes], str]: + converted_payloads: dict[str, bytes] = {} + real_xls: dict[str, bytes] = {} + for period, payload in payloads.items(): + if payload.startswith(b"PK"): + converted_payloads[period] = payload + else: + real_xls[period] = payload + if not real_xls: + return converted_payloads, "fixture_xlsx_payload" + + executable = shutil.which("soffice") + if executable is None: + raise ArchiveAuditError( + "legacy CPI XLS content verification requires LibreOffice 'soffice'" + ) + with tempfile.TemporaryDirectory(prefix="macro-nowcast-cpi-") as temporary: + root = Path(temporary) + input_directory = root / "input" + output_directory = root / "output" + input_directory.mkdir() + output_directory.mkdir() + sources: list[Path] = [] + for period, payload in sorted(real_xls.items()): + source = input_directory / f"cpi-u-{period}.xls" + source.write_bytes(payload) + sources.append(source) + completed = subprocess.run( + [ + executable, + f"-env:UserInstallation={(root / 'profile').as_uri()}", + "--headless", + "--convert-to", + "xlsx", + "--outdir", + str(output_directory), + *(str(source) for source in sources), + ], + check=False, + capture_output=True, + text=True, + timeout=120, + ) + if completed.returncode != 0: + message = completed.stderr.strip() or completed.stdout.strip() + raise ArchiveAuditError(f"legacy CPI XLS conversion failed: {message}") + for period in sorted(real_xls): + converted = output_directory / f"cpi-u-{period}.xlsx" + if not converted.exists(): + raise ArchiveAuditError(f"legacy CPI XLS conversion missing output: {period}") + converted_payloads[period] = converted.read_bytes() + return converted_payloads, Path(executable).name + + +def _verify_legacy_core_cpi( + payloads: dict[str, bytes], +) -> tuple[dict[str, list[str]], str]: + converted, tool = convert_legacy_xls_to_xlsx(payloads) + locations = { + period: _verify_core_cpi_xlsx(payload, period) for period, payload in converted.items() + } + return locations, tool + + +def _audit_cpi_release_mapping( + path: Path, + expected_periods: set[str], +) -> dict[str, object]: + document = json.loads(path.read_text(encoding="utf-8")) + events = document.get("release_events") + if not isinstance(events, list): + raise ArchiveAuditError("CPI release index has no release_events list") + mapping: dict[str, str] = {} + for event in events: + if not isinstance(event, dict): + raise ArchiveAuditError("CPI release index contains an invalid event") + label = event.get("observation_label") + if not isinstance(label, str): + continue + match = _CPI_LABEL_RE.fullmatch(label) + if match is None: + continue + period = f"{int(match.group(2)):04d}{_MONTH_NUMBERS[match.group(1)]:02d}" + if period in expected_periods: + mapping[period] = str(event["release_date"]) + missing = sorted(expected_periods - set(mapping)) + if missing: + raise ArchiveAuditError(f"CPI release mapping is incomplete: {missing}") + rows = [ + { + "snapshot_period": f"{period[:4]}-{period[4:]}", + "release_date": mapping[period], + "mapping_basis": "official_observation_label", + } + for period in sorted(mapping) + ] + return { + **_file_facts(path), + "official_url": str(document.get("source_url", "")), + "source_release_event_count": len(events), + "mapped_snapshot_periods": len(rows), + "unique_release_dates": len({str(row["release_date"]) for row in rows}), + "release_date_mapping": rows, + "exact_intraday_time_mapping_pending": True, + "passed": True, + } + + +def _audit_cpi(directory: Path) -> dict[str, object]: + annual_archives: dict[str, dict[str, object]] = {} + layout_counts: dict[str, dict[str, int]] = {} + core_location_examples: dict[str, list[str]] = {} + legacy_payloads: dict[str, bytes] = {} + verified_xlsx = 0 + legacy_xls = 0 + + for year in CPI_ARCHIVE_YEARS: + path = directory / _cpi_archive_filename(year) + facts = _file_facts(path) + facts.update(_zip_facts(path)) + with ZipFile(path) as archive: + members = _cpi_monthly_members(archive, year) + year_xlsx = 0 + year_xls = 0 + for period, name in sorted(members.items()): + if name.lower().endswith(".xlsx"): + locations = _verify_core_cpi_xlsx(archive.read(name), name) + year_xlsx += 1 + verified_xlsx += 1 + if period.endswith(("01", "12")): + core_location_examples[period] = locations + else: + year_xls += 1 + legacy_xls += 1 + legacy_payloads[period] = archive.read(name) + facts.update( + { + "passed": True, + "official_url": _cpi_archive_url(year), + "monthly_workbooks": 12, + "xlsx_content_verified": year_xlsx, + "legacy_xls_inventory_verified": year_xls, + } + ) + annual_archives[str(year)] = facts + layout_counts[str(year)] = {"xlsx": year_xlsx, "xls": year_xls} + + legacy_locations, legacy_conversion_tool = _verify_legacy_core_cpi(legacy_payloads) + for period, locations in sorted(legacy_locations.items()): + if period.endswith(("01", "12")): + core_location_examples[period] = locations + + current_files: dict[str, dict[str, object]] = {} + current_directory = directory / "cpi-current" + for period in CPI_CURRENT_PERIODS: + path = current_directory / f"cpi-u-{period}.xlsx" + locations = _verify_core_cpi_xlsx(path.read_bytes(), path.name) + current_files[period] = { + **_file_facts(path), + "official_url": ( + f"https://www.bls.gov/cpi/tables/supplemental-files/cpi-u-{period}.xlsx" + ), + "core_cpi_locations": locations, + "passed": True, + } + verified_xlsx += 1 + + expected_periods = { + f"{year}{month:02d}" for year in CPI_ARCHIVE_YEARS for month in range(1, 13) + } | set(CPI_CURRENT_PERIODS) + release_mapping = _audit_cpi_release_mapping( + directory / CPI_RELEASE_INDEX_FILENAME, + expected_periods, + ) + + return { + "passed": True, + "official_url": CPI_INDEX_URL, + "target_series_id": "CUSR0000SA0L1E", + "annual_archive_count": len(annual_archives), + "annual_coverage": "2012-2024", + "annual_archives": annual_archives, + "layout_counts_by_year": layout_counts, + "current_snapshot_count": len(current_files), + "current_coverage": "2025-01 through 2026-06", + "current_files": current_files, + "documented_missing_periods": list(CPI_DOCUMENTED_MISSING_PERIODS), + "monthly_workbooks_inventoried": len(annual_archives) * 12 + len(current_files), + "xlsx_core_content_verified": verified_xlsx, + "legacy_xls_inventory_verified": legacy_xls, + "legacy_xls_core_content_verified": len(legacy_locations), + "legacy_xls_conversion_tool": legacy_conversion_tool, + "legacy_xls_value_parser_available": True, + "legacy_xls_value_parser_pending": False, + "core_cpi_location_examples": core_location_examples, + "release_mapping": release_mapping, + "provenance_status": ( + "full_official_inventory_core_rows_and_release_dates_verified_" + "legacy_values_parseable_intraday_times_unverified" + ), + } + + +def _quarter_rows(rows: dict[int, dict[int, Any]]) -> dict[str, int]: + result: dict[str, int] = {} + for row_number, values in rows.items(): + for value in values.values(): + text = str(value).strip() + if _QUARTER_RE.fullmatch(text): + result[text] = row_number + break + return result + + +def _summary_advance(rows: dict[int, dict[int, Any]], quarter: str) -> dict[str, object]: + quarters = _quarter_rows(rows) + if quarter not in quarters: + raise ArchiveAuditError(f"GDP vintage summary is missing {quarter}") + start = quarters[quarter] + later_quarter_rows = sorted(row for row in quarters.values() if row > start) + stop = later_quarter_rows[0] if later_quarter_rows else max(rows) + 1 + for row_number in range(start + 1, stop): + values = rows.get(row_number, {}) + if str(values.get(2, "")).strip().lower() == "advance": + return { + "row": row_number, + "growth_qoq_saar": float(values[5]), + "release_date_text": str(values[7]).strip(), + } + raise ArchiveAuditError(f"GDP vintage summary is missing {quarter} Advance row") + + +def _audit_gdp_initial_rows( + rows: dict[int, dict[int, Any]], + quarters: dict[str, int], +) -> tuple[dict[str, int], int, list[dict[str, str]]]: + ordered = sorted(quarters.items(), key=lambda item: item[1]) + labels: dict[str, int] = {} + dated_initials = 0 + release_mapping: list[dict[str, str]] = [] + for index, (quarter, start) in enumerate(ordered): + stop = ordered[index + 1][1] if index + 1 < len(ordered) else max(rows) + 1 + matches: list[tuple[str, Any, str]] = [] + for row_number in range(start + 1, stop): + values = rows.get(row_number, {}) + label = str(values.get(2, "")).strip() + if label in {"Advance", "Initial"}: + matches.append((label, values.get(5), str(values.get(7, "")).strip())) + if len(matches) != 1: + raise ArchiveAuditError( + f"GDP vintage summary requires one initial estimate for {quarter}; " + f"found {len(matches)}" + ) + label, growth, release_text = matches[0] + float(growth) + if not release_text: + raise ArchiveAuditError(f"GDP initial estimate is missing a date for {quarter}") + release_match = _GDP_RELEASE_DATE_RE.search(release_text) + if release_match is None: + raise ArchiveAuditError( + f"GDP initial estimate has an invalid date for {quarter}" + ) + release_date = datetime.strptime( + release_match.group(1), + "%b %d, %Y", + ).date() + labels[label] = labels.get(label, 0) + 1 + dated_initials += 1 + release_mapping.append( + { + "quarter": quarter, + "release_date": release_date.isoformat(), + "source_release_type": label, + } + ) + if len({row["release_date"] for row in release_mapping}) != len(release_mapping): + raise ArchiveAuditError("GDP initial releases contain duplicate dates") + return labels, dated_initials, release_mapping + + +def _audit_gdp_estimate_rows( + rows: dict[int, dict[int, Any]], +) -> tuple[dict[str, int], int]: + accepted = { + "Advance", + "Initial", + "Second", + "Preliminary", + "Third", + "Final", + "Updated", + "Revised", + } + labels: dict[str, int] = {} + count = 0 + for row_number, values in rows.items(): + label = str(values.get(2, "")).strip() + if label not in accepted: + continue + try: + float(values.get(5)) + except (TypeError, ValueError) as exc: + raise ArchiveAuditError( + f"GDP estimate row {row_number} has invalid growth value" + ) from exc + if not str(values.get(7, "")).strip(): + raise ArchiveAuditError(f"GDP estimate row {row_number} has no release date") + labels[label] = labels.get(label, 0) + 1 + count += 1 + return labels, count + + +def _audit_gdp_summary(path: Path) -> tuple[dict[str, object], dict[str, object]]: + facts = _file_facts(path) + sheets = _xlsx_sheet_names(path) + if not {"ReadMe", "Vintage History"}.issubset(sheets): + raise ArchiveAuditError("unexpected GDP vintage-history workbook sheets") + rows = _xlsx_rows(path, "Vintage History") + quarters = _quarter_rows(rows) + initial_labels, dated_initials, initial_release_mapping = _audit_gdp_initial_rows( + rows, + quarters, + ) + estimate_labels, dated_estimates = _audit_gdp_estimate_rows(rows) + advance = _summary_advance(rows, "2024Q4") + facts.update( + { + "passed": True, + "official_url": BEA_GDP_VINTAGE_URL, + "sheets": list(sheets), + "quarter_count": len(quarters), + "first_quarter": min(quarters), + "last_quarter": max(quarters), + "initial_estimate_count": dated_initials, + "initial_estimate_labels": initial_labels, + "initial_release_mapping": initial_release_mapping, + "all_initial_estimates_have_release_date_text": True, + "estimate_row_count": dated_estimates, + "estimate_row_labels": estimate_labels, + "all_estimate_rows_have_numeric_growth_and_release_date_text": True, + "supports_published_first_release_growth": True, + "supplies_real_gdp_levels": False, + "verified_2024q4_advance": advance, + "provenance_status": "growth_summary_verified_not_real_gdp_levels", + } + ) + return facts, advance + + +def _metadata_text(rows: dict[int, dict[int, Any]], prefix: str) -> str: + for values in rows.values(): + for value in values.values(): + text = str(value).strip() + if text.startswith(prefix): + return text + raise ArchiveAuditError(f"missing workbook metadata: {prefix}") + + +def _audit_gdp_nipa( + path: Path, + *, + summary_advance: dict[str, object], +) -> dict[str, object]: + facts = _file_facts(path) + sheets = _xlsx_sheet_names(path) + if "T10106-Q" not in sheets: + raise ArchiveAuditError("NIPA snapshot is missing T10106-Q") + rows = _xlsx_rows(path, "T10106-Q") + header_row = next( + values for values in rows.values() if "2024Q4" in {str(value) for value in values.values()} + ) + q3_column = next(column for column, value in header_row.items() if value == "2024Q3") + q4_column = next(column for column, value in header_row.items() if value == "2024Q4") + gdp_row = next( + values + for values in rows.values() + if str(values.get(1, "")).strip() == "1" + and str(values.get(2, "")).strip() == "Gross domestic product" + and str(values.get(3, "")).strip() == "A191RX" + ) + q3_level = float(gdp_row[q3_column]) + q4_level = float(gdp_row[q4_column]) + calculated = 100.0 * ((q4_level / q3_level) ** 4 - 1.0) + published = float(summary_advance["growth_qoq_saar"]) + if not math.isclose(round(calculated, 1), published, abs_tol=0.05): + raise ArchiveAuditError( + "NIPA level transformation does not reconcile to the published Advance growth" + ) + published_text = _metadata_text(rows, "Data published") + facts.update( + { + "passed": True, + "official_url": BEA_NIPA_SAMPLE_URL, + "target_series_id": "GDPC1", + "table": "NIPA 1.1.6", + "line": 1, + "series_code": "A191RX", + "units": "millions_of_chained_2017_dollars_saar", + "workbook_metadata": published_text, + "q3_2024_level": int(q3_level), + "q4_2024_level": int(q4_level), + "calculated_qoq_saar_percent": calculated, + "published_qoq_saar_percent": published, + "rounded_reconciliation_passed": True, + "verified_release_timestamp_utc": "2025-01-30T13:30:00Z", + "release_evidence_url": BEA_2024Q4_ADVANCE_RELEASE_URL, + "archive_directory_label": "Advance_January-31-2025", + "archive_directory_date_disagrees_with_release_evidence": True, + "provenance_status": "single_release_snapshot_verified_full_coverage_pending", + } + ) + return facts + + +def _safe_audit(name: str, callback: Any) -> dict[str, object]: + try: + return callback() + except (ArchiveAuditError, BadZipFile, FileNotFoundError, KeyError, StopIteration) as exc: + return {"filename": name, "passed": False, "error": str(exc)} + + +def _audit_empsit_dom_exports(directory: Path, index_path: Path) -> dict[str, object]: + document = json.loads(index_path.read_text(encoding="utf-8")) + events = [event for event in document["release_events"] if event.get("html_available")] + expected: dict[str, dict[str, object]] = {} + for event in events: + release = datetime.strptime(str(event["release_date"]), "%Y-%m-%d").date() + expected[f"empsit_{release:%m%d%Y}.htm"] = event + actual = {path.name: path for path in directory.glob("empsit_*.htm")} + missing = sorted(set(expected) - set(actual)) + extra = sorted(set(actual) - set(expected)) + if missing or extra: + raise ArchiveAuditError( + f"Employment Situation DOM inventory mismatch: missing={missing[:3]}, extra={extra[:3]}" + ) + try: + clock_archive = parse_empsit_release_clock_archive(directory) + except BLSReleaseClockError as exc: + raise ArchiveAuditError(str(exc)) from exc + files: dict[str, dict[str, object]] = {} + structured = 0 + preformatted = 0 + for name in sorted(expected): + if _EMPSIT_DOM_FILENAME_RE.fullmatch(name) is None: + raise ArchiveAuditError(f"invalid Employment Situation DOM filename: {name}") + path = actual[name] + document_text = path.read_text(encoding="utf-8") + if not document_text.rstrip().endswith(""): + raise ArchiveAuditError(f"incomplete Employment Situation DOM export: {name}") + if "Employment Situation News Release" not in document_text: + raise ArchiveAuditError(f"Employment Situation marker missing: {name}") + if "Table A-1" not in document_text: + raise ArchiveAuditError(f"Employment Situation table A-1 missing: {name}") + layout = ( + "html_table_a1" if 'id="cps_empsit_a01"' in document_text else "preformatted_table_a1" + ) + structured += layout == "html_table_a1" + preformatted += layout == "preformatted_table_a1" + release_date = str(expected[name]["release_date"]) + parsed_release_date = date.fromisoformat(release_date) + clock = clock_archive.clocks.get(parsed_release_date) + exclusion_reason = clock_archive.exclusions.get(parsed_release_date) + facts = _file_facts(path) + files[release_date] = { + **facts, + "official_url": f"https://www.bls.gov/news.release/archives/{name}", + "observation_label": expected[name].get("observation_label"), + "layout": layout, + "complete_dom": True, + "release_timestamp_utc": ( + clock.release_timestamp.isoformat().replace("+00:00", "Z") + if clock is not None + else None + ), + "printed_timezone": clock.printed_timezone if clock is not None else None, + "timing_quality": ( + BLS_EMBARGO_CLOCK_TIMING_QUALITY + if clock is not None + else DATE_ONLY_TIMING_QUALITY + ), + "clock_exclusion_reason": exclusion_reason, + } + hashes = {str(item["sha256"]) for item in files.values()} + if len(hashes) != len(files): + raise ArchiveAuditError("Employment Situation DOM exports contain duplicate content hashes") + return { + "passed": True, + "official_url": str(document["source_url"]), + "directory": directory.name, + "acquisition_format": "browser_rendered_complete_dom_export", + "server_original_bytes_claimed": False, + "file_count": len(files), + "first_release_date": min(files), + "last_release_date": max(files), + "structured_table_count": structured, + "preformatted_table_count": preformatted, + "all_files_complete": True, + "all_hashes_unique": True, + "exact_release_clock_count": len(clock_archive.clocks), + "date_only_clock_exclusion_count": len(clock_archive.exclusions), + "date_only_clock_exclusions": { + release_date.isoformat(): reason + for release_date, reason in clock_archive.exclusions.items() + }, + "exact_timing_quality": BLS_EMBARGO_CLOCK_TIMING_QUALITY, + "files": files, + "provenance_status": ( + "complete_official_dom_exports_table_a1_inventory_verified_" + "release_dates_verified_intraday_not_normalized" + ), + } + + +def audit_agency_vintages( + raw_dir: str | Path, + *, + audited_at: datetime | None = None, +) -> dict[str, object]: + """Verify locally downloaded official archive artifacts without network access.""" + + directory = Path(raw_dir).resolve() + timestamp = (audited_at or datetime.now(UTC)).astimezone(UTC) + ces = _safe_audit( + CES_FILENAME, + lambda: _audit_ces( + directory / CES_FILENAME, + directory / CES_RELEASE_INDEX_FILENAME, + ), + ) + cpi = _safe_audit(CPI_FILENAME, lambda: _audit_cpi(directory)) + + summary_holder: dict[str, object] = {} + + def audit_summary() -> dict[str, object]: + facts, advance = _audit_gdp_summary(directory / GDP_VINTAGE_FILENAME) + summary_holder.update(advance) + return facts + + gdp_summary = _safe_audit(GDP_VINTAGE_FILENAME, audit_summary) + if gdp_summary.get("passed"): + gdp_nipa = _safe_audit( + GDP_NIPA_SAMPLE_FILENAME, + lambda: _audit_gdp_nipa( + directory / GDP_NIPA_SAMPLE_FILENAME, + summary_advance=summary_holder, + ), + ) + else: + gdp_nipa = { + "filename": GDP_NIPA_SAMPLE_FILENAME, + "passed": False, + "error": "GDP summary audit failed; cross-check not attempted", + } + + rejected_ces_xlsx: dict[str, object] | None = None + rejected_path = directory / "cesvin00.xlsx" + if rejected_path.exists(): + rejected_ces_xlsx = _safe_audit( + rejected_path.name, + lambda: { + **_file_facts(rejected_path), + "sheets": list(_xlsx_sheet_names(rejected_path)), + "passed": True, + }, + ) + + artifacts = { + "ces": ces, + "cpi": cpi, + "gdp_vintage_summary": gdp_summary, + "gdp_nipa_snapshot": gdp_nipa, + } + gdp_clock_directory = directory / BEA_GDP_CLOCK_DIRECTORY + if gdp_clock_directory.exists(): + if gdp_summary.get("passed"): + initial_release_mapping = gdp_summary.get("initial_release_mapping", []) + assert isinstance(initial_release_mapping, list) + expected_initial_releases = { + date.fromisoformat(str(row["release_date"])): str( + row["source_release_type"] + ) + for row in initial_release_mapping + if isinstance(row, dict) + } + artifacts["gdp_release_clock_evidence"] = _safe_audit( + BEA_GDP_CLOCK_DIRECTORY, + lambda: audit_bea_gdp_clock_archive( + gdp_clock_directory, + expected_initial_releases=expected_initial_releases, + ), + ) + else: + artifacts["gdp_release_clock_evidence"] = { + "filename": BEA_GDP_CLOCK_DIRECTORY, + "passed": False, + "error": "GDP summary audit failed; clock reconciliation not attempted", + } + nipa_level_directory = directory / "bea-nipa-levels" + if nipa_level_directory.exists(): + from macro_nowcast.bea_nipa_archive import ( + BEANIPAArchiveError, + audit_bea_nipa_level_archive, + ) + + def audit_nipa_levels() -> dict[str, object]: + try: + return audit_bea_nipa_level_archive( + nipa_level_directory, + clock_evidence_path=( + directory / BEA_GDP_CLOCK_DIRECTORY / "clock-evidence.json" + ), + published_growth_path=directory / GDP_VINTAGE_FILENAME, + ) + except BEANIPAArchiveError as exc: + raise ArchiveAuditError(str(exc)) from exc + + artifacts["gdp_nipa_level_archive"] = _safe_audit( + "bea-nipa-levels", + audit_nipa_levels, + ) + empsit_dom_directory = directory / EMPSIT_DOM_DIRECTORY + if empsit_dom_directory.exists(): + artifacts["employment_situation_dom"] = _safe_audit( + EMPSIT_DOM_DIRECTORY, + lambda: _audit_empsit_dom_exports( + empsit_dom_directory, + directory / CES_RELEASE_INDEX_FILENAME, + ), + ) + empsit_text_clock_directory = directory / BLS_EMPSIT_CLOCK_DIRECTORY + if empsit_text_clock_directory.exists(): + artifacts["employment_situation_txt_clock_evidence"] = _safe_audit( + BLS_EMPSIT_CLOCK_DIRECTORY, + lambda: audit_empsit_text_clock_archive( + empsit_text_clock_directory, + release_index_path=directory / CES_RELEASE_INDEX_FILENAME, + ), + ) + cpi_clock_directory = directory / BLS_CPI_CLOCK_DIRECTORY + if cpi_clock_directory.exists(): + artifacts["cpi_release_clock_evidence"] = _safe_audit( + BLS_CPI_CLOCK_DIRECTORY, + lambda: audit_bls_cpi_clock_archive( + cpi_clock_directory, + release_index_path=directory / CPI_RELEASE_INDEX_FILENAME, + ), + ) + dol_claims_directory = directory / DOL_CLAIMS_DIRECTORY + if dol_claims_directory.exists(): + artifacts["dol_weekly_claims"] = _safe_audit( + DOL_CLAIMS_DIRECTORY, + lambda: audit_dol_claims_archive(dol_claims_directory), + ) + fed_g17_directory = directory / FED_G17_DIRECTORY + if fed_g17_directory.exists(): + artifacts["fed_g17_industrial_production"] = _safe_audit( + FED_G17_DIRECTORY, + lambda: audit_fed_g17_archive(fed_g17_directory), + ) + treasury_rates_directory = directory / TREASURY_RATES_DIRECTORY + if treasury_rates_directory.exists(): + artifacts["treasury_10y_daily_rates"] = _safe_audit( + TREASURY_RATES_DIRECTORY, + lambda: audit_treasury_rates_archive(treasury_rates_directory), + ) + census_retail_directory = directory / CENSUS_RETAIL_DIRECTORY + if census_retail_directory.exists(): + artifacts["census_retail_sales"] = _safe_audit( + CENSUS_RETAIL_DIRECTORY, + lambda: audit_census_retail_archive(census_retail_directory), + ) + census_housing_directory = directory / CENSUS_HOUSING_DIRECTORY + if census_housing_directory.exists(): + artifacts["census_housing_starts"] = _safe_audit( + CENSUS_HOUSING_DIRECTORY, + lambda: audit_census_housing_archive(census_housing_directory), + ) + required_passed = all(bool(item.get("passed")) for item in artifacts.values()) + report: dict[str, object] = { + "schema_version": 1, + "status": "verified_with_limitations" if required_passed else "failed", + "audited_at": timestamp.isoformat().replace("+00:00", "Z"), + "raw_directory": str(directory), + "api_credentials_used": False, + "api_txt_read": False, + "operator_opt_in_basis": "user_requested_acquisition_and_verification", + "authorization_basis": { + "bls_public_domain_page": BLS_COPYRIGHT_URL, + "bea_public_domain_page": BEA_PUBLIC_DOMAIN_URL, + "dol_public_domain_page": DOL_PUBLIC_DOMAIN_URL, + "federal_reserve_public_domain_page": FED_G17_PUBLIC_DOMAIN_URL, + "treasury_official_feed_documentation": TREASURY_RATES_FEED_DOCUMENTATION_URL, + "treasury_rate_methodology": TREASURY_RATES_METHOD_URL, + "census_citation_policy": CENSUS_RETAIL_CITATION_URL, + "census_housing_citation_policy": CENSUS_HOUSING_CITATION_URL, + "legal_advice": False, + }, + "source_indexes": { + "ces": CES_INDEX_URL, + "employment_situation": BLS_EMPSIT_ARCHIVE_INDEX_URL, + "cpi": CPI_INDEX_URL, + "gdp": BEA_GDP_PAGE_URL, + "gdp_news_archive": BEA_GDP_CLOCK_INDEX_URL, + "bea_nipa_archive": BEA_NIPA_ARCHIVE_INDEX_URL, + "dol_weekly_claims": DOL_CLAIMS_ARCHIVE_URL, + "fed_g17_industrial_production": FED_G17_INDEX_URL, + "treasury_10y_daily_rates": TREASURY_RATES_INDEX_URL, + "census_retail_sales": CENSUS_RETAIL_INDEX_URL, + "census_housing_starts": CENSUS_HOUSING_INDEX_URL, + }, + "artifacts": artifacts, + "archive_ingestion_approval": { + "terms_reviewed": True, + "operator_opt_in": True, + "full_coverage_audited": False, + }, + "historical_ingestion_ready": False, + "remaining_gates": [ + ( + "Employment Situation embargo clocks are verified for the complete " + "acquired PAYEMS target window using 2003-2008 official TXT and later " + "HTML evidence, except the explicitly retained 2012-12-07 EST/EDT " + "source conflict." + ), + ( + "CPI embargo clocks are verified for all 173 acquired target snapshots; " + "the supplemental archive's documented October 2025 gap remains missing." + ), + ( + "GDP initial-release clocks are verified for all 98 target events. " + "The official NIPA directory supplies 96 initial Section 1 level " + "snapshots; 2002Q1 and 2002Q2 predate its available release folders " + "and remain explicit, non-imputed archive gaps." + ), + ( + "Acquire genuine original-provider vintages for the broader predictor " + "set beyond the acquired DOL claims, Fed G.17 industrial production, " + "Treasury daily 10-year CMT observations, Census retail sales, CPS " + "unemployment-rate, and CES sector histories before extending " + "conclusions beyond the archive pilot. Treasury rates are point-in-time " + "market observations; the feed does not reconstruct later corrections." + ), + ], + } + if rejected_ces_xlsx is not None: + report["rejected_optional_downloads"] = [rejected_ces_xlsx] + return report + + +def write_agency_vintage_audit( + raw_dir: str | Path, + output_path: str | Path, + *, + audited_at: datetime | None = None, +) -> dict[str, object]: + """Run the offline audit and write its deterministic JSON evidence record.""" + + report = audit_agency_vintages(raw_dir, audited_at=audited_at) + destination = Path(output_path).resolve() + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8") + return { + "status": report["status"], + "audit_path": destination, + "historical_ingestion_ready": report["historical_ingestion_ready"], + } diff --git a/Macroeconomics/src/macro_nowcast/archive_ingestion.py b/Macroeconomics/src/macro_nowcast/archive_ingestion.py new file mode 100644 index 0000000000000000000000000000000000000000..f8ad9b3ad4468e122fdf64800dd470dc04237881 --- /dev/null +++ b/Macroeconomics/src/macro_nowcast/archive_ingestion.py @@ -0,0 +1,1940 @@ +"""Parse audited BLS/BEA/Census/DOL/Federal Reserve archives into canonical rows. + +Verified source-page clocks propagate as exact timezone-aware timestamps. Events +without equivalent evidence retain the documented conservative date-only rule. +""" + +from __future__ import annotations + +import csv +import hashlib +import io +import json +import re +from collections import defaultdict +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from datetime import UTC, date, datetime, time, timedelta +from html.parser import HTMLParser +from pathlib import Path +from typing import ClassVar +from zipfile import ZipFile + +import polars as pl + +from macro_nowcast.archive_audit import ( + CES_FILENAME, + CPI_ARCHIVE_YEARS, + CPI_CURRENT_PERIODS, + CPI_RELEASE_INDEX_FILENAME, + GDP_VINTAGE_FILENAME, + ArchiveAuditError, + audit_agency_vintages, + convert_legacy_xls_to_xlsx, +) +from macro_nowcast.archive_audit import _xlsx_rows as read_xlsx_rows +from macro_nowcast.bea_gdp_clock_archive import ( + BEA_GDP_CLOCK_DIRECTORY, + BEA_GDP_CLOCK_FILENAME, + BEA_GDP_CLOCK_TIMING_QUALITY, + BEAGDPClockArchive, + BEAReleaseClock, + parse_bea_gdp_clock_archive, +) +from macro_nowcast.bea_nipa_archive import ( + BEA_NIPA_LEVEL_DIRECTORY, + BEA_NIPA_LEVEL_SERIES_ID, + BEA_NIPA_LEVEL_SOURCE, + parse_bea_nipa_level_archive, +) +from macro_nowcast.bls_cpi_clock_archive import ( + BLS_CPI_CLOCK_DIRECTORY, + BLS_CPI_CLOCK_FILENAME, + BLSCPIClockArchive, + parse_bls_cpi_clock_archive, +) +from macro_nowcast.bls_empsit_clock_archive import ( + BLS_EMPSIT_CLOCK_DIRECTORY, + merge_empsit_release_clocks, + parse_empsit_text_clock_archive, +) +from macro_nowcast.bls_release_clock import ( + BLS_EMBARGO_CLOCK_TIMING_QUALITY, + BLSReleaseClock, + parse_empsit_release_clock_archive, +) +from macro_nowcast.calendar import ( + DATE_ONLY_TIMING_QUALITY, + RELEASE_CALENDAR_SCHEMA, + validate_release_calendar, +) +from macro_nowcast.census_housing_archive import ( + CENSUS_HOUSING_DIRECTORY, + CENSUS_HOUSING_SOURCE, + CENSUS_HOUSING_STARTS_SERIES_ID, + CENSUS_HOUSING_TIMING_QUALITY, + parse_census_housing_archive, +) +from macro_nowcast.census_retail_archive import ( + CENSUS_RETAIL_DIRECTORY, + CENSUS_RETAIL_LEVEL_SERIES_ID, + CENSUS_RETAIL_MOM_SERIES_ID, + CENSUS_RETAIL_SOURCE, + CENSUS_RETAIL_TIMING_QUALITY, + parse_census_retail_archive, +) +from macro_nowcast.dol_claims_archive import ( + DOL_CLAIMS_DIRECTORY, + DOL_CLAIMS_SERIES_ID, + DOL_CLAIMS_SOURCE, + DOL_CLAIMS_TIMING_QUALITY, + parse_dol_claims_archive, +) +from macro_nowcast.fed_g17_archive import ( + FED_G17_DIRECTORY, + FED_G17_INDEX_SERIES_ID, + FED_G17_MOM_SERIES_ID, + FED_G17_SOURCE, + FED_G17_TIMING_QUALITY, + parse_fed_g17_archive, +) +from macro_nowcast.schema import VintageObservation, observations_to_frame +from macro_nowcast.storage import VintageStore +from macro_nowcast.treasury_rates_archive import ( + TREASURY_10Y_SERIES_ID, + TREASURY_RATES_AVAILABILITY_RULE, + TREASURY_RATES_DIRECTORY, + TREASURY_RATES_TIMING_QUALITY, + parse_treasury_rates_archive, +) + +OFFICIAL_ARCHIVE_PROVENANCE = "official_agency_archive" +GDP_GROWTH_SERIES_ID = "BEA_REAL_GDP_GROWTH_QOQ_SAAR" +UNEMPLOYMENT_RATE_SERIES_ID = "LNS14000000" +EMPSIT_DOM_DIRECTORY = "bls-empsit-html" + +_CES_HEADER_RE = re.compile(r"([A-Z][a-z]{2})_(\d{2})") +_CPI_MEMBER_RE = re.compile(r"(?:^|/)cpi-u[_-](\d{6})\.(xls|xlsx)$", re.IGNORECASE) +_GDP_QUARTER_RE = re.compile(r"(\d{4})Q([1-4])") +_GDP_DATE_RE = re.compile(r"([A-Z][a-z]{2} \d{1,2}, \d{4})") +_MONTHS = { + name: number + for number, name in enumerate( + ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), + start=1, + ) +} +_GDP_RELEASE_TYPES = { + "Advance": "initial", + "Initial": "initial", + "Second": "second", + "Preliminary": "second", + "Third": "third", + "Final": "third", + "Updated": "revised", + "Revised": "revised", +} +_MISSING_CPI_VALUES = {"", ".", "-", "\N{EN DASH}", "\N{EM DASH}"} +_MONTH_TOKEN_RE = re.compile( + r"(Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|" + r"Aug(?:ust)?|Sept?(?:ember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\.?", + re.IGNORECASE, +) +_NUMBER_RE = re.compile(r"[pr]?(-?\d+(?:\.\d+)?)", re.IGNORECASE) +_EMPSIT_LABEL_RE = re.compile(r"([A-Za-z]+) (\d{4}) Employment Situation") +_EMPSIT_FILENAME_RE = re.compile(r"empsit_(\d{2})(\d{2})(\d{4})\.htm") + + +class ArchiveIngestionError(RuntimeError): + """Raised when audited source content cannot be mapped without guessing.""" + + +@dataclass(frozen=True, slots=True) +class OfficialArchiveData: + """Canonical official observations, target releases, and ingestion metadata.""" + + observations: pl.DataFrame + release_calendar: pl.DataFrame + metadata: Mapping[str, object] + + +def _gdp_level_target_validation( + observations: pl.DataFrame, + release_calendar: pl.DataFrame, +) -> pl.DataFrame: + """Reconcile level-derived and directly published initial GDP growth.""" + + from macro_nowcast.targets import ( + PUBLISHED_REAL_GDP_TARGET_SPEC, + REAL_GDP_TARGET_SPEC, + build_targets_for_spec, + ) + + if not observations.filter(pl.col("series_id") == BEA_NIPA_LEVEL_SERIES_ID).height: + return pl.DataFrame() + latest_as_of = release_calendar["release_timestamp"].max() + assert isinstance(latest_as_of, datetime) + level_targets = build_targets_for_spec( + observations, + release_calendar, + REAL_GDP_TARGET_SPEC, + latest_as_of=latest_as_of, + modes=("first_release",), + built_at=latest_as_of, + ).select( + "target_period", + pl.col("value").alias("level_derived_qoq_saar_percent"), + pl.col("current_level").alias("level_current"), + pl.col("prior_level").alias("level_prior"), + pl.col("current_level_realtime_start").alias("current_level_vintage_date"), + pl.col("prior_level_realtime_start").alias("prior_level_vintage_date"), + pl.col("snapshot_timestamp").alias("level_snapshot_timestamp"), + pl.col("target_release_timestamp").alias("level_target_release_timestamp"), + pl.col("release_id").alias("level_release_id"), + pl.col("target_formula").alias("level_target_formula"), + pl.col("observation_source").alias("level_observation_source"), + pl.col("calendar_source").alias("level_calendar_source"), + ) + published_targets = build_targets_for_spec( + observations, + release_calendar, + PUBLISHED_REAL_GDP_TARGET_SPEC, + latest_as_of=latest_as_of, + modes=("first_release",), + built_at=latest_as_of, + ).select( + "target_period", + pl.col("value").alias("published_qoq_saar_percent"), + pl.col("snapshot_timestamp").alias("published_snapshot_timestamp"), + pl.col("release_id").alias("published_release_id"), + pl.col("observation_source").alias("published_observation_source"), + ) + joined = ( + level_targets.join(published_targets, on="target_period", how="left", validate="1:1") + .with_columns( + ( + pl.col("level_derived_qoq_saar_percent") + - pl.col("published_qoq_saar_percent") + ).alias("difference_pp"), + ( + pl.col("current_level_vintage_date") + == pl.col("prior_level_vintage_date") + ).alias("same_snapshot_adjacent_levels"), + ) + .with_columns( + pl.col("difference_pp").abs().alias("absolute_difference_pp"), + ( + pl.col("level_derived_qoq_saar_percent").round(1) + == pl.col("published_qoq_saar_percent") + ).alias("rounds_exactly_to_published_tenth"), + (pl.col("difference_pp").abs() <= 0.06).alias( + "within_006pp_level_rounding_tolerance" + ), + ) + .sort("target_period") + ) + if joined.height != 96: + raise ArchiveIngestionError( + f"expected 96 level-derived GDP validation rows, found {joined.height}" + ) + if joined["published_qoq_saar_percent"].null_count(): + raise ArchiveIngestionError("GDP level validation has no published comparison") + if not joined["same_snapshot_adjacent_levels"].all(): + raise ArchiveIngestionError("GDP level target mixes source snapshots") + if not joined["within_006pp_level_rounding_tolerance"].all(): + raise ArchiveIngestionError("GDP level target fails published-growth reconciliation") + return joined + + +@dataclass(frozen=True, slots=True) +class CESVintageSeriesSpec: + """One seasonally adjusted CES employment series in the BLS vintage ZIP.""" + + series_id: str + agency_series_id: str + archive_member: str + industry_title: str + observation_start: date | None = None + + +class _A1TableParser(HTMLParser): + """Collect cells from the archived CPS table A-1 without third-party HTML deps.""" + + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self.in_target = False + self.table_depth = 0 + self.current_row: list[str] | None = None + self.current_cell: list[str] | None = None + self.rows: list[list[str]] = [] + + def handle_starttag( + self, + tag: str, + attrs: list[tuple[str, str | None]], + ) -> None: + attributes = dict(attrs) + if tag == "table" and attributes.get("id") == "cps_empsit_a01": + self.in_target = True + self.table_depth = 1 + return + if not self.in_target: + return + if tag == "table": + self.table_depth += 1 + elif tag == "tr": + self.current_row = [] + elif tag in {"th", "td"}: + self.current_cell = [] + + def handle_endtag(self, tag: str) -> None: + if not self.in_target: + return + if tag in {"th", "td"} and self.current_cell is not None: + assert self.current_row is not None + text = " ".join("".join(self.current_cell).split()) + self.current_row.append(text) + self.current_cell = None + elif tag == "tr" and self.current_row is not None: + if self.current_row: + self.rows.append(self.current_row) + self.current_row = None + elif tag == "table": + self.table_depth -= 1 + if self.table_depth == 0: + self.in_target = False + + def handle_data(self, data: str) -> None: + if self.in_target and self.current_cell is not None: + self.current_cell.append(data) + + +class _VisibleTextParser(HTMLParser): + """Extract visible archival text while preserving preformatted line breaks.""" + + _BLOCKS: ClassVar[frozenset[str]] = frozenset( + { + "br", + "div", + "figure", + "h1", + "h2", + "h3", + "li", + "p", + "pre", + "section", + "table", + "tr", + } + ) + + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self.parts: list[str] = [] + self.ignored_depth = 0 + + def handle_starttag( + self, + tag: str, + attrs: list[tuple[str, str | None]], + ) -> None: + del attrs + if tag in {"script", "style"}: + self.ignored_depth += 1 + elif not self.ignored_depth and tag in self._BLOCKS: + self.parts.append("\n") + + def handle_endtag(self, tag: str) -> None: + if tag in {"script", "style"} and self.ignored_depth: + self.ignored_depth -= 1 + elif not self.ignored_depth and tag in self._BLOCKS: + self.parts.append("\n") + + def handle_data(self, data: str) -> None: + if not self.ignored_depth: + self.parts.append(data) + + def text(self) -> str: + return "".join(self.parts) + + +PAYEMS_CES_SPEC = CESVintageSeriesSpec( + series_id="PAYEMS", + agency_series_id="CES0000000001", + archive_member="tri_000000_SA.csv", + industry_title="Total nonfarm", +) + +# These are genuine publication-vintage matrices from the same Employment +# Situation releases as PAYEMS. Keeping the official BLS identifiers as the +# canonical IDs avoids implying that the rows came from FRED aliases. +CES_SECTOR_PREDICTOR_SPECS = ( + CESVintageSeriesSpec( + "CES2000000001", + "CES2000000001", + "tri_200000_SA.csv", + "Construction", + date(2002, 1, 1), + ), + CESVintageSeriesSpec( + "CES3000000001", + "CES3000000001", + "tri_300000_SA.csv", + "Manufacturing", + date(2002, 1, 1), + ), + CESVintageSeriesSpec( + "CES4000000001", + "CES4000000001", + "tri_400000_SA.csv", + "Trade, transportation, and utilities", + date(2002, 1, 1), + ), + CESVintageSeriesSpec( + "CES5000000001", + "CES5000000001", + "tri_500000_SA.csv", + "Information", + date(2002, 1, 1), + ), + CESVintageSeriesSpec( + "CES5500000001", + "CES5500000001", + "tri_550000_SA.csv", + "Financial activities", + date(2002, 1, 1), + ), + CESVintageSeriesSpec( + "CES6000000001", + "CES6000000001", + "tri_600000_SA.csv", + "Professional and business services", + date(2002, 1, 1), + ), + CESVintageSeriesSpec( + "CES6500000001", + "CES6500000001", + "tri_650000_SA.csv", + "Private education and health services", + date(2002, 1, 1), + ), + CESVintageSeriesSpec( + "CES7000000001", + "CES7000000001", + "tri_700000_SA.csv", + "Leisure and hospitality", + date(2002, 1, 1), + ), +) + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as source: + while chunk := source.read(1024 * 1024): + digest.update(chunk) + return digest.hexdigest() + + +def _download_timestamp(path: Path) -> datetime: + return datetime.fromtimestamp(path.stat().st_mtime, UTC) + + +def _month_start(period: str) -> date: + try: + return date(int(period[:4]), int(period[5:7]), 1) + except (TypeError, ValueError) as exc: + raise ArchiveIngestionError(f"invalid monthly period: {period!r}") from exc + + +def _ces_observation_date(header: str) -> date: + match = _CES_HEADER_RE.fullmatch(header) + if match is None: + raise ArchiveIngestionError(f"invalid CES observation header: {header!r}") + short_year = int(match.group(2)) + year = 2000 + short_year if short_year < 30 else 1900 + short_year + return date(year, _MONTHS[match.group(1)], 1) + + +def _date_only_release_timestamp(release_date: date) -> datetime: + return datetime.combine(release_date, time.max, UTC) + + +def _rows_with_realtime_ends( + rows: Sequence[Mapping[str, object]], +) -> list[VintageObservation]: + grouped: dict[tuple[str, date], list[dict[str, object]]] = defaultdict(list) + for source_row in rows: + row = dict(source_row) + grouped[(str(row["series_id"]), row["observation_date"])].append(row) # type: ignore[index] + + result: list[VintageObservation] = [] + for values in grouped.values(): + values.sort(key=lambda row: row["realtime_start"]) # type: ignore[arg-type,return-value] + starts = [row["realtime_start"] for row in values] + if len(starts) != len(set(starts)): + raise ArchiveIngestionError( + "one observation has multiple source vintages on the same release date" + ) + for index, row in enumerate(values): + if index + 1 < len(values): + next_start = values[index + 1]["realtime_start"] + assert isinstance(next_start, date) + row["realtime_end"] = next_start - timedelta(days=1) + result.append(VintageObservation.from_mapping(row)) + return result + + +def _month_number(text: str) -> int: + normalized = text.strip().rstrip(".").lower() + candidates = ( + "january", + "february", + "march", + "april", + "may", + "june", + "july", + "august", + "september", + "october", + "november", + "december", + ) + for number, candidate in enumerate(candidates, start=1): + if candidate.startswith(normalized): + return number + raise ArchiveIngestionError(f"invalid Employment Situation month: {text!r}") + + +def _month_year(text: str) -> date: + compact = "".join(text.split()) + month = _MONTH_TOKEN_RE.match(compact) + year = re.search(r"(19|20)\d{2}", compact) + if month is None or year is None: + raise ArchiveIngestionError(f"invalid Employment Situation month header: {text!r}") + return date(int(year.group()), _month_number(month.group()), 1) + + +def _numeric_cell(text: str) -> float | None: + normalized = "".join(text.split()).replace(",", "") + if normalized in {"", "-", "--", "\N{EN DASH}", "\N{EM DASH}"}: + return None + match = _NUMBER_RE.fullmatch(normalized) + if match is None: + raise ArchiveIngestionError(f"invalid Employment Situation numeric cell: {text!r}") + return float(match.group(1)) + + +def _structured_unemployment_snapshot(document: str) -> tuple[list[tuple[date, float]], str]: + parser = _A1TableParser() + parser.feed(document) + if not parser.rows: + return [], "" + header = next( + ( + row + for row in parser.rows + if len(row) == 9 + and all( + _MONTH_TOKEN_RE.search(cell) and re.search(r"(19|20)\d{2}", cell) for cell in row + ) + ), + None, + ) + values = next( + ( + row[1:] + for row in parser.rows + if row and row[0].strip().lower() == "unemployment rate" and len(row) == 10 + ), + None, + ) + if header is None or values is None: + raise ArchiveIngestionError("structured Employment Situation table A-1 is incomplete") + dates = [_month_year(cell) for cell in header[3:]] + parsed_values = [_numeric_cell(cell) for cell in values[3:]] + return [ + (observation_date, value) + for observation_date, value in zip(dates, parsed_values, strict=True) + if value is not None + ], "html_table_a1" + + +def _preformatted_unemployment_snapshot( + document: str, +) -> tuple[list[tuple[date, float]], str]: + parser = _VisibleTextParser() + parser.feed(document) + text = parser.text() + start_match = re.search(r"Table\s+A-1\.\s+Employment status", text, re.IGNORECASE) + if start_match is None: + raise ArchiveIngestionError("Employment Situation DOM has no table A-1") + following = text[start_match.start() :] + stop_match = re.search(r"\n\s*Table\s+A-2\.", following, re.IGNORECASE) + table = following[: stop_match.start()] if stop_match else following + lines = table.splitlines() + stub_index = next( + index for index, line in enumerate(lines) if "Employment status, sex, and age" in line + ) + header_dates: list[date] | None = None + for index in range(stub_index + 1, min(stub_index + 20, len(lines) - 1)): + months = _MONTH_TOKEN_RE.findall(lines[index]) + years = re.findall(r"(?:19|20)\d{2}", lines[index + 1]) + if len(months) == 9 and len(years) == 9: + header_dates = [ + date(int(year), _month_number(month), 1) + for month, year in zip(months, years, strict=True) + ] + break + if header_dates is None: + raise ArchiveIngestionError("preformatted table A-1 has no nine-column month header") + unemployment_line = next( + (line for line in lines if re.match(r"^\s*Unemployment rate\.{2,}", line, re.IGNORECASE)), + None, + ) + if unemployment_line is None: + raise ArchiveIngestionError("preformatted table A-1 has no total unemployment-rate row") + values = [float(value) for value in _NUMBER_RE.findall(unemployment_line)] + if len(values) != 9: + raise ArchiveIngestionError( + f"preformatted table A-1 expected nine unemployment rates; found {len(values)}" + ) + return list(zip(header_dates[3:], values[3:], strict=True)), "preformatted_table_a1" + + +def parse_empsit_unemployment_rate_snapshot( + path: str | Path, + *, + current_period: date, + release_date: date, + release_clock: BLSReleaseClock | None = None, + download_timestamp: datetime | None = None, +) -> list[dict[str, object]]: + """Parse the published seasonally adjusted U-3 history visible in table A-1.""" + + source_path = Path(path) + document = source_path.read_text(encoding="utf-8") + if not document.rstrip().endswith(""): + raise ArchiveIngestionError( + f"incomplete Employment Situation DOM export: {source_path.name}" + ) + snapshot, extraction_basis = _structured_unemployment_snapshot(document) + if not snapshot: + snapshot, extraction_basis = _preformatted_unemployment_snapshot(document) + if not snapshot or snapshot[-1][0] != current_period: + found = snapshot[-1][0].isoformat() if snapshot else "none" + raise ArchiveIngestionError( + f"Employment Situation {release_date} current period mismatch: " + f"expected {current_period}, found {found}" + ) + acquired_at = download_timestamp or _download_timestamp(source_path) + source_url = f"https://www.bls.gov/news.release/archives/{source_path.name}" + source_hash = _sha256(source_path) + if release_clock is not None and release_clock.release_date != release_date: + raise ArchiveIngestionError("Employment Situation release clock date mismatch") + release_timestamp = ( + release_clock.release_timestamp if release_clock is not None else None + ) + timing_quality = ( + BLS_EMBARGO_CLOCK_TIMING_QUALITY + if release_clock is not None + else DATE_ONLY_TIMING_QUALITY + ) + return [ + { + "series_id": UNEMPLOYMENT_RATE_SERIES_ID, + "observation_date": observation_date, + "realtime_start": release_date, + "availability_date": release_date, + "release_timestamp": release_timestamp, + "availability_timestamp": release_timestamp, + "value": value, + "units": "percent", + "frequency": "monthly", + "seasonal_adjustment": "seasonally_adjusted", + "transformation": "level", + "download_timestamp": acquired_at, + "source": "BLS_EMPLOYMENT_SITUATION_DOM_ARCHIVE", + "provenance_label": OFFICIAL_ARCHIVE_PROVENANCE, + "source_metadata": { + "agency_series_id": UNEMPLOYMENT_RATE_SERIES_ID, + "archive_file": source_path.name, + "archive_sha256": source_hash, + "source_url": source_url, + "snapshot_current_period": current_period.isoformat(), + "extraction_basis": extraction_basis, + "dom_export_kind": "browser_rendered_complete_dom", + "timing_quality": timing_quality, + "printed_release_timezone": ( + release_clock.printed_timezone if release_clock is not None else None + ), + }, + } + for observation_date, value in snapshot + ] + + +def parse_empsit_unemployment_rate_archive( + directory: str | Path, + release_mapping: Sequence[Mapping[str, object]], + *, + release_clocks: Mapping[date, BLSReleaseClock] | None = None, +) -> list[VintageObservation]: + """Parse all acquired Employment Situation DOM exports as genuine vintages.""" + + source_directory = Path(directory) + index_path = source_directory.parent / "empsit-release-index.json" + official_periods: dict[date, date] = {} + if index_path.exists(): + document = json.loads(index_path.read_text(encoding="utf-8")) + for event in document.get("release_events", []): + label = event.get("observation_label") + if not isinstance(label, str): + continue + match = _EMPSIT_LABEL_RE.fullmatch(label) + if match is None: + continue + official_periods[date.fromisoformat(str(event["release_date"]))] = date( + int(match.group(2)), + _month_number(match.group(1)), + 1, + ) + raw_rows: list[dict[str, object]] = [] + parsed_files = 0 + mapped_periods: dict[date, date] = {} + for release in release_mapping: + release_date = date.fromisoformat(str(release["release_date"])) + mapped_periods.setdefault( + release_date, + _month_start(str(release["vintage_period"])), + ) + for source_path in sorted(source_directory.glob("empsit_*.htm")): + match = _EMPSIT_FILENAME_RE.fullmatch(source_path.name) + if match is None: + raise ArchiveIngestionError( + f"unexpected Employment Situation archive filename: {source_path.name}" + ) + release_date = date(int(match.group(3)), int(match.group(1)), int(match.group(2))) + current_period = official_periods.get(release_date, mapped_periods.get(release_date)) + if current_period is None: + raise ArchiveIngestionError( + f"Employment Situation archive has no official period mapping: {release_date}" + ) + raw_rows.extend( + parse_empsit_unemployment_rate_snapshot( + source_path, + current_period=current_period, + release_date=release_date, + release_clock=(release_clocks or {}).get(release_date), + ) + ) + parsed_files += 1 + if parsed_files == 0: + raise ArchiveIngestionError("no Employment Situation DOM exports were parsed") + return _rows_with_realtime_ends(raw_rows) + + +def parse_ces_series_vintage_archive( + path: str | Path, + release_mapping: Sequence[Mapping[str, object]], + *, + series: CESVintageSeriesSpec, + release_clocks: Mapping[date, BLSReleaseClock] | None = None, + download_timestamp: datetime | None = None, +) -> list[VintageObservation]: + """Expand one audited BLS CES vintage matrix into canonical observations.""" + + source_path = Path(path) + mapping = {str(row["vintage_period"]): row for row in release_mapping} + acquired_at = download_timestamp or _download_timestamp(source_path) + archive_hash = _sha256(source_path) + raw_rows: list[dict[str, object]] = [] + with ZipFile(source_path) as archive: + if series.archive_member not in archive.namelist(): + raise ArchiveIngestionError( + f"CES archive is missing {series.archive_member} for {series.agency_series_id}" + ) + binary = archive.open(series.archive_member) + reader = csv.reader(io.TextIOWrapper(binary, encoding="utf-8-sig", newline="")) + header = next(reader) + observation_dates = [_ces_observation_date(value) for value in header[2:]] + for source_row in reader: + vintage_period = f"{int(source_row[0]):04d}-{int(source_row[1]):02d}" + release = mapping.get(vintage_period) + if release is None: + raise ArchiveIngestionError( + f"CES vintage has no audited release mapping: {vintage_period}" + ) + if ( + release.get("mapping_basis") + == "official_november_release_includes_october_ces_initial" + ): + continue + release_date = date.fromisoformat(str(release["release_date"])) + release_clock = (release_clocks or {}).get(release_date) + if release_clock is not None and release_clock.release_date != release_date: + raise ArchiveIngestionError("CES release clock date mismatch") + release_timestamp = ( + release_clock.release_timestamp if release_clock is not None else None + ) + timing_quality = ( + BLS_EMBARGO_CLOCK_TIMING_QUALITY + if release_clock is not None + else DATE_ONLY_TIMING_QUALITY + ) + latest_allowed = _month_start(vintage_period) + for observation_date, raw_value in zip( + observation_dates, + source_row[2:], + strict=True, + ): + if ( + series.observation_start is not None + and observation_date < series.observation_start + ): + continue + if raw_value in {"", ".", "-1"}: + continue + if observation_date > latest_allowed: + raise ArchiveIngestionError( + f"CES {vintage_period} contains future period {observation_date}" + ) + value = float(raw_value) + if value < 0: + raise ArchiveIngestionError("CES employment levels cannot be negative") + raw_rows.append( + { + "series_id": series.series_id, + "observation_date": observation_date, + "realtime_start": release_date, + "availability_date": release_date, + "release_timestamp": release_timestamp, + "availability_timestamp": release_timestamp, + "value": value, + "units": "thousands_of_persons", + "frequency": "monthly", + "seasonal_adjustment": "seasonally_adjusted", + "transformation": "level", + "download_timestamp": acquired_at, + "source": "BLS_CES_VINTAGE_ARCHIVE", + "provenance_label": OFFICIAL_ARCHIVE_PROVENANCE, + "source_metadata": { + "agency_series_id": series.agency_series_id, + "archive_member": series.archive_member, + "archive_sha256": archive_hash, + "industry_title": series.industry_title, + "observation_start_filter": ( + series.observation_start.isoformat() + if series.observation_start is not None + else None + ), + "vintage_period": vintage_period, + "release_mapping_basis": release["mapping_basis"], + "timing_quality": timing_quality, + "printed_release_timezone": ( + release_clock.printed_timezone + if release_clock is not None + else None + ), + }, + } + ) + return _rows_with_realtime_ends(raw_rows) + + +def parse_ces_vintage_archive( + path: str | Path, + release_mapping: Sequence[Mapping[str, object]], + *, + release_clocks: Mapping[date, BLSReleaseClock] | None = None, + download_timestamp: datetime | None = None, +) -> list[VintageObservation]: + """Backward-compatible total-nonfarm CES vintage parser.""" + + return parse_ces_series_vintage_archive( + path, + release_mapping, + series=PAYEMS_CES_SPEC, + release_clocks=release_clocks, + download_timestamp=download_timestamp, + ) + + +def parse_ces_sector_vintage_archives( + path: str | Path, + release_mapping: Sequence[Mapping[str, object]], + *, + series: Sequence[CESVintageSeriesSpec] = CES_SECTOR_PREDICTOR_SPECS, + release_clocks: Mapping[date, BLSReleaseClock] | None = None, + download_timestamp: datetime | None = None, +) -> list[VintageObservation]: + """Parse the declared set of BLS sector-employment vintage matrices.""" + + parsed: list[VintageObservation] = [] + for definition in series: + parsed.extend( + parse_ces_series_vintage_archive( + path, + release_mapping, + series=definition, + release_clocks=release_clocks, + download_timestamp=download_timestamp, + ) + ) + return parsed + + +def _cpi_period(value: object) -> str | None: + normalized = re.sub(r"[.\n\r]+", " ", str(value)).strip() + match = re.search(r"([A-Za-z]{3,9})\s+(\d{4})", normalized) + if match is None: + return None + month = _MONTHS.get(match.group(1)[:3].title()) + if month is None: + return None + return f"{int(match.group(2)):04d}-{month:02d}" + + +def parse_cpi_snapshot( + payload: bytes, + *, + snapshot_period: str, + release_date: date, + download_timestamp: datetime, + source_file: str, + source_sha256: str, + release_clock: BLSReleaseClock | None = None, + release_clock_metadata: Mapping[str, object] | None = None, +) -> list[dict[str, object]]: + """Read the seasonally adjusted core-CPI level row from one snapshot workbook.""" + + rows = read_xlsx_rows(payload, "US") + item_matches = [ + (row_number, column) + for row_number, values in rows.items() + for column, value in values.items() + if str(value).strip() == "All items less food and energy" + ] + if len(item_matches) != 1: + raise ArchiveIngestionError( + f"{source_file} requires exactly one core-CPI row; found {len(item_matches)}" + ) + item_row_number, item_label_column = item_matches[0] + item_row = rows[item_row_number] + category_candidates = [ + (row_number, values) + for row_number, values in rows.items() + if row_number < item_row_number + and any(str(value).strip() == "Seasonally adjusted indexes" for value in values.values()) + ] + if not category_candidates: + raise ArchiveIngestionError(f"{source_file} has no seasonally adjusted index header") + category_row_number, category_row = max(category_candidates, key=lambda item: item[0]) + explicit_index_columns = { + column + for column, value in category_row.items() + if str(value).strip() == "Seasonally adjusted indexes" + } + index_start = min(explicit_index_columns) + following_heading_columns = [ + column + for column, value in category_row.items() + if column > index_start + and str(value).strip() + and str(value).strip() != "Seasonally adjusted indexes" + ] + index_stop = min(following_heading_columns, default=max(item_row) + 1) + index_columns = set(range(index_start, index_stop)) + period_candidates: list[tuple[int, dict[int, str]]] = [] + for row_number in range(category_row_number + 1, item_row_number): + parsed = { + column: period + for column in index_columns + if (period := _cpi_period(rows.get(row_number, {}).get(column))) is not None + } + if parsed: + period_candidates.append((row_number, parsed)) + if not period_candidates: + raise ArchiveIngestionError(f"{source_file} has no CPI index-period header") + _, periods_by_column = max(period_candidates, key=lambda item: len(item[1])) + normalized_snapshot = f"{snapshot_period[:4]}-{snapshot_period[4:]}" + if normalized_snapshot not in periods_by_column.values(): + raise ArchiveIngestionError( + f"{source_file} does not contain its snapshot period {normalized_snapshot}" + ) + + if release_clock is not None and release_clock.release_date != release_date: + raise ArchiveIngestionError("CPI release clock date mismatch") + release_timestamp = ( + release_clock.release_timestamp if release_clock is not None else None + ) + timing_quality = ( + BLS_EMBARGO_CLOCK_TIMING_QUALITY + if release_clock is not None + else DATE_ONLY_TIMING_QUALITY + ) + parsed_rows: list[dict[str, object]] = [] + for column, period in sorted(periods_by_column.items(), key=lambda item: item[1]): + if period > normalized_snapshot: + raise ArchiveIngestionError(f"{source_file} contains future CPI period {period}") + raw_value = item_row.get(column) + if raw_value is None or str(raw_value).strip() in _MISSING_CPI_VALUES: + continue + parsed_rows.append( + { + "series_id": "CPILFESL", + "observation_date": _month_start(period), + "realtime_start": release_date, + "availability_date": release_date, + "release_timestamp": release_timestamp, + "availability_timestamp": release_timestamp, + "value": float(raw_value), + "units": "index_1982_1984_100", + "frequency": "monthly", + "seasonal_adjustment": "seasonally_adjusted", + "transformation": "level", + "download_timestamp": download_timestamp, + "source": "BLS_CPI_SUPPLEMENTAL_ARCHIVE", + "provenance_label": OFFICIAL_ARCHIVE_PROVENANCE, + "source_metadata": { + "agency_series_id": "CUSR0000SA0L1E", + "source_file": source_file, + "source_sha256": source_sha256, + "snapshot_period": normalized_snapshot, + "sheet": "US", + "row": item_row_number, + "item_label_column": item_label_column, + "column": column, + "timing_quality": timing_quality, + "printed_release_timezone": ( + release_clock.printed_timezone + if release_clock is not None + else None + ), + "release_clock_evidence_format": ( + release_clock_metadata.get("evidence_format") + if release_clock_metadata is not None + else None + ), + "release_clock_header_sha256": ( + release_clock_metadata.get("header_sha256") + if release_clock_metadata is not None + else None + ), + }, + } + ) + return parsed_rows + + +def _cpi_members(archive: ZipFile, year: int) -> dict[str, str]: + result: dict[str, str] = {} + for name in archive.namelist(): + match = _CPI_MEMBER_RE.search(name) + if match is not None and match.group(1).startswith(str(year)): + result[match.group(1)] = name + if len(result) != 12: + raise ArchiveIngestionError(f"CPI {year} requires 12 monthly workbooks") + return result + + +def parse_cpi_archives( + raw_dir: str | Path, + release_mapping: Sequence[Mapping[str, object]], + *, + release_clock_archive: BLSCPIClockArchive | None = None, +) -> list[VintageObservation]: + """Parse every audited CPI supplemental snapshot, including legacy XLS files.""" + + directory = Path(raw_dir) + releases = { + str(row["snapshot_period"]).replace("-", ""): date.fromisoformat(str(row["release_date"])) + for row in release_mapping + } + raw_rows: list[dict[str, object]] = [] + for year in CPI_ARCHIVE_YEARS: + archive_path = directory / f"cpi-supplemental-{year}.zip" + archive_hash = _sha256(archive_path) + acquired_at = _download_timestamp(archive_path) + with ZipFile(archive_path) as archive: + members = _cpi_members(archive, year) + legacy = { + period: archive.read(name) + for period, name in members.items() + if name.lower().endswith(".xls") + } + converted_legacy, _ = convert_legacy_xls_to_xlsx(legacy) + for period, name in sorted(members.items()): + payload = ( + converted_legacy[period] + if name.lower().endswith(".xls") + else archive.read(name) + ) + raw_rows.extend( + parse_cpi_snapshot( + payload, + snapshot_period=period, + release_date=releases[period], + download_timestamp=acquired_at, + source_file=name, + source_sha256=archive_hash, + release_clock=( + release_clock_archive.clocks.get(releases[period]) + if release_clock_archive is not None + else None + ), + release_clock_metadata=( + release_clock_archive.event_metadata.get(releases[period]) + if release_clock_archive is not None + else None + ), + ) + ) + current = directory / "cpi-current" + for period in CPI_CURRENT_PERIODS: + path = current / f"cpi-u-{period}.xlsx" + raw_rows.extend( + parse_cpi_snapshot( + path.read_bytes(), + snapshot_period=period, + release_date=releases[period], + download_timestamp=_download_timestamp(path), + source_file=path.name, + source_sha256=_sha256(path), + release_clock=( + release_clock_archive.clocks.get(releases[period]) + if release_clock_archive is not None + else None + ), + release_clock_metadata=( + release_clock_archive.event_metadata.get(releases[period]) + if release_clock_archive is not None + else None + ), + ) + ) + return _rows_with_realtime_ends(raw_rows) + + +def _gdp_release_date(value: object) -> date: + match = _GDP_DATE_RE.search(str(value)) + if match is None: + raise ArchiveIngestionError(f"GDP release date text is invalid: {value!r}") + return datetime.strptime(match.group(1), "%b %d, %Y").date() + + +def parse_gdp_vintage_history( + path: str | Path, + *, + release_clocks: Mapping[date, BEAReleaseClock] | None = None, + release_clock_metadata: Mapping[date, Mapping[str, object]] | None = None, + download_timestamp: datetime | None = None, +) -> list[VintageObservation]: + """Parse BEA's already-annualized published real-GDP growth vintages.""" + + source_path = Path(path) + acquired_at = download_timestamp or _download_timestamp(source_path) + source_hash = _sha256(source_path) + rows = read_xlsx_rows(source_path, "Vintage History") + quarter_rows: list[tuple[int, str]] = [] + for row_number, values in rows.items(): + for value in values.values(): + if _GDP_QUARTER_RE.fullmatch(str(value).strip()): + quarter_rows.append((row_number, str(value).strip())) + break + quarter_rows.sort() + raw_rows: list[dict[str, object]] = [] + for index, (start, quarter) in enumerate(quarter_rows): + stop = quarter_rows[index + 1][0] if index + 1 < len(quarter_rows) else max(rows) + 1 + match = _GDP_QUARTER_RE.fullmatch(quarter) + assert match is not None + observation_date = date(int(match.group(1)), (int(match.group(2)) - 1) * 3 + 1, 1) + for row_number in range(start + 1, stop): + values = rows.get(row_number, {}) + source_release_type = str(values.get(2, "")).strip() + release_type = _GDP_RELEASE_TYPES.get(source_release_type) + if release_type is None: + continue + release_text = str(values.get(7, "")).strip() + release_date = _gdp_release_date(release_text) + release_clock = (release_clocks or {}).get(release_date) + clock_metadata = (release_clock_metadata or {}).get(release_date) + release_timestamp = ( + release_clock.release_timestamp if release_clock is not None else None + ) + raw_rows.append( + { + "series_id": GDP_GROWTH_SERIES_ID, + "observation_date": observation_date, + "realtime_start": release_date, + "availability_date": release_date, + "release_timestamp": release_timestamp, + "availability_timestamp": release_timestamp, + "value": float(values[5]), + "units": "percent_change_qoq_saar", + "frequency": "quarterly", + "seasonal_adjustment": "seasonally_adjusted_annual_rate", + "transformation": "already_transformed", + "download_timestamp": acquired_at, + "source": "BEA_GDP_GDI_VINTAGE_HISTORY", + "provenance_label": OFFICIAL_ARCHIVE_PROVENANCE, + "source_metadata": { + "agency_series_id": "A191RL", + "source_file": source_path.name, + "source_sha256": source_hash, + "source_release_type": source_release_type, + "release_type": release_type, + "release_date_text": release_text, + "timing_quality": ( + BEA_GDP_CLOCK_TIMING_QUALITY + if release_clock is not None + else DATE_ONLY_TIMING_QUALITY + ), + "printed_release_timezone": ( + release_clock.printed_timezone + if release_clock is not None + else None + ), + "release_clock_evidence_format": ( + clock_metadata.get("evidence_format") + if clock_metadata is not None + else None + ), + "release_clock_header_sha256": ( + clock_metadata.get("header_sha256") + if clock_metadata is not None + else None + ), + "archive_index_published_date": ( + clock_metadata.get("archive_index_published_date") + if clock_metadata is not None + else None + ), + "source_date_discrepancy": ( + clock_metadata.get("source_date_discrepancy") + if clock_metadata is not None + else None + ), + }, + } + ) + return _rows_with_realtime_ends(raw_rows) + + +def _release_calendar( + ces_mapping: Sequence[Mapping[str, object]], + cpi_mapping: Sequence[Mapping[str, object]], + gdp_observations: Sequence[VintageObservation], + dol_claims_observations: Sequence[VintageObservation] = (), + fed_g17_observations: Sequence[VintageObservation] = (), + census_retail_observations: Sequence[VintageObservation] = (), + census_housing_observations: Sequence[VintageObservation] = (), + gdp_level_observations: Sequence[VintageObservation] = (), + empsit_release_clocks: Mapping[date, BLSReleaseClock] | None = None, + cpi_release_clocks: Mapping[date, BLSReleaseClock] | None = None, + gdp_release_clocks: Mapping[date, BEAReleaseClock] | None = None, +) -> pl.DataFrame: + rows: list[dict[str, object]] = [] + for mapping in ces_mapping: + period = str(mapping["vintage_period"]) + release_date = date.fromisoformat(str(mapping["release_date"])) + release_clock = (empsit_release_clocks or {}).get(release_date) + rows.append( + { + "release_id": f"bls-payems-{period}-initial", + "series_id": "PAYEMS", + "observation_date": _month_start(period), + "release_timestamp": ( + release_clock.release_timestamp + if release_clock is not None + else _date_only_release_timestamp(release_date) + ), + "release_type": "initial", + "timing_quality": ( + BLS_EMBARGO_CLOCK_TIMING_QUALITY + if release_clock is not None + else DATE_ONLY_TIMING_QUALITY + ), + "source": "BLS_EMPLOYMENT_SITUATION_ARCHIVE", + "provenance_label": OFFICIAL_ARCHIVE_PROVENANCE, + } + ) + for mapping in cpi_mapping: + period = str(mapping["snapshot_period"]) + release_date = date.fromisoformat(str(mapping["release_date"])) + release_clock = (cpi_release_clocks or {}).get(release_date) + rows.append( + { + "release_id": f"bls-cpilfesl-{period}-initial", + "series_id": "CPILFESL", + "observation_date": _month_start(period), + "release_timestamp": ( + release_clock.release_timestamp + if release_clock is not None + else _date_only_release_timestamp(release_date) + ), + "release_type": "initial", + "timing_quality": ( + BLS_EMBARGO_CLOCK_TIMING_QUALITY + if release_clock is not None + else DATE_ONLY_TIMING_QUALITY + ), + "source": "BLS_CPI_NEWS_RELEASE_ARCHIVE", + "provenance_label": OFFICIAL_ARCHIVE_PROVENANCE, + } + ) + for observation in gdp_observations: + if observation.source_metadata.get("release_type") != "initial": + continue + release_clock = (gdp_release_clocks or {}).get(observation.availability_date) + quarter = (observation.observation_date.month + 2) // 3 + rows.append( + { + "release_id": ( + f"bea-real-gdp-growth-{observation.observation_date.year}-Q{quarter}-initial" + ), + "series_id": GDP_GROWTH_SERIES_ID, + "observation_date": observation.observation_date, + "release_timestamp": ( + release_clock.release_timestamp + if release_clock is not None + else _date_only_release_timestamp(observation.availability_date) + ), + "release_type": "initial", + "timing_quality": ( + BEA_GDP_CLOCK_TIMING_QUALITY + if release_clock is not None + else DATE_ONLY_TIMING_QUALITY + ), + "source": "BEA_GDP_GDI_VINTAGE_HISTORY", + "provenance_label": OFFICIAL_ARCHIVE_PROVENANCE, + } + ) + for observation in dol_claims_observations: + if observation.source_metadata.get("vintage_type") != "advance": + continue + if observation.release_timestamp is None: + raise ArchiveIngestionError("DOL claims advance row requires a release timestamp") + rows.append( + { + "release_id": f"dol-ui-claims-{observation.observation_date.isoformat()}-advance", + "series_id": DOL_CLAIMS_SERIES_ID, + "observation_date": observation.observation_date, + "release_timestamp": observation.release_timestamp, + "release_type": "initial", + "timing_quality": DOL_CLAIMS_TIMING_QUALITY, + "source": DOL_CLAIMS_SOURCE, + "provenance_label": OFFICIAL_ARCHIVE_PROVENANCE, + } + ) + g17_releases: dict[date, list[VintageObservation]] = defaultdict(list) + for observation in fed_g17_observations: + if observation.series_id == FED_G17_INDEX_SERIES_ID: + g17_releases[observation.realtime_start].append(observation) + for release_date, release_observations in sorted(g17_releases.items()): + representative = max(release_observations, key=lambda row: row.observation_date) + if representative.release_timestamp is None: + raise ArchiveIngestionError("Fed G.17 row requires a release timestamp") + source_release_type = str(representative.source_metadata.get("release_type")) + rows.append( + { + "release_id": f"fed-g17-{release_date.isoformat()}-{source_release_type}", + "series_id": FED_G17_MOM_SERIES_ID, + "observation_date": representative.observation_date, + "release_timestamp": representative.release_timestamp, + "release_type": source_release_type, + "timing_quality": FED_G17_TIMING_QUALITY, + "source": FED_G17_SOURCE, + "provenance_label": OFFICIAL_ARCHIVE_PROVENANCE, + } + ) + for observation in census_retail_observations: + if observation.series_id != CENSUS_RETAIL_MOM_SERIES_ID: + continue + if observation.release_timestamp is None: + raise ArchiveIngestionError("Census MARTS row requires a release timestamp") + rows.append( + { + "release_id": ( + f"census-marts-{observation.observation_date.isoformat()}-advance" + ), + "series_id": CENSUS_RETAIL_MOM_SERIES_ID, + "observation_date": observation.observation_date, + "release_timestamp": observation.release_timestamp, + "release_type": "initial", + "timing_quality": CENSUS_RETAIL_TIMING_QUALITY, + "source": CENSUS_RETAIL_SOURCE, + "provenance_label": OFFICIAL_ARCHIVE_PROVENANCE, + } + ) + for observation in census_housing_observations: + if observation.series_id != CENSUS_HOUSING_STARTS_SERIES_ID: + continue + if observation.release_timestamp is None: + raise ArchiveIngestionError("Census NRC row requires a release timestamp") + rows.append( + { + "release_id": ( + f"census-nrc-{observation.observation_date.isoformat()}-preliminary" + ), + "series_id": CENSUS_HOUSING_STARTS_SERIES_ID, + "observation_date": observation.observation_date, + "release_timestamp": observation.release_timestamp, + "release_type": "initial", + "timing_quality": CENSUS_HOUSING_TIMING_QUALITY, + "source": CENSUS_HOUSING_SOURCE, + "provenance_label": OFFICIAL_ARCHIVE_PROVENANCE, + } + ) + for observation in gdp_level_observations: + target_quarter = observation.source_metadata.get("target_quarter") + if not isinstance(target_quarter, str): + continue + quarter = (observation.observation_date.month - 1) // 3 + 1 + observation_quarter = f"{observation.observation_date.year:04d}Q{quarter}" + if observation_quarter != target_quarter: + continue + if observation.release_timestamp is None: + raise ArchiveIngestionError("BEA NIPA level target row requires exact timing") + rows.append( + { + "release_id": f"bea-real-gdp-level-{target_quarter}-initial", + "series_id": BEA_NIPA_LEVEL_SERIES_ID, + "observation_date": observation.observation_date, + "release_timestamp": observation.release_timestamp, + "release_type": "initial", + "timing_quality": BEA_GDP_CLOCK_TIMING_QUALITY, + "source": BEA_NIPA_LEVEL_SOURCE, + "provenance_label": OFFICIAL_ARCHIVE_PROVENANCE, + } + ) + return validate_release_calendar( + pl.from_dicts(rows, schema=RELEASE_CALENDAR_SCHEMA, strict=True) + ) + + +def _count_release_rows_with_clock( + release_mapping: Sequence[Mapping[str, object]], + clocks: Mapping[date, object], +) -> int: + """Count target rows, not unique dates, backed by exact clock evidence.""" + + return sum( + date.fromisoformat(str(row["release_date"])) in clocks + for row in release_mapping + ) + + +def build_official_archive_data(raw_dir: str | Path) -> OfficialArchiveData: + """Audit and parse all acquired official target archives without network access.""" + + directory = Path(raw_dir).resolve() + audit = audit_agency_vintages(directory) + if audit["status"] != "verified_with_limitations": + raise ArchiveAuditError("official archive audit must pass before ingestion") + artifacts = audit["artifacts"] + ces_artifact = artifacts["ces"] # type: ignore[index] + cpi_artifact = artifacts["cpi"] # type: ignore[index] + ces_mapping = ces_artifact["release_mapping"]["release_date_mapping"] + cpi_mapping = cpi_artifact["release_mapping"]["release_date_mapping"] + + empsit_directory = directory / EMPSIT_DOM_DIRECTORY + empsit_dom_clock_archive = ( + parse_empsit_release_clock_archive(empsit_directory) + if empsit_directory.exists() + else None + ) + empsit_text_clock_directory = directory / BLS_EMPSIT_CLOCK_DIRECTORY + empsit_text_clock_archive = ( + parse_empsit_text_clock_archive( + empsit_text_clock_directory, + release_index_path=directory / "empsit-release-index.json", + ) + if empsit_text_clock_directory.exists() + else None + ) + empsit_release_clocks = merge_empsit_release_clocks( + ( + empsit_dom_clock_archive.clocks + if empsit_dom_clock_archive is not None + else {} + ), + ( + empsit_text_clock_archive.clocks + if empsit_text_clock_archive is not None + else {} + ), + ) + + ces = parse_ces_vintage_archive( + directory / CES_FILENAME, + ces_mapping, + release_clocks=empsit_release_clocks, + ) + ces_sectors = parse_ces_sector_vintage_archives( + directory / CES_FILENAME, + ces_mapping, + release_clocks=empsit_release_clocks, + ) + unemployment_rate = ( + parse_empsit_unemployment_rate_archive( + empsit_directory, + ces_mapping, + release_clocks=empsit_release_clocks, + ) + if empsit_directory.exists() + else [] + ) + cpi_clock_directory = directory / BLS_CPI_CLOCK_DIRECTORY + cpi_clock_archive = ( + parse_bls_cpi_clock_archive( + cpi_clock_directory / BLS_CPI_CLOCK_FILENAME, + release_index_path=directory / CPI_RELEASE_INDEX_FILENAME, + ) + if cpi_clock_directory.exists() + else None + ) + cpi = parse_cpi_archives( + directory, + cpi_mapping, + release_clock_archive=cpi_clock_archive, + ) + gdp_clock_directory = directory / BEA_GDP_CLOCK_DIRECTORY + gdp_clock_archive: BEAGDPClockArchive | None = ( + parse_bea_gdp_clock_archive( + gdp_clock_directory / BEA_GDP_CLOCK_FILENAME, + ) + if gdp_clock_directory.exists() + else None + ) + gdp = parse_gdp_vintage_history( + directory / GDP_VINTAGE_FILENAME, + release_clocks=( + gdp_clock_archive.clocks if gdp_clock_archive is not None else {} + ), + release_clock_metadata=( + gdp_clock_archive.event_metadata if gdp_clock_archive is not None else {} + ), + ) + nipa_level_directory = directory / BEA_NIPA_LEVEL_DIRECTORY + if nipa_level_directory.exists(): + if gdp_clock_archive is None: + raise ArchiveIngestionError( + "BEA NIPA level ingestion requires verified GDP clock evidence" + ) + _, gdp_levels = parse_bea_nipa_level_archive( + nipa_level_directory, + clock_evidence_path=gdp_clock_directory / BEA_GDP_CLOCK_FILENAME, + ) + else: + gdp_levels = [] + dol_claims_directory = directory / DOL_CLAIMS_DIRECTORY + dol_claims = ( + parse_dol_claims_archive(dol_claims_directory) + if dol_claims_directory.exists() + else [] + ) + fed_g17_directory = directory / FED_G17_DIRECTORY + fed_g17 = parse_fed_g17_archive(fed_g17_directory) if fed_g17_directory.exists() else [] + treasury_rates_directory = directory / TREASURY_RATES_DIRECTORY + treasury_rates = ( + parse_treasury_rates_archive(treasury_rates_directory) + if treasury_rates_directory.exists() + else [] + ) + census_retail_directory = directory / CENSUS_RETAIL_DIRECTORY + census_retail = ( + parse_census_retail_archive(census_retail_directory) + if census_retail_directory.exists() + else [] + ) + census_housing_directory = directory / CENSUS_HOUSING_DIRECTORY + census_housing = ( + parse_census_housing_archive(census_housing_directory) + if census_housing_directory.exists() + else [] + ) + observations = observations_to_frame( + [ + *ces, + *ces_sectors, + *unemployment_rate, + *cpi, + *gdp, + *gdp_levels, + *dol_claims, + *fed_g17, + *treasury_rates, + *census_retail, + *census_housing, + ] + ) + calendar = _release_calendar( + ces_mapping, + cpi_mapping, + gdp, + dol_claims, + fed_g17, + census_retail, + census_housing, + gdp_levels, + empsit_release_clocks=empsit_release_clocks, + cpi_release_clocks=( + cpi_clock_archive.clocks if cpi_clock_archive is not None else {} + ), + gdp_release_clocks=( + gdp_clock_archive.clocks if gdp_clock_archive is not None else {} + ), + ) + metadata: dict[str, object] = { + "provenance_label": OFFICIAL_ARCHIVE_PROVENANCE, + "audit_status": audit["status"], + "historical_ingestion_ready": True, + "intraday_timing_verified": False, + "target_intraday_timing_partially_verified": bool( + empsit_release_clocks or cpi_clock_archive or gdp_clock_archive + ), + "employment_situation_exact_release_clock_count": len( + empsit_release_clocks + ), + "employment_situation_html_exact_release_clock_count": ( + len(empsit_dom_clock_archive.clocks) + if empsit_dom_clock_archive is not None + else 0 + ), + "employment_situation_txt_exact_release_clock_count": ( + len(empsit_text_clock_archive.clocks) + if empsit_text_clock_archive is not None + else 0 + ), + "employment_situation_txt_clock_evidence_sha256": ( + empsit_text_clock_archive.evidence_sha256 + if empsit_text_clock_archive is not None + else None + ), + "payems_target_release_clock_count": _count_release_rows_with_clock( + ces_mapping, + empsit_release_clocks, + ), + "employment_situation_date_only_clock_exclusions": ( + { + release_date.isoformat(): reason + for release_date, reason in empsit_dom_clock_archive.exclusions.items() + } + if empsit_dom_clock_archive is not None + else {} + ), + "cpi_exact_release_clock_count": ( + len(cpi_clock_archive.clocks) if cpi_clock_archive is not None else 0 + ), + "cpi_target_release_clock_count": ( + len( + { + date.fromisoformat(str(row["release_date"])) + for row in cpi_mapping + if cpi_clock_archive is not None + and date.fromisoformat(str(row["release_date"])) + in cpi_clock_archive.clocks + } + ) + if cpi_clock_archive is not None + else 0 + ), + "cpi_release_clock_evidence_sha256": ( + cpi_clock_archive.evidence_sha256 + if cpi_clock_archive is not None + else None + ), + "gdp_exact_release_clock_count": ( + len(gdp_clock_archive.clocks) if gdp_clock_archive is not None else 0 + ), + "gdp_target_release_clock_count": ( + len( + { + row.realtime_start + for row in gdp + if row.source_metadata.get("release_type") == "initial" + and gdp_clock_archive is not None + and row.realtime_start in gdp_clock_archive.clocks + } + ) + if gdp_clock_archive is not None + else 0 + ), + "gdp_release_clock_evidence_sha256": ( + gdp_clock_archive.evidence_sha256 + if gdp_clock_archive is not None + else None + ), + "gdp_release_clock_source_date_discrepancies": ( + artifacts.get("gdp_release_clock_evidence", {}).get( + "source_date_discrepancies", + {}, + ) + ), + "gdp_target_intraday_timing_verified": bool(gdp_clock_archive), + "empirical_findings_supported": False, + "timing_convention": ( + "event_specific_exact_clock_else_official_date_eod_convention" + ), + "forecast_origin_rule": ( + "one_second_before_exact_release_else_previous_calendar_day_eod_" + "America/New_York" + ), + "gdp_target_semantics": "official_published_qoq_saar_growth_not_level_derived", + "gdp_nipa_level_vintages_included": bool(gdp_levels), + "gdp_nipa_level_series_id": BEA_NIPA_LEVEL_SERIES_ID, + "gdp_nipa_level_canonical_rows": len(gdp_levels), + "gdp_nipa_level_release_snapshots": len( + {row.realtime_start for row in gdp_levels} + ), + "gdp_nipa_level_missing_target_quarters": ( + artifacts.get("gdp_nipa_level_archive", {}).get("missing_quarters", []) + ), + "gdp_nipa_level_same_snapshot_growth_supported": bool(gdp_levels), + "gdp_nipa_level_cross_vintage_raw_level_comparison_supported": False, + "gdp_nipa_level_published_growth_exact_rounded_count": ( + artifacts.get("gdp_nipa_level_archive", {}).get( + "published_growth_exact_rounded_count" + ) + ), + "gdp_nipa_level_published_growth_reconciliation_count": ( + artifacts.get("gdp_nipa_level_archive", {}).get( + "published_growth_reconciliation_count" + ) + ), + "ces_sector_predictor_vintages_included": True, + "cps_unemployment_rate_vintages_included": bool(unemployment_rate), + "cps_unemployment_rate_series_id": UNEMPLOYMENT_RATE_SERIES_ID, + "cps_unemployment_rate_release_snapshots": len( + {row.realtime_start for row in unemployment_rate} + ), + "dol_weekly_claims_vintages_included": bool(dol_claims), + "dol_weekly_claims_series_id": DOL_CLAIMS_SERIES_ID, + "dol_weekly_claims_release_snapshots": len( + { + row.realtime_start + for row in dol_claims + if row.source_metadata.get("vintage_type") == "advance" + } + ), + "dol_weekly_claims_intraday_timing_verified": bool(dol_claims), + "fed_g17_vintages_included": bool(fed_g17), + "fed_g17_index_series_id": FED_G17_INDEX_SERIES_ID, + "fed_g17_mom_series_id": FED_G17_MOM_SERIES_ID, + "fed_g17_release_snapshots": len({row.realtime_start for row in fed_g17}), + "fed_g17_release_clock_times_verified": bool(fed_g17), + "treasury_10y_daily_observations_included": bool(treasury_rates), + "treasury_10y_series_id": TREASURY_10Y_SERIES_ID, + "treasury_10y_observation_rows": len(treasury_rates), + "treasury_10y_first_observation_date": ( + min(row.observation_date for row in treasury_rates).isoformat() + if treasury_rates + else None + ), + "treasury_10y_last_observation_date": ( + max(row.observation_date for row in treasury_rates).isoformat() + if treasury_rates + else None + ), + "treasury_10y_timing_quality": TREASURY_RATES_TIMING_QUALITY, + "treasury_10y_availability_rule": TREASURY_RATES_AVAILABILITY_RULE, + "treasury_10y_exact_publication_clock_claimed": False, + "treasury_10y_publication_vintage_dimension_available": False, + "treasury_10y_later_correction_history_available": False, + "census_retail_vintages_included": bool(census_retail), + "census_retail_level_series_id": CENSUS_RETAIL_LEVEL_SERIES_ID, + "census_retail_mom_series_id": CENSUS_RETAIL_MOM_SERIES_ID, + "census_retail_release_snapshots": len( + {row.realtime_start for row in census_retail} + ), + "census_retail_release_clock_times_verified": bool(census_retail), + "census_housing_vintages_included": bool(census_housing), + "census_housing_starts_series_id": CENSUS_HOUSING_STARTS_SERIES_ID, + "census_housing_release_snapshots": len(census_housing), + "census_housing_release_clock_times_verified": bool(census_housing), + "ces_sector_predictor_series": [ + { + "series_id": spec.series_id, + "agency_series_id": spec.agency_series_id, + "industry_title": spec.industry_title, + "archive_member": spec.archive_member, + "observation_start": ( + spec.observation_start.isoformat() + if spec.observation_start is not None + else None + ), + } + for spec in CES_SECTOR_PREDICTOR_SPECS + ], + "observation_rows": observations.height, + "release_rows": calendar.height, + "series": observations["series_id"].unique().sort().to_list(), + "row_counts_by_series": { + row["series_id"]: row["len"] + for row in observations.group_by("series_id").len().to_dicts() + }, + "source_audit": { + "audited_at": audit["audited_at"], + "api_credentials_used": audit["api_credentials_used"], + "api_txt_read": audit["api_txt_read"], + }, + } + return OfficialArchiveData(observations, calendar, metadata) + + +def write_official_archive_data( + raw_dir: str | Path, + output_dir: str | Path, + *, + overwrite: bool = False, +) -> dict[str, object]: + """Write frozen Parquet artifacts and metadata after a successful local audit.""" + + data = build_official_archive_data(raw_dir) + destination = Path(output_dir).resolve() + observations_path = destination / "official_vintage_observations.parquet" + calendar_path = destination / "official_release_calendar.parquet" + gdp_level_validation_path = destination / "gdp_level_target_validation.parquet" + catalog_path = destination / "official_vintages.duckdb" + metadata_path = destination / "ingestion_manifest.json" + existing = [ + path + for path in ( + observations_path, + calendar_path, + gdp_level_validation_path, + catalog_path, + metadata_path, + ) + if path.exists() + ] + if existing and not overwrite: + raise FileExistsError(f"official artifacts already exist: {existing[0].name}") + destination.mkdir(parents=True, exist_ok=True) + if overwrite and catalog_path.exists(): + catalog_path.unlink() + store = VintageStore(destination, catalog_path) + observations_path = store.write_observations( + data.observations, + dataset_name="official_vintage_observations", + overwrite=overwrite, + table_name="official_vintage_observations", + ) + data.release_calendar.write_parquet(calendar_path, compression="zstd", statistics=True) + store.register_view(calendar_path, table_name="official_release_calendar") + gdp_level_validation = _gdp_level_target_validation( + data.observations, + data.release_calendar, + ) + if gdp_level_validation.height: + gdp_level_validation.write_parquet( + gdp_level_validation_path, + compression="zstd", + statistics=True, + ) + store.register_view( + gdp_level_validation_path, + table_name="gdp_level_target_validation", + ) + elif overwrite and gdp_level_validation_path.exists(): + gdp_level_validation_path.unlink() + manifest = { + "status": "ready_with_mixed_timing", + **data.metadata, + "observation_artifact": { + "path": observations_path.name, + "sha256": _sha256(observations_path), + }, + "release_calendar_artifact": { + "path": calendar_path.name, + "sha256": _sha256(calendar_path), + }, + "gdp_level_target_validation_artifact": ( + { + "path": gdp_level_validation_path.name, + "sha256": _sha256(gdp_level_validation_path), + "rows": gdp_level_validation.height, + "same_snapshot_rows": int( + gdp_level_validation["same_snapshot_adjacent_levels"].sum() + ), + "exact_rounded_rows": int( + gdp_level_validation["rounds_exactly_to_published_tenth"].sum() + ), + "within_006pp_rows": int( + gdp_level_validation[ + "within_006pp_level_rounding_tolerance" + ].sum() + ), + "maximum_abs_difference_pp": gdp_level_validation[ + "absolute_difference_pp" + ].max(), + "target_semantics": ( + "same_snapshot_adjacent_real_gdp_levels_qoq_saar_validation_only" + ), + "official_pilot_target_replaced": False, + } + if gdp_level_validation.height + else None + ), + "duckdb_catalog": { + "path": catalog_path.name, + "views": [ + "official_vintage_observations", + "official_release_calendar", + *( + ["gdp_level_target_validation"] + if gdp_level_validation.height + else [] + ), + ], + }, + } + metadata_path.write_text( + json.dumps(manifest, indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + return { + "status": "ready_with_mixed_timing", + "output_dir": destination, + "observation_rows": data.observations.height, + "release_rows": data.release_calendar.height, + "gdp_level_target_validation_rows": gdp_level_validation.height, + "historical_ingestion_ready": True, + } + + +__all__ = [ + "CENSUS_HOUSING_DIRECTORY", + "CENSUS_HOUSING_STARTS_SERIES_ID", + "CENSUS_RETAIL_DIRECTORY", + "CENSUS_RETAIL_LEVEL_SERIES_ID", + "CENSUS_RETAIL_MOM_SERIES_ID", + "CES_SECTOR_PREDICTOR_SPECS", + "DATE_ONLY_TIMING_QUALITY", + "DOL_CLAIMS_DIRECTORY", + "DOL_CLAIMS_SERIES_ID", + "EMPSIT_DOM_DIRECTORY", + "FED_G17_DIRECTORY", + "FED_G17_INDEX_SERIES_ID", + "FED_G17_MOM_SERIES_ID", + "GDP_GROWTH_SERIES_ID", + "OFFICIAL_ARCHIVE_PROVENANCE", + "PAYEMS_CES_SPEC", + "UNEMPLOYMENT_RATE_SERIES_ID", + "ArchiveIngestionError", + "CESVintageSeriesSpec", + "OfficialArchiveData", + "build_official_archive_data", + "parse_ces_sector_vintage_archives", + "parse_ces_series_vintage_archive", + "parse_ces_vintage_archive", + "parse_cpi_archives", + "parse_cpi_snapshot", + "parse_empsit_unemployment_rate_archive", + "parse_empsit_unemployment_rate_snapshot", + "parse_gdp_vintage_history", + "write_official_archive_data", +] diff --git a/Macroeconomics/src/macro_nowcast/artifacts.py b/Macroeconomics/src/macro_nowcast/artifacts.py new file mode 100644 index 0000000000000000000000000000000000000000..95ded43d04f7d4892dc2e45866bbb55ed549ec4e --- /dev/null +++ b/Macroeconomics/src/macro_nowcast/artifacts.py @@ -0,0 +1,72 @@ +"""Reproducibility metadata and deterministic artifact helpers.""" + +from __future__ import annotations + +import hashlib +import importlib.metadata +import json +from datetime import date, datetime +from io import BytesIO +from pathlib import Path +from typing import Any + +import polars as pl + + +def sha256_bytes(payload: bytes) -> str: + return hashlib.sha256(payload).hexdigest() + + +def sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + while chunk := handle.read(1024 * 1024): + digest.update(chunk) + return digest.hexdigest() + + +def frame_hash(frame: pl.DataFrame) -> str: + """Hash a deterministically ordered frame as Arrow IPC bytes.""" + + buffer = BytesIO() + frame.write_ipc(buffer, compression="uncompressed") + return sha256_bytes(buffer.getvalue()) + + +def config_hash(path: Path) -> str: + return sha256_file(path) + + +def package_versions(names: list[str] | None = None) -> dict[str, str]: + selected = names or [ + "macro-nowcast", + "polars", + "duckdb", + "pyarrow", + "numpy", + "scikit-learn", + "statsmodels", + ] + versions: dict[str, str] = {} + for name in selected: + try: + versions[name] = importlib.metadata.version(name) + except importlib.metadata.PackageNotFoundError: + versions[name] = "not-installed" + return versions + + +def _json_default(value: object) -> str: + if isinstance(value, (date, datetime, Path)): + return value.isoformat() if not isinstance(value, Path) else str(value) + if hasattr(value, "item"): + return str(value.item()) # type: ignore[union-attr] + raise TypeError(f"cannot JSON encode {type(value).__name__}") + + +def write_json(payload: dict[str, Any], path: Path) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + json.dumps(payload, indent=2, sort_keys=True, default=_json_default) + "\n" + ) + return path diff --git a/Macroeconomics/src/macro_nowcast/asof.py b/Macroeconomics/src/macro_nowcast/asof.py new file mode 100644 index 0000000000000000000000000000000000000000..0a75f73c9da95b982ae3d0db8dcffd1ddaa28b95 --- /dev/null +++ b/Macroeconomics/src/macro_nowcast/asof.py @@ -0,0 +1,243 @@ +"""Vintage selection with strict, auditable information boundaries.""" + +from __future__ import annotations + +from datetime import UTC, datetime + +import polars as pl + +from macro_nowcast.schema import validate_canonical_frame + +AS_OF_MODE = "as_of" +LATEST_SAME_MASK_MODE = "latest_values_same_eligibility_mask" +NAIVE_LATEST_MODE = "naive_latest_revised" + + +def _coerce_as_of(value: datetime | str) -> datetime: + if isinstance(value, str): + normalized = f"{value[:-1]}+00:00" if value.endswith("Z") else value + try: + value = datetime.fromisoformat(normalized) + except ValueError as exc: + raise ValueError("as_of must be an ISO datetime with a timezone") from exc + if not isinstance(value, datetime): + raise TypeError("as_of must be a timezone-aware datetime") + if value.tzinfo is None or value.utcoffset() is None: + raise ValueError("as_of must include an explicit timezone") + return value.astimezone(UTC) + + +def _effective_availability() -> pl.Expr: + """Use exact timing when present and conservative UTC end-of-day otherwise.""" + + end_of_day = pl.col("availability_date").cast(pl.Datetime("us", "UTC")) + pl.duration( + hours=23, + minutes=59, + seconds=59, + microseconds=999_999, + ) + return pl.coalesce(pl.col("availability_timestamp"), end_of_day).alias( + "effective_availability_timestamp" + ) + + +def _validated_observations(observations: pl.DataFrame) -> pl.DataFrame: + frame = validate_canonical_frame(observations) + timestamp_date_mismatch = frame.filter( + pl.col("availability_timestamp").is_not_null() + & (pl.col("availability_timestamp").dt.date() != pl.col("availability_date")) + ) + if timestamp_date_mismatch.height: + raise ValueError("availability_timestamp must fall on availability_date in UTC") + duplicate_vintages = ( + frame.group_by(["series_id", "observation_date", "realtime_start"]) + .len() + .filter(pl.col("len") > 1) + ) + if duplicate_vintages.height: + raise ValueError( + "series_id, observation_date, and realtime_start must identify one vintage" + ) + return frame.with_columns(_effective_availability()) + + +def _latest_per_observation(frame: pl.DataFrame) -> pl.DataFrame: + """Rank every row, including null values, before selecting the latest vintage.""" + + return ( + frame.sort( + [ + "series_id", + "observation_date", + "effective_availability_timestamp", + "realtime_start", + "download_timestamp", + ] + ) + .unique(subset=["series_id", "observation_date"], keep="last", maintain_order=True) + .sort(["series_id", "observation_date"]) + ) + + +def select_as_of( + observations: pl.DataFrame, + as_of: datetime | str, +) -> pl.DataFrame: + """Select the latest vintage actually available at ``as_of``. + + Missing latest rows are intentionally retained. Filtering nulls before the + vintage rank would resurrect stale values and is therefore forbidden. + """ + + cutoff = _coerce_as_of(as_of) + frame = _validated_observations(observations) + eligible = frame.filter(pl.col("effective_availability_timestamp") <= pl.lit(cutoff)) + snapshot = _latest_per_observation(eligible).with_columns( + pl.lit(AS_OF_MODE).alias("information_set_mode"), + pl.lit(False).alias("is_counterfactual"), + pl.lit(cutoff).cast(pl.Datetime("us", "UTC")).alias("as_of_timestamp"), + pl.col("effective_availability_timestamp").alias("eligibility_timestamp"), + pl.col("effective_availability_timestamp").alias( + "selected_vintage_availability_timestamp" + ), + ) + assert_no_future_information(snapshot, cutoff) + return snapshot + + +def select_latest_values_same_eligibility_mask( + observations: pl.DataFrame, + as_of: datetime | str, +) -> pl.DataFrame: + """Substitute latest values only for observation cells eligible at ``as_of``. + + This intentionally counterfactual view isolates value-revision leakage from + release-timing leakage. ``eligibility_timestamp`` records when the cell first + entered the information set; ``selected_vintage_availability_timestamp`` records + when the substituted value actually became available. + """ + + cutoff = _coerce_as_of(as_of) + frame = _validated_observations(observations) + eligible_cells = ( + frame.filter(pl.col("effective_availability_timestamp") <= pl.lit(cutoff)) + .group_by(["series_id", "observation_date"]) + .agg( + pl.col("effective_availability_timestamp") + .min() + .alias("eligibility_timestamp") + ) + ) + latest = _latest_per_observation(frame).rename( + {"effective_availability_timestamp": "selected_vintage_availability_timestamp"} + ) + counterfactual = ( + latest.join( + eligible_cells, + on=["series_id", "observation_date"], + how="inner", + validate="1:1", + ) + .with_columns( + pl.col("selected_vintage_availability_timestamp").alias( + "effective_availability_timestamp" + ), + pl.lit(LATEST_SAME_MASK_MODE).alias("information_set_mode"), + pl.lit(True).alias("is_counterfactual"), + pl.lit(cutoff).cast(pl.Datetime("us", "UTC")).alias("as_of_timestamp"), + ) + .sort(["series_id", "observation_date"]) + ) + if counterfactual.filter(pl.col("eligibility_timestamp") > pl.col("as_of_timestamp")).height: + raise AssertionError("counterfactual eligibility mask contains future information") + return counterfactual + + +def select_naive_latest_revised( + observations: pl.DataFrame, + as_of: datetime | str, +) -> pl.DataFrame: + """Return the latest row for every cell, ignoring historical eligibility. + + This is an intentionally leaky research benchmark. Callers should first + restrict ``observations`` to a declared fixed evaluation vintage. The + historical ``as_of`` timestamp is retained so downstream audits can count + cells whose first availability occurred after the forecast origin. + """ + + cutoff = _coerce_as_of(as_of) + frame = _validated_observations(observations) + first_availability = frame.group_by(["series_id", "observation_date"]).agg( + pl.col("effective_availability_timestamp") + .min() + .alias("eligibility_timestamp") + ) + latest = _latest_per_observation(frame).rename( + {"effective_availability_timestamp": "selected_vintage_availability_timestamp"} + ) + return ( + latest.join( + first_availability, + on=["series_id", "observation_date"], + how="inner", + validate="1:1", + ) + .with_columns( + pl.col("selected_vintage_availability_timestamp").alias( + "effective_availability_timestamp" + ), + pl.lit(NAIVE_LATEST_MODE).alias("information_set_mode"), + pl.lit(True).alias("is_counterfactual"), + pl.lit(cutoff).cast(pl.Datetime("us", "UTC")).alias("as_of_timestamp"), + ) + .sort(["series_id", "observation_date"]) + ) + + +def assert_no_future_information( + frame: pl.DataFrame, + as_of: datetime | str | None = None, +) -> None: + """Raise if a valid as-of frame contains information from after its cutoff.""" + + if frame.is_empty(): + return + if "is_counterfactual" in frame.columns and frame["is_counterfactual"].any(): + raise ValueError("strict no-future validation does not accept counterfactual rows") + + if "effective_availability_timestamp" in frame.columns: + availability = pl.col("effective_availability_timestamp") + elif "availability_timestamp" in frame.columns and "availability_date" in frame.columns: + availability = _effective_availability() + frame = frame.with_columns(availability) + availability = pl.col("effective_availability_timestamp") + else: + raise ValueError("frame lacks auditable availability columns") + + if as_of is None: + if "as_of_timestamp" not in frame.columns: + raise ValueError("as_of is required when frame has no as_of_timestamp") + violations = frame.filter(availability > pl.col("as_of_timestamp")) + else: + cutoff = _coerce_as_of(as_of) + violations = frame.filter(availability > pl.lit(cutoff)) + if violations.height: + raise AssertionError( + f"future information detected in {violations.height} row(s)" + ) + + +# Descriptive compatibility alias for callers that prefer noun-first naming. +as_of_snapshot = select_as_of + + +__all__ = [ + "AS_OF_MODE", + "LATEST_SAME_MASK_MODE", + "NAIVE_LATEST_MODE", + "as_of_snapshot", + "assert_no_future_information", + "select_as_of", + "select_latest_values_same_eligibility_mask", + "select_naive_latest_revised", +] diff --git a/Macroeconomics/src/macro_nowcast/attribution.py b/Macroeconomics/src/macro_nowcast/attribution.py new file mode 100644 index 0000000000000000000000000000000000000000..f9f774ff4043747a8764a4a89c6cdb968f2e668a --- /dev/null +++ b/Macroeconomics/src/macro_nowcast/attribution.py @@ -0,0 +1,290 @@ +"""Fixed-model nowcast news attribution. + +Linear attributions are exact coefficient decompositions in the fitted model's +transformed feature space. Tree attributions use deterministic sequential +feature replacement and are always labeled approximate because interaction +credit depends on replacement order. +""" + +from __future__ import annotations + +import math +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import Any + +import numpy as np +from numpy.typing import NDArray +from sklearn.pipeline import Pipeline +from sklearn.utils.validation import check_is_fitted + +FloatArray = NDArray[np.float64] + + +@dataclass(frozen=True) +class AttributionResult: + """Auditable change decomposition for a fixed fitted model.""" + + previous_prediction: float + updated_prediction: float + total_change: float + contributions: Mapping[str, float] + feature_changes: Mapping[str, float] + unattributed_residual: float + method: str + approximate: bool + + @property + def is_exact(self) -> bool: + return not self.approximate + + @property + def label(self) -> str: + return "approximate" if self.approximate else "exact" + + +def _raw_row_and_names( + values: Any, + *, + feature_names: Sequence[str] | None, +) -> tuple[FloatArray, tuple[str, ...]]: + if isinstance(values, Mapping): + inferred_names = tuple(str(name) for name in values) + row = np.asarray([values[name] for name in values], dtype=float).reshape(1, -1) + else: + if hasattr(values, "to_numpy"): + raw = values.to_numpy() + columns = getattr(values, "columns", None) + inferred_names = tuple(str(name) for name in columns) if columns is not None else () + else: + raw = np.asarray(values) + inferred_names = () + row = np.asarray(raw, dtype=float) + if row.ndim == 1: + row = row.reshape(1, -1) + if row.ndim != 2 or row.shape[0] != 1: + raise ValueError("Features must describe exactly one observation") + + if feature_names is not None: + names = tuple(str(name) for name in feature_names) + elif inferred_names: + names = inferred_names + else: + names = tuple(f"x{index}" for index in range(row.shape[1])) + if len(names) != row.shape[1] or len(set(names)) != len(names): + raise ValueError("feature_names must be unique and match the feature count") + return row, names + + +def _aligned_rows( + previous_features: Any, + updated_features: Any, + feature_names: Sequence[str] | None, +) -> tuple[FloatArray, FloatArray, tuple[str, ...]]: + if isinstance(previous_features, Mapping) and isinstance(updated_features, Mapping): + previous_keys = tuple(str(key) for key in previous_features) + updated_keys = tuple(str(key) for key in updated_features) + if set(previous_keys) != set(updated_keys): + raise ValueError("Previous and updated feature mappings must have identical keys") + names = tuple(str(name) for name in feature_names) if feature_names else previous_keys + try: + previous = np.asarray( + [previous_features[name] for name in names], dtype=float + ).reshape(1, -1) + updated = np.asarray( + [updated_features[name] for name in names], dtype=float + ).reshape(1, -1) + except KeyError as exc: + raise ValueError("feature_names contains a key missing from a feature mapping") from exc + return previous, updated, names + + previous, names = _raw_row_and_names( + previous_features, + feature_names=feature_names, + ) + updated, updated_names = _raw_row_and_names( + updated_features, + feature_names=names, + ) + if previous.shape != updated.shape or names != updated_names: + raise ValueError("Previous and updated features must have identical shape and order") + return previous, updated, names + + +def _predict_one(model: Any, row: FloatArray) -> float: + prediction = np.asarray(model.predict(row), dtype=float).reshape(-1) + if prediction.size != 1 or not np.isfinite(prediction[0]): + raise ValueError("Model must return one finite prediction per attribution row") + return float(prediction[0]) + + +def _pipeline_and_linear_estimator(model: Any) -> tuple[Any, Any]: + fitted = getattr(model, "pipeline_", model) + if isinstance(fitted, Pipeline): + check_is_fitted(fitted) + estimator = fitted.steps[-1][1] + transformer = fitted[:-1] + else: + estimator = fitted + transformer = None + check_is_fitted(estimator, attributes=["coef_"]) + return transformer, estimator + + +def _dense_2d(values: Any) -> FloatArray: + if hasattr(values, "toarray"): + values = values.toarray() + result = np.asarray(values, dtype=float) + if result.ndim == 1: + result = result.reshape(1, -1) + if result.ndim != 2: + raise ValueError("Transformed features must be two-dimensional") + return result + + +def linear_news_attribution( + model: Any, + previous_features: Any, + updated_features: Any, + *, + feature_names: Sequence[str] | None = None, + atol: float = 1e-9, +) -> AttributionResult: + """Exactly decompose a fixed fitted linear model's prediction revision. + + For an imputer/scaler/linear pipeline, contributions are coefficients times + changes in the transformed features. The transformer and model are never + refitted during attribution. + """ + + previous, updated, raw_names = _aligned_rows( + previous_features, + updated_features, + feature_names, + ) + transformer, estimator = _pipeline_and_linear_estimator(model) + if transformer is None: + previous_transformed = previous + updated_transformed = updated + transformed_names = raw_names + else: + previous_transformed = _dense_2d(transformer.transform(previous)) + updated_transformed = _dense_2d(transformer.transform(updated)) + try: + transformed_names = tuple( + str(name) for name in transformer.get_feature_names_out(raw_names) + ) + except (AttributeError, TypeError, ValueError): + transformed_names = raw_names + + coefficients = np.asarray(estimator.coef_, dtype=float) + if coefficients.ndim == 2 and coefficients.shape[0] == 1: + coefficients = coefficients[0] + if coefficients.ndim != 1: + raise ValueError("Only single-output linear estimators are supported") + if previous_transformed.shape != updated_transformed.shape: + raise ValueError("Preprocessing changed feature dimensions between snapshots") + if coefficients.size != previous_transformed.shape[1]: + raise ValueError("Linear coefficient count does not match transformed features") + if len(transformed_names) != coefficients.size: + transformed_names = tuple(f"transformed_x{i}" for i in range(coefficients.size)) + + previous_prediction = _predict_one(model, previous) + updated_prediction = _predict_one(model, updated) + contribution_values = coefficients * (updated_transformed[0] - previous_transformed[0]) + total_change = updated_prediction - previous_prediction + residual = total_change - float(np.sum(contribution_values)) + tolerance = atol * max(1.0, abs(total_change)) + if not math.isfinite(residual) or abs(residual) > tolerance: + raise RuntimeError( + "Linear contribution sum does not reproduce the fixed-model prediction change" + ) + contributions = { + name: float(value) + for name, value in zip(transformed_names, contribution_values, strict=True) + } + feature_changes = { + name: float(value) + for name, value in zip(raw_names, updated[0] - previous[0], strict=True) + } + return AttributionResult( + previous_prediction=previous_prediction, + updated_prediction=updated_prediction, + total_change=total_change, + contributions=contributions, + feature_changes=feature_changes, + unattributed_residual=residual, + method="exact_linear_fixed_model", + approximate=False, + ) + + +def approximate_tree_news_attribution( + model: Any, + previous_features: Any, + updated_features: Any, + *, + feature_names: Sequence[str] | None = None, + feature_order: Sequence[str] | None = None, +) -> AttributionResult: + """Approximate nonlinear attribution by sequential feature replacement. + + The deterministic contributions telescope to the prediction change, but the + allocation of interactions is order-dependent. The result therefore remains + explicitly approximate even when its numerical residual is zero. + """ + + previous, updated, names = _aligned_rows( + previous_features, + updated_features, + feature_names, + ) + if feature_order is None: + order = names + else: + order = tuple(str(name) for name in feature_order) + if len(order) != len(names) or set(order) != set(names): + raise ValueError("feature_order must contain every feature exactly once") + + previous_prediction = _predict_one(model, previous) + updated_prediction = _predict_one(model, updated) + current = previous.copy() + current_prediction = previous_prediction + contributions: dict[str, float] = {name: 0.0 for name in names} + positions = {name: index for index, name in enumerate(names)} + for name in order: + position = positions[name] + current[0, position] = updated[0, position] + next_prediction = _predict_one(model, current) + contributions[name] = next_prediction - current_prediction + current_prediction = next_prediction + + total_change = updated_prediction - previous_prediction + residual = total_change - float(sum(contributions.values())) + feature_changes = { + name: float(value) + for name, value in zip(names, updated[0] - previous[0], strict=True) + } + return AttributionResult( + previous_prediction=previous_prediction, + updated_prediction=updated_prediction, + total_change=total_change, + contributions=contributions, + feature_changes=feature_changes, + unattributed_residual=residual, + method="approximate_sequential_feature_replacement", + approximate=True, + ) + + +exact_linear_attribution = linear_news_attribution +tree_news_attribution = approximate_tree_news_attribution + + +__all__ = [ + "AttributionResult", + "approximate_tree_news_attribution", + "exact_linear_attribution", + "linear_news_attribution", + "tree_news_attribution", +] diff --git a/Macroeconomics/src/macro_nowcast/bea_gdp_clock_archive.py b/Macroeconomics/src/macro_nowcast/bea_gdp_clock_archive.py new file mode 100644 index 0000000000000000000000000000000000000000..f9e3e7a9650d5cd014ed1a63c19105179d2a377f --- /dev/null +++ b/Macroeconomics/src/macro_nowcast/bea_gdp_clock_archive.py @@ -0,0 +1,414 @@ +"""Offline audit of official BEA GDP release-header clock evidence.""" + +from __future__ import annotations + +import hashlib +import json +import re +from collections.abc import Mapping +from dataclasses import dataclass +from datetime import UTC, date, datetime +from pathlib import Path +from types import MappingProxyType +from typing import Final +from zoneinfo import ZoneInfo + +BEA_GDP_CLOCK_DIRECTORY: Final = "bea-gdp-news" +BEA_GDP_CLOCK_FILENAME: Final = "clock-evidence.json" +BEA_GDP_CLOCK_SOURCE: Final = "BEA_GDP_NEWS_RELEASE_HEADER_EVIDENCE" +BEA_GDP_CLOCK_INDEX_URL: Final = "https://www.bea.gov/news/archive" +BEA_GDP_CLOCK_TIMING_QUALITY: Final = ( + "official_embargo_header_clock_America_New_York" +) + +_NEW_YORK = ZoneInfo("America/New_York") +_CLOCK_RE = re.compile( + r"(?P\d{1,2}):(?P\d{2})\s*" + r"(?Pa\.?\s*m\.?|p\.?\s*m\.?)\s*" + r"(?PEST|EDT)\b", + re.IGNORECASE, +) +_DATE_RE = re.compile( + r"(?PMonday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)" + r"\s*,\s*" + r"(?PJanuary|February|March|April|May|June|July|August|September|" + r"October|November|December)\s+" + r"(?P\d{1,2}),\s*(?P\d{4})", + re.IGNORECASE, +) +_ALLOWED_FORMATS = {"browser_rendered_html_header_text_extraction"} + + +class BEAGDPClockArchiveError(ValueError): + """Raised when BEA header evidence cannot prove its claimed release clock.""" + + +@dataclass(frozen=True, slots=True) +class BEAReleaseClock: + """One release instant proven by a BEA news-release header.""" + + release_date: date + release_timestamp: datetime + printed_timezone: str + printed_weekday: str + timing_quality: str = BEA_GDP_CLOCK_TIMING_QUALITY + + +@dataclass(frozen=True, slots=True) +class BEAGDPClockArchive: + """Verified GDP release clocks and immutable acquisition metadata.""" + + clocks: Mapping[date, BEAReleaseClock] + event_metadata: Mapping[date, Mapping[str, object]] + retrieved_at: str + evidence_sha256: str + source_release_index_sha256: str + + +def _sha256_bytes(payload: bytes) -> str: + return hashlib.sha256(payload).hexdigest() + + +def parse_bea_release_header( + header_text: str, + *, + expected_release_date: date, +) -> BEAReleaseClock: + """Parse a BEA wire/embargo header and verify its date, weekday, and zone.""" + + if not re.search( + r"FOR WIRE TRANSMISSION|EMBARGOED (?:UNTIL|FOR) RELEASE", + header_text, + re.IGNORECASE, + ): + raise BEAGDPClockArchiveError("BEA evidence is not a recognized release header") + clock_match = _CLOCK_RE.search(header_text) + if clock_match is None: + raise BEAGDPClockArchiveError("BEA release header has no EST/EDT clock") + date_match = _DATE_RE.search(header_text, clock_match.end()) + if date_match is None: + raise BEAGDPClockArchiveError("BEA release header has no weekday and date") + + parsed_date = datetime.strptime( + "{} {} {}".format( + date_match.group("month").title(), + date_match.group("day"), + date_match.group("year"), + ), + "%B %d %Y", + ).date() + if parsed_date != expected_release_date: + raise BEAGDPClockArchiveError( + "BEA release date mismatch: " + f"expected {expected_release_date}, found {parsed_date}" + ) + printed_weekday = date_match.group("weekday").title() + if parsed_date.strftime("%A") != printed_weekday: + raise BEAGDPClockArchiveError( + "BEA release weekday conflicts with its printed date" + ) + + hour = int(clock_match.group("hour")) + minute = int(clock_match.group("minute")) + if not 1 <= hour <= 12 or not 0 <= minute <= 59: + raise BEAGDPClockArchiveError("BEA release clock is outside 12-hour bounds") + meridiem = re.sub(r"[.\s]", "", clock_match.group("meridiem")).lower() + if meridiem == "pm" and hour != 12: + hour += 12 + elif meridiem == "am" and hour == 12: + hour = 0 + local = datetime( + parsed_date.year, + parsed_date.month, + parsed_date.day, + hour, + minute, + tzinfo=_NEW_YORK, + ) + printed_timezone = clock_match.group("timezone").upper() + if local.tzname() != printed_timezone: + raise BEAGDPClockArchiveError( + "BEA release timezone label conflicts with America/New_York: " + f"printed {printed_timezone}, calendar implies {local.tzname()}" + ) + return BEAReleaseClock( + release_date=parsed_date, + release_timestamp=local.astimezone(UTC), + printed_timezone=printed_timezone, + printed_weekday=printed_weekday, + ) + + +def _validated_document(path: Path) -> tuple[dict[str, object], bytes]: + payload = path.read_bytes() + try: + document = json.loads(payload) + except json.JSONDecodeError as exc: + raise BEAGDPClockArchiveError("GDP clock evidence is not valid JSON") from exc + if not isinstance(document, dict): + raise BEAGDPClockArchiveError("GDP clock evidence must be a JSON object") + expected = { + "schema_version": 1, + "status": "complete", + "source_index_url": BEA_GDP_CLOCK_INDEX_URL, + "source_home_url": "https://www.bea.gov/", + "acquisition_format": "browser_rendered_embargo_header_text_extraction", + "server_original_bytes_claimed": False, + "complete_dom_claimed": False, + } + for field, expected_value in expected.items(): + if document.get(field) != expected_value: + raise BEAGDPClockArchiveError( + f"GDP clock evidence field {field!r} is not {expected_value!r}" + ) + if not isinstance(document.get("retrieved_at"), str): + raise BEAGDPClockArchiveError("GDP clock evidence has no retrieval timestamp") + events = document.get("events") + inventory = document.get("source_release_index_inventory") + expected_count = document.get("expected_event_count") + archive_count = document.get("archive_initial_event_count") + current_count = document.get("current_event_count") + if ( + not isinstance(events, list) + or not events + or not isinstance(expected_count, int) + or expected_count != len(events) + or not isinstance(archive_count, int) + or not isinstance(current_count, int) + or archive_count + current_count != len(events) + ): + raise BEAGDPClockArchiveError("GDP clock evidence event counts disagree") + if not isinstance(document.get("archive_filter_page_count"), int): + raise BEAGDPClockArchiveError("GDP clock evidence has no archive-page count") + if not isinstance(inventory, list) or len(inventory) != len(events): + raise BEAGDPClockArchiveError("GDP source index inventory is incomplete") + inventory_payload = json.dumps( + inventory, + separators=(",", ":"), + ensure_ascii=False, + ).encode() + if document.get("source_release_index_sha256") != _sha256_bytes(inventory_payload): + raise BEAGDPClockArchiveError("GDP source release-index hash mismatch") + return document, payload + + +def parse_bea_gdp_clock_archive( + path: str | Path, + *, + expected_initial_releases: Mapping[date, str] | None = None, +) -> BEAGDPClockArchive: + """Parse all 98 saved GDP initial-release headers and reconcile source evidence.""" + + document, payload = _validated_document(Path(path)) + raw_events = document["events"] + inventory = document["source_release_index_inventory"] + assert isinstance(raw_events, list) + assert isinstance(inventory, list) + clocks: dict[date, BEAReleaseClock] = {} + metadata: dict[date, Mapping[str, object]] = {} + header_hashes: set[str] = set() + inventory_by_url = { + str(item.get("official_url")): item + for item in inventory + if isinstance(item, dict) + } + if len(inventory_by_url) != len(inventory): + raise BEAGDPClockArchiveError("GDP source inventory contains duplicate URLs") + for raw_event in raw_events: + if not isinstance(raw_event, dict): + raise BEAGDPClockArchiveError("GDP clock evidence contains a non-object event") + try: + release_date = date.fromisoformat(str(raw_event["release_date"])) + except (KeyError, ValueError) as exc: + raise BEAGDPClockArchiveError("GDP clock event has an invalid date") from exc + if release_date in clocks: + raise BEAGDPClockArchiveError(f"duplicate GDP clock event: {release_date}") + header_text = raw_event.get("header_text") + header_sha256 = raw_event.get("header_sha256") + evidence_format = raw_event.get("evidence_format") + if not isinstance(header_text, str) or not header_text: + raise BEAGDPClockArchiveError(f"GDP clock event has no header: {release_date}") + if evidence_format not in _ALLOWED_FORMATS: + raise BEAGDPClockArchiveError( + f"GDP clock event has unsupported evidence format: {release_date}" + ) + calculated_hash = _sha256_bytes(header_text.encode()) + if header_sha256 != calculated_hash: + raise BEAGDPClockArchiveError( + f"GDP clock event header hash mismatch: {release_date}" + ) + if calculated_hash in header_hashes: + raise BEAGDPClockArchiveError("GDP clock evidence contains duplicate headers") + header_hashes.add(calculated_hash) + label = raw_event.get("observation_label") + release_type = raw_event.get("source_release_type") + if ( + not isinstance(label, str) + or not re.search(r"Gross Domestic Product|\bGDP\b", label) + or not re.search(r"advance|initial", label, re.IGNORECASE) + ): + raise BEAGDPClockArchiveError( + f"GDP clock event has an invalid observation label: {release_date}" + ) + if release_type not in {"Advance", "Initial"}: + raise BEAGDPClockArchiveError( + f"GDP clock event has an invalid release type: {release_date}" + ) + url = raw_event.get("official_url") + resolved_url = raw_event.get("resolved_url") + if ( + not isinstance(url, str) + or re.match( + r"https://www\.bea\.gov/(?:news|index\.(?:php|ph%70)/news)/", + url, + re.IGNORECASE, + ) + is None + or resolved_url != url + ): + raise BEAGDPClockArchiveError( + f"GDP clock event has an invalid official URL: {release_date}" + ) + index_event = inventory_by_url.get(url) + if ( + index_event is None + or index_event.get("observation_label") != label + or raw_event.get("archive_index_published_date") + != index_event.get("release_date") + ): + raise BEAGDPClockArchiveError( + f"GDP event evidence disagrees with source inventory: {release_date}" + ) + index_date = str(index_event["release_date"]) + discrepancy = raw_event.get("source_date_discrepancy") + if index_date == release_date.isoformat(): + if discrepancy is not None: + raise BEAGDPClockArchiveError( + f"GDP event records an unsupported date discrepancy: {release_date}" + ) + elif discrepancy != ( + "archive_index_one_day_early_header_and_vintage_workbook_agree" + ): + raise BEAGDPClockArchiveError( + f"GDP event does not document its source date discrepancy: {release_date}" + ) + clock = parse_bea_release_header( + header_text, + expected_release_date=release_date, + ) + if clock.release_timestamp.time() != datetime.strptime( + "12:30" if clock.printed_timezone == "EDT" else "13:30", + "%H:%M", + ).time(): + raise BEAGDPClockArchiveError("GDP initial release is not at 8:30 a.m. Eastern") + clocks[release_date] = clock + metadata[release_date] = MappingProxyType(dict(raw_event)) + if set(inventory_by_url) != { + str(event.get("official_url")) + for event in raw_events + if isinstance(event, dict) + }: + raise BEAGDPClockArchiveError("GDP source/event URL inventories disagree") + if expected_initial_releases is not None: + if set(expected_initial_releases) != set(clocks): + missing = sorted(set(expected_initial_releases) - set(clocks)) + extra = sorted(set(clocks) - set(expected_initial_releases)) + raise BEAGDPClockArchiveError( + f"GDP clock/workbook inventory mismatch: missing={missing[:3]}, " + f"extra={extra[:3]}" + ) + for release_date, expected_type in expected_initial_releases.items(): + if metadata[release_date]["source_release_type"] != expected_type: + raise BEAGDPClockArchiveError( + f"GDP clock/workbook release type mismatch: {release_date}" + ) + + return BEAGDPClockArchive( + clocks=MappingProxyType(clocks), + event_metadata=MappingProxyType(metadata), + retrieved_at=str(document["retrieved_at"]), + evidence_sha256=_sha256_bytes(payload), + source_release_index_sha256=str(document["source_release_index_sha256"]), + ) + + +def audit_bea_gdp_clock_archive( + directory: str | Path, + *, + expected_initial_releases: Mapping[date, str], +) -> dict[str, object]: + """Return machine-readable offline audit facts for GDP clock evidence.""" + + source = Path(directory) / BEA_GDP_CLOCK_FILENAME + archive = parse_bea_gdp_clock_archive( + source, + expected_initial_releases=expected_initial_releases, + ) + zones: dict[str, int] = {} + release_types: dict[str, int] = {} + header_styles: dict[str, int] = {} + source_date_discrepancies: dict[str, dict[str, str]] = {} + for release_date, clock in archive.clocks.items(): + zones[clock.printed_timezone] = zones.get(clock.printed_timezone, 0) + 1 + release_type = str(archive.event_metadata[release_date]["source_release_type"]) + release_types[release_type] = release_types.get(release_type, 0) + 1 + header = str(archive.event_metadata[release_date]["header_text"]) + if re.search(r"FOR WIRE TRANSMISSION", header, re.IGNORECASE): + style = "for_wire_transmission" + elif re.search(r"EMBARGOED FOR RELEASE", header, re.IGNORECASE): + style = "embargoed_for_release" + else: + style = "embargoed_until_release" + header_styles[style] = header_styles.get(style, 0) + 1 + discrepancy = archive.event_metadata[release_date].get( + "source_date_discrepancy" + ) + if discrepancy is not None: + source_date_discrepancies[release_date.isoformat()] = { + "archive_index_published_date": str( + archive.event_metadata[release_date][ + "archive_index_published_date" + ] + ), + "resolution": str(discrepancy), + } + dates = sorted(archive.clocks) + return { + "passed": True, + "directory": Path(directory).name, + "filename": source.name, + "bytes": source.stat().st_size, + "sha256": archive.evidence_sha256, + "official_url": BEA_GDP_CLOCK_INDEX_URL, + "event_count": len(dates), + "first_release_date": dates[0].isoformat(), + "last_release_date": dates[-1].isoformat(), + "release_type_counts": release_types, + "header_style_counts": header_styles, + "printed_timezone_counts": zones, + "source_date_discrepancy_count": len(source_date_discrepancies), + "source_date_discrepancies": source_date_discrepancies, + "all_header_hashes_unique": True, + "all_release_dates_weekdays_zones_verified": True, + "all_workbook_initial_release_dates_reconciled": True, + "all_release_times_0830_eastern": True, + "server_original_bytes_claimed": False, + "complete_dom_claimed": False, + "source_release_index_sha256": archive.source_release_index_sha256, + "retrieved_at": archive.retrieved_at, + } + + +__all__ = [ + "BEA_GDP_CLOCK_DIRECTORY", + "BEA_GDP_CLOCK_FILENAME", + "BEA_GDP_CLOCK_INDEX_URL", + "BEA_GDP_CLOCK_SOURCE", + "BEA_GDP_CLOCK_TIMING_QUALITY", + "BEAGDPClockArchive", + "BEAGDPClockArchiveError", + "BEAReleaseClock", + "audit_bea_gdp_clock_archive", + "parse_bea_gdp_clock_archive", + "parse_bea_release_header", +] diff --git a/Macroeconomics/src/macro_nowcast/bea_nipa_archive.py b/Macroeconomics/src/macro_nowcast/bea_nipa_archive.py new file mode 100644 index 0000000000000000000000000000000000000000..de34a199cdb85ba8843ea60461eb53a31df57125 --- /dev/null +++ b/Macroeconomics/src/macro_nowcast/bea_nipa_archive.py @@ -0,0 +1,1213 @@ +"""Acquire and audit BEA real-GDP level snapshots from the NIPA archive. + +The ordinary BEA API exposes current estimates, not historical as-of vintages. +This module instead uses BEA's public historical-data directory and downloads +only the Section 1 workbook published with each initial GDP release. Original +bytes, the evolving directory response, per-release file lists, hashes, archive +directory dates, and separately verified news-release clocks are retained. + +BEA changed workbook names, Excel formats, sheet names, series-code suffixes, +scale, and chained-dollar reference years across the archive. Consequently, +raw levels are never compared across release snapshots. The supported target +operation is the q/q SAAR ratio of two adjacent levels from the *same* snapshot. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import re +import shutil +import subprocess +import tempfile +import time +from collections import defaultdict +from collections.abc import Mapping, Sequence +from concurrent.futures import ThreadPoolExecutor, as_completed +from dataclasses import dataclass +from datetime import UTC, date, datetime, timedelta +from pathlib import Path +from typing import Final +from urllib.error import HTTPError, URLError +from urllib.parse import quote, urlencode +from urllib.request import Request, urlopen + +from macro_nowcast.archive_audit import _xlsx_rows, _xlsx_sheet_names +from macro_nowcast.bea_gdp_clock_archive import ( + BEA_GDP_CLOCK_TIMING_QUALITY, + BEAReleaseClock, + parse_bea_gdp_clock_archive, +) +from macro_nowcast.schema import VintageObservation + +BEA_NIPA_LEVEL_DIRECTORY: Final = "bea-nipa-levels" +BEA_NIPA_LEVEL_SOURCE: Final = "BEA_NIPA_HISTORICAL_RELEASE_ARCHIVE" +BEA_NIPA_LEVEL_SERIES_ID: Final = "GDPC1" +BEA_NIPA_LEVEL_PROVENANCE: Final = "official_agency_archive" +BEA_NIPA_ARCHIVE_INDEX_URL: Final = "https://apps.bea.gov/histdata/" +BEA_NIPA_RELEASE_INVENTORY_URL: Final = ( + "https://apps.bea.gov/histdata/core/data/Fea_DisplayChildrenC/" + "?HistMainId=7&getFiles=false&getDirs=true" +) +BEA_NIPA_FILE_INVENTORY_ENDPOINT: Final = ( + "https://apps.bea.gov/histdata/core/data/Fea_DisplayChildrenC/" +) +BEA_NIPA_PUBLIC_FILE_ROOT: Final = "https://apps.bea.gov" +BEA_NIPA_EXPECTED_FIRST_QUARTER: Final = "2002Q1" +BEA_NIPA_EXPECTED_LAST_QUARTER: Final = "2026Q2" +BEA_NIPA_DOCUMENTED_MISSING_QUARTERS: Final = ("2002Q1", "2002Q2") + +_SERVER_ROOT = "/Inetpub/wwwroot/website/website" +_USER_AGENT = "macro-nowcast-research/0.1 (public BEA NIPA archive verification)" +_OLE_SIGNATURE = bytes.fromhex("d0cf11e0a1b11ae1") +_RELEASE_PATH_RE = re.compile( + r"GDP_and_PI[\\\\/](?P20\d{2})[\\\\/]" + r"(?P[Qq][1-4])[\\\\/](?P