File size: 12,031 Bytes
6e1e6a7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 | """
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")
|