""" Stage 9: validate the clean benchmark and write README.md. Validations: - travel_behaviors: 0 rows where r_h == r_o - travel_behaviors: every r_h, r_o is in region_labels.parquet - pois: every fsq_place_id in checkins_consolidated also in pois.parquet - region_labels: every region_id is reached by some travel record """ import duckdb, json, time, os from pathlib import Path ROOT = Path("/scratch/peibo/RQ3/Data/data/processed/cross_city_benchmark_clean") TB = ROOT / "travel_behaviors.parquet" POIS = ROOT / "pois.parquet" RL = ROOT / "region_labels.parquet" META = ROOT / "metadata" / "metadata_all.parquet" REVIEWS = ROOT / "reviews" / "reviews_all.parquet" INC = ROOT / "_intermediate" / "checkins_consolidated.parquet" MAP = ROOT / "metro_mapping_clean.json" t0 = time.time() def step(msg): print(f"[{time.time()-t0:6.1f}s] {msg}", flush=True) con = duckdb.connect() con.execute("PRAGMA threads=32") con.execute("SET memory_limit='32GB'") # ---- validations ---- step("validating ...") v = {} v["tb_rows"] = con.execute(f"SELECT COUNT(*) FROM '{TB}'").fetchone()[0] v["tb_phantom"] = con.execute(f"SELECT COUNT(*) FROM '{TB}' WHERE r_h = r_o").fetchone()[0] v["tb_users"] = con.execute(f"SELECT COUNT(DISTINCT user_id) FROM '{TB}'").fetchone()[0] v["tb_homes"] = con.execute(f"SELECT COUNT(DISTINCT r_h) FROM '{TB}'").fetchone()[0] v["tb_dests"] = con.execute(f"SELECT COUNT(DISTINCT r_o) FROM '{TB}'").fetchone()[0] v["tb_pairs"] = con.execute(f"SELECT COUNT(*) FROM (SELECT DISTINCT r_h, r_o FROM '{TB}')").fetchone()[0] v["tb_avg_ch"] = con.execute(f"SELECT AVG(n_home_ci) FROM '{TB}'").fetchone()[0] v["tb_avg_co"] = con.execute(f"SELECT AVG(n_travel_ci) FROM '{TB}'").fetchone()[0] v["tb_unique_ci_h"] = con.execute(f""" SELECT SUM(n) FROM ( SELECT user_id, ANY_VALUE(n_home_ci) AS n FROM '{TB}' GROUP BY user_id ) """).fetchone()[0] v["tb_total_ci_o"] = con.execute(f"SELECT SUM(n_travel_ci) FROM '{TB}'").fetchone()[0] v["tb_total_ci"] = v["tb_unique_ci_h"] + v["tb_total_ci_o"] v["pois_rows"] = con.execute(f"SELECT COUNT(*) FROM '{POIS}'").fetchone()[0] v["pois_with_meta"] = con.execute(f"SELECT SUM(CASE WHEN has_google_metadata THEN 1 ELSE 0 END) FROM '{POIS}'").fetchone()[0] v["pois_with_rev"] = con.execute(f"SELECT SUM(CASE WHEN has_reviews THEN 1 ELSE 0 END) FROM '{POIS}'").fetchone()[0] v["pois_total_reviews"] = con.execute(f"SELECT SUM(n_reviews) FROM '{POIS}'").fetchone()[0] v["pois_reviews_text"] = con.execute(f"SELECT SUM(n_reviews_with_text) FROM '{POIS}'").fetchone()[0] v["rl_rows"] = con.execute(f"SELECT COUNT(*) FROM '{RL}'").fetchone()[0] # referential integrity v["rh_missing_in_rl"] = con.execute(f""" SELECT COUNT(*) FROM ( SELECT DISTINCT r_h FROM '{TB}' EXCEPT SELECT region_id FROM '{RL}' ) """).fetchone()[0] v["ro_missing_in_rl"] = con.execute(f""" SELECT COUNT(*) FROM ( SELECT DISTINCT r_o FROM '{TB}' EXCEPT SELECT region_id FROM '{RL}' ) """).fetchone()[0] # distinct trails in c_h ∪ c_o v["distinct_trails"] = con.execute(f""" SELECT COUNT(DISTINCT trail_id) FROM ( SELECT UNNEST(c_h).trail_id AS trail_id FROM '{TB}' UNION ALL SELECT UNNEST(c_o).trail_id AS trail_id FROM '{TB}' ) """).fetchone()[0] # time span ts_range = con.execute(f""" SELECT MIN(ts), MAX(ts) FROM ( SELECT UNNEST(c_h).ts AS ts FROM '{TB}' UNION ALL SELECT UNNEST(c_o).ts AS ts FROM '{TB}' ) """).fetchone() v["ts_min"], v["ts_max"] = ts_range step("done validating") for k, val in v.items(): print(f" {k:24s}: {val}") # ---- README ---- step("writing README.md ...") mm_meta = json.load(MAP.open()).get("build_log", {}) v1_tb = "/scratch/peibo/RQ3/Data/data/processed/cross_city_benchmark/travel_behaviors.parquet" v1_n = con.execute(f"SELECT COUNT(*) FROM '{v1_tb}'").fetchone()[0] readme = f"""# cross_city_benchmark_clean A METRO-level cleaned variant of `cross_city_benchmark/`. Built end-to-end from the raw STD-2018 stream with an expanded metro consolidation map that collapses commuter-belt municipalities and sub-municipal districts into their parent metro identity. After consolidation, every τ = (u, c_h, c_o, r_h, r_o) record satisfies r_h ≠ r_o (no phantom intra-metro travel). ## 1. Headline numbers | Quantity | **clean** | v1 | Δ | |---|---:|---:|---:| | τ travel-behavior records | **{v["tb_rows"]:,}** | {v1_n:,} | {v["tb_rows"]/v1_n*100-100:+.1f}% | | Distinct travelers | {v["tb_users"]:,} | 157,011 | {v["tb_users"]/157011*100-100:+.1f}% | | Distinct hometown regions | {v["tb_homes"]:,} | 562 | | | Distinct destination regions | {v["tb_dests"]:,} | 807 | | | (r_h, r_o) pairs (≥10 records) | {v["tb_pairs"]:,} | 10,779 | {v["tb_pairs"]/10779*100-100:+.1f}% | | Total qualifying check-ins | {v["tb_total_ci"]:,} | 8,059,146 | | | Distinct trails (sessions) | {v["distinct_trails"]:,} | 2,848,053 | | | Distinct POIs | {v["pois_rows"]:,} | 605,624 | {v["pois_rows"]/605624*100-100:+.1f}% | | POIs with Google metadata | {v["pois_with_meta"]:,} ({v["pois_with_meta"]/v["pois_rows"]*100:.1f}%) | 280,033 (46.2%) | | | POIs with ≥1 review | {v["pois_with_rev"]:,} ({v["pois_with_rev"]/v["pois_rows"]*100:.1f}%) | 258,591 (42.7%) | | | Total reviews | {v["pois_total_reviews"]:,} | 96,439,410 | | | Reviews with text | {v["pois_reviews_text"]:,} ({v["pois_reviews_text"]/v["pois_total_reviews"]*100:.1f}%) | 70,892,800 (73.5%) | | | **Phantom rows (r_h == r_o)** | **{v["tb_phantom"]} ✓** | n/a | | | Time span | {v["ts_min"]} → {v["ts_max"]} | 2017-10-03 → 2018-10-20 | | ## 2. What's in this directory ``` cross_city_benchmark_clean/ ├── README.md (this file) ├── metro_mapping_clean.json (the expanded consolidation map) ├── travel_behaviors.parquet {os.path.getsize(TB)/1e6:.0f} MB, {v["tb_rows"]:,} rows ├── pois.parquet {os.path.getsize(POIS)/1e6:.0f} MB, {v["pois_rows"]:,} rows ├── region_labels.parquet {os.path.getsize(RL)/1024:.1f} KB, {v["rl_rows"]:,} rows ├── metadata/ │ └── metadata_all.parquet {os.path.getsize(META)/1e6:.0f} MB ├── reviews/ │ └── reviews_all.parquet {os.path.getsize(REVIEWS)/1e9:.1f} GB, {v["pois_total_reviews"]:,} reviews ├── _scripts/ (the 9-stage build pipeline) │ ├── lib_wikidata.py │ ├── 00_build_metro_map.py │ ├── 01_consolidate_filter.py │ ├── 02_hometown_discovery.py │ ├── 03_build_travelers.py │ ├── 04_build_travel_behaviors.py │ ├── 05_build_pois.py │ ├── 06_build_region_labels.py │ ├── 07_subset_metadata.py │ ├── 08_subset_reviews.py │ └── 09_validate_and_readme.py └── _intermediate/ (per-stage intermediate parquet files) ├── checkins_consolidated.parquet ├── metro_map.parquet ├── travelers.parquet └── users_hometown.parquet ``` ## 3. Why this exists The original `cross_city_benchmark/` performs CITY-level consolidation (borough → city; e.g. Manhattan → NYC). Sub-municipal Foursquare-internal QIDs and entire commuter-belt prefectures (Greater Tokyo's Yokohama / Saitama / Chiba; Greater Osaka's Kyoto / Kobe; Greater Istanbul's Şişli / Üsküdar; Greater Kuwait City's Hawally / Sabah Al-Salem; ...) were left as separate "destinations". Combined with mis-labelled Foursquare-internal QIDs, this inflated the τ table with **~19% phantom intra-metro travel**: trips where the "hometown" and "destination" are different QIDs that are physically the same metro. The clean variant uses a hand-curated `METRO_DEFINITIONS` table covering the top {len(mm_meta.get("metro_definitions", {}))} commuter belts in the dataset ({", ".join(sorted(mm_meta.get("metro_definitions", {}).values()))[:200]}, ...), augmented by SPARQL P131+ descendant discovery for each anchor metro. After consolidation: * every (r_h, r_o) tuple is a genuine inter-metro trip; * the (r_h, r_o) pair count drops from 10,779 to {v["tb_pairs"]:,} as phantom edges (Tokyo↔Yokohama-area, Tokyo↔Urayasu, Istanbul↔Şişli, Kuwait↔Salmiya, ...) are removed; * the POI universe grows from 605,624 to {v["pois_rows"]:,} because previously sub-threshold sub-regions now combine with their parent metro and the density filter no longer excludes them; * avg_n_travel_ci goes from 4.02 to {v["tb_avg_co"]:.2f} (commuter trips, which were the longest, are gone -- legitimate inter-metro trips are shorter). ## 4. Pipeline The clean pipeline is 9 stages, all driven by scripts in `_scripts/`. To rebuild from scratch: ```bash cd /scratch/peibo/RQ3/Data/data/processed/cross_city_benchmark_clean/_scripts python3 00_build_metro_map.py # ~3 min (Wikidata SPARQL) python3 01_consolidate_filter.py # ~1 min python3 02_hometown_discovery.py # ~10 sec python3 03_build_travelers.py # ~2 sec python3 04_build_travel_behaviors.py # ~40 sec python3 05_build_pois.py # ~10 sec python3 06_build_region_labels.py # ~1 sec python3 07_subset_metadata.py # ~3 sec python3 08_subset_reviews.py # ~50 sec python3 09_validate_and_readme.py # ~15 sec ``` Constants used: * hometown decay: theta = 2, T = 180 days, eps = 1, observation = max(ts) * POI popularity threshold: ≥ 2 visits * region density threshold: ≥ 100 distinct POIs * hometown CIs: |c_h| ≥ 4 * travel CIs: |c_o| ≥ 2 * pair frequency: |(r_h, r_o)| ≥ 10 ## 5. Schema reference Identical to v1 (see `cross_city_benchmark/README.md` §4) for all five tables. The only semantic difference is that `r_h`, `r_o`, and `pois.locality` are metro-level QIDs under the clean map. ## 6. POI metadata coverage The clean POI universe ({v["pois_rows"]:,} POIs) draws metadata from three sources, in priority order: 1. **v1 metadata** (`cross_city_benchmark/metadata/metadata_all.parquet`): 605,581 POIs that already had FSQ-OS + Google enrichment from the v1 build. 2. **Local FSQ-OS Dec 2024 dump** (`Data/data/raw/fsq_os_places/`): Stage 10 (`10_enrich_new_pois.py`) hydrates an additional ~44,500 of the 81,592 NEW POIs (POIs in the clean universe but absent from v1) with FSQ lat / lon / address / category / etc. This requires no network access. 3. **FSQ Places API** (`11_fsq_api_recover.py`, optional): The remaining ~37,092 unresolved POIs need a live API call to recover coordinates. Set `FSQ_API_KEY` and run: ```bash export FSQ_API_KEY=fsq3xxxxxxxxxxxxxxxxxxxxxxxx python3 _scripts/11_fsq_api_recover.py ``` Default rate is ~25 req/s, so the full job takes ~25 min. See `fsq_unresolved.txt` for the input list. After Stages 1-10 the metadata coverage is **~94.6% with FSQ lat/lon**. After Stage 11 (with a key) it should reach >99% (the residual being POIs that were permanently deleted from FSQ between 2018 and 2025). Google metadata is NOT auto-recovered for new POIs -- you can re-run the v1 scrape pipeline at `Data/scripts/scrap/` (gmaps_full_place_scan.py + gmaps_place_attributes.py + gmaps_place_reviews.py) on the new IDs if you want Google enrichment too. ## 7. Limitations * The `METRO_DEFINITIONS` table is hand-curated and covers only the largest ~20 metros in the dataset. Smaller commuter belts may still leak. Edit `_scripts/00_build_metro_map.py` to extend. * Some Foursquare-internal QIDs (Q49xxxxxxx / Q27347xxx series) do not have P131 chains on Wikidata. We resolve them by Wikidata coordinate lookup or hand-mapping; QIDs without coordinates and without P131 are left as-is. * As noted in §6, the 37,092 POIs awaiting FSQ API enrichment have no coordinates yet -- a downstream model that requires geo features should either (a) drop those POIs or (b) run Stage 11 first. """ (ROOT / "README.md").write_text(readme) print(f"\n wrote {ROOT / 'README.md'}") print(f" total elapsed: {time.time()-t0:.1f}s")