| """ |
| Build the METRO-level metro_mapping_clean.json for the clean pipeline. |
| |
| The benchmark v1 used CITY-level consolidation, which left commuter-belt |
| municipalities (Yokohama -> Tokyo, Suita -> Osaka, ...) as separate |
| "destinations". This produced ~14% phantom intra-metro travel records. |
| The clean pipeline uses METRO-level consolidation: any administrative entity |
| inside a known metropolitan area collapses to a single anchor QID. |
| |
| Sources: |
| 1) Existing metro_mapping_v2.json (carried through; only adds, never removes). |
| 2) Hand-curated METRO_DEFINITIONS giving each anchor metro and the cities, |
| districts and prefectures inside its commuter belt. Member QIDs are |
| drawn from Wikidata (verified by name lookup -- see _scripts/lookup_qids.txt). |
| 3) SPARQL P131+ descendants of each anchor (gathers any sub-municipal entity |
| reachable via "located in administrative entity" within the metro). |
| 4) Foursquare-internal "Q49xxxxxxx / Q27347xxx / Q35xxxxxxx" QIDs that lack |
| proper P131 chains -- explicitly listed below by raw_QID -> metro_QID. |
| |
| Output: cross_city_benchmark_clean/metro_mapping_clean.json |
| """ |
| from __future__ import annotations |
| import argparse, csv, json, time, collections |
| from pathlib import Path |
| from lib_wikidata import sparql, labels_batch |
|
|
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| METRO_DEFINITIONS: dict[str, dict] = { |
| |
| "Q1490": { |
| "name": "Tokyo (Greater Tokyo Area)", |
| "members": [ |
| "Q1490", |
| "Q308891", |
| "Q956318", |
| |
| "Q161176", |
| "Q281289", |
| "Q281254", |
| "Q235923", |
| "Q170204", |
| "Q277338", |
| "Q281286", |
| "Q220977", |
| "Q281295", |
| "Q220957", |
| "Q260106", |
| "Q160438", |
| "Q207601", |
| "Q263552", |
| "Q277331", |
| "Q275007", |
| "Q281324", |
| "Q277021", |
| "Q220962", |
| "Q207370", |
| "Q227773", |
| "Q281321", |
| "Q281332", |
| |
| "Q391093", |
| "Q486868", |
| "Q406798", |
| "Q486876", |
| "Q210667", |
| "Q1133105", |
| "Q317813", |
| "Q390788", |
| |
| "Q38283", |
| "Q201136", |
| "Q406798", |
| "Q461920", |
| "Q319330", |
| "Q277260", |
| "Q319737", |
| "Q1057611", |
| "Q132860", |
| |
| "Q205616", |
| "Q380049", |
| "Q425418", |
| "Q425556", |
| "Q390655", |
| "Q425481", |
| |
| "Q121054", |
| "Q319729", |
| "Q271417", |
| "Q487247", |
| "Q425556", |
| "Q486883", |
| "Q200988", |
| |
| "Q127513", |
| "Q128186", |
| "Q80011", |
| |
| "Q49295377", |
| "Q49369715", |
| "Q49369649", |
| "Q49371464", |
| "Q49371967", |
| "Q49371923", |
| "Q49371907", |
| "Q49371895", |
| "Q49371841", |
| "Q49371829", |
| "Q49371792", |
| "Q49371745", |
| |
| "Q35730142", |
| "Q35722099", |
| "Q386697", |
| "Q387136", |
| "Q273798", |
| "Q49371923", |
| |
| "Q49353821", |
| "Q49355990", |
| "Q49371464", |
| |
| |
| |
| |
| ], |
| }, |
|
|
| |
| "Q35765": { |
| "name": "Osaka (Keihanshin)", |
| "members": [ |
| "Q35765", |
| "Q122723", |
| "Q34600", |
| "Q120730", |
| |
| "Q130290", |
| "Q133054", |
| "Q187153", |
| "Q220655", |
| "Q725514", |
| "Q653510", |
| "Q49368443", |
| "Q231318", |
| "Q486398", |
| "Q499375", |
| "Q734474", |
| "Q200994", |
| "Q48320", |
| |
| "Q49368443", |
| ], |
| }, |
|
|
| |
| |
| "Q11751": { |
| "name": "Nagoya (Chukyo)", |
| "members": [ |
| "Q11751", |
| "Q80434", |
| "Q131277", |
| "Q128196", |
| "Q188996", |
| "Q486392", |
| "Q462000", |
| "Q462009", |
| "Q499390", |
| ], |
| }, |
|
|
| |
| "Q406": { |
| "name": "Istanbul", |
| "members": [ |
| "Q406", |
| "Q534799", |
| "Q326339", |
| "Q746516", |
| "Q1006881", |
| "Q49371964", |
| "Q179351", |
| |
| "Q3473299", |
| "Q1023876", |
| "Q1247058", |
| "Q1067075", |
| "Q1023901", |
| "Q605884", |
| "Q604919", |
| "Q1135036", |
| "Q1019002", |
| ], |
| }, |
|
|
| |
| "Q3640": { |
| "name": "Ankara", |
| "members": [ |
| "Q3640", |
| "Q2297724", |
| "Q3928674", |
| "Q608459", |
| "Q625728", |
| ], |
| }, |
|
|
| |
| "Q35997": { |
| "name": "İzmir", |
| "members": [ |
| "Q35997", |
| "Q344490", |
| "Q3123584", |
| "Q615098", |
| "Q615075", |
| "Q1190403", |
| ], |
| }, |
|
|
| |
| "Q35178": { |
| "name": "Kuwait City", |
| "members": [ |
| "Q35178", |
| "Q3235220", |
| "Q3495478", |
| "Q4704795", |
| "Q747432", |
| "Q372316", |
| "Q953508", |
| "Q185122", |
| "Q1057620", |
| "Q310948", |
| "Q83341", |
| "Q3221814", |
| "Q14708037", |
| "Q5894717", |
| |
| "Q27347020", |
| "Q27347063", |
| "Q27347142", |
| "Q1046645", |
| |
| "Q3505782", |
| "Q4120400", |
| "Q3495485", |
| "Q552354", |
| "Q1077024", |
| "Q405701", |
| ], |
| }, |
|
|
| |
| "Q1489": { |
| "name": "Mexico City", |
| "members": [ |
| "Q1489", |
| |
| "Q1502190", |
| "Q21509", |
| "Q161113", |
| "Q244366", |
| "Q205344", |
| ], |
| }, |
|
|
| |
| "Q13580": { |
| "name": "Metro Manila", |
| "members": [ |
| "Q13580", |
| "Q1461", |
| "Q1475", |
| "Q1508", |
| "Q9085", |
| "Q31475562", |
| "Q9248", |
| "Q12972", |
| "Q190482", |
| "Q47265", |
| "Q24856", |
| "Q31476", |
| "Q23681", |
| "Q161115", |
| "Q190428", |
| "Q31476", |
| ], |
| }, |
|
|
| |
| "Q174": { |
| "name": "São Paulo", |
| "members": [ |
| "Q174", |
| "Q175", |
| "Q201161", |
| "Q140714", |
| "Q188800", |
| "Q188820", |
| "Q188824", |
| "Q201161", |
| ], |
| }, |
|
|
| |
| "Q8678": { |
| "name": "Rio de Janeiro", |
| "members": [ |
| "Q8678", |
| "Q41428", |
| "Q188897", |
| "Q983459", |
| "Q186363", |
| "Q188867", |
| "Q189070", |
| "Q189158", |
| ], |
| }, |
|
|
| |
| "Q1861": { |
| "name": "Bangkok", |
| "members": [ |
| "Q1861", |
| "Q242932", |
| "Q475212", |
| "Q15199204", |
| "Q768864", |
| "Q205454", |
| "Q244408", |
| "Q244399", |
| ], |
| }, |
|
|
| |
| "Q84": { |
| "name": "London", |
| "members": [ |
| "Q84", |
| "Q179351", |
| |
| "Q201808", |
| "Q204022", |
| "Q205817", |
| "Q204008", |
| "Q204009", |
| "Q204008", |
| "Q207017", |
| "Q207018", |
| "Q207020", |
| "Q204010", |
| "Q205677", |
| "Q204023", |
| "Q204008", |
| "Q207016", |
| "Q207021", |
| "Q207022", |
| "Q207023", |
| "Q204023", |
| "Q204022", |
| ], |
| }, |
|
|
| |
| "Q60": { |
| "name": "New York City", |
| "members": [ |
| "Q60", |
| "Q11299", |
| "Q18424", |
| "Q18432", |
| "Q18426", |
| "Q18437", |
| |
| |
| ], |
| }, |
|
|
| |
| "Q1297": { |
| "name": "Chicago", |
| "members": ["Q1297"], |
| }, |
|
|
| |
| "Q1486": { |
| "name": "Buenos Aires", |
| "members": ["Q1486"], |
| }, |
|
|
| |
| "Q1865": { |
| "name": "Kuala Lumpur (Klang Valley)", |
| "members": [ |
| "Q1865", |
| "Q864965", |
| "Q2701266", |
| "Q189710", |
| "Q221275", |
| "Q815117", |
| |
| "Q864964", |
| "Q1018830", |
| "Q1018828", |
| "Q500033", |
| "Q2366087", |
| "Q4251470", |
| ], |
| }, |
|
|
| |
| "Q3692": { |
| "name": "Riyadh", |
| "members": [ |
| "Q3692", |
| "Q41475", |
| ], |
| }, |
|
|
| |
| "Q46747": { |
| "name": "Sendai", |
| "members": [ |
| "Q46747", |
| "Q47896", |
| ], |
| }, |
|
|
| |
| "Q37951": { |
| "name": "Sapporo", |
| "members": [ |
| "Q37951", |
| "Q1037393", |
| "Q1997315", |
| "Q49295332", |
| "Q693237", |
| ], |
| }, |
|
|
| |
| "Q26600": { |
| "name": "Fukuoka", |
| "members": [ |
| "Q26600", |
| "Q123258", |
| "Q49295241", |
| ], |
| }, |
| } |
|
|
|
|
| |
| |
| DO_NOT_MERGE: set[str] = { |
| |
| |
| "Q49295248", |
| "Q49355990", |
| "Q49353249", |
| "Q49353821", |
| "Q49755161", |
| |
| "Q132894", |
| "Q1392079", |
| "Q21", |
| "Q26952", |
| "Q1190403", |
| "Q953508", |
| } |
|
|
| |
|
|
| def step(t0, msg): |
| print(f"[{time.time()-t0:6.1f}s] {msg}", flush=True) |
|
|
|
|
| def enumerate_raw_cities(raw_csv: Path, min_ci: int) -> list[tuple[str, int]]: |
| counter: collections.Counter[str] = collections.Counter() |
| with raw_csv.open() as f: |
| rd = csv.DictReader(f) |
| for row in rd: |
| v = row.get("venue_city") |
| if v: |
| counter[v] += 1 |
| big = [(q.replace("wd:", ""), n) for q, n in counter.items() if n >= min_ci] |
| big.sort(key=lambda x: -x[1]) |
| return big |
|
|
|
|
| def discover_p131_descendants(anchor_qid: str, max_results: int = 100000) -> set[str]: |
| """Return all entities reachable as wdt:P131+ wd:<anchor>.""" |
| q = f""" |
| SELECT ?desc WHERE {{ |
| ?desc wdt:P131+ wd:{anchor_qid} . |
| }} LIMIT {max_results} |
| """ |
| try: |
| rows = sparql(q) |
| return {r["desc"]["value"].rsplit("/", 1)[-1] for r in rows} |
| except Exception as e: |
| print(f" P131+ for {anchor_qid} failed: {e}") |
| return set() |
|
|
|
|
| |
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--raw", default="/scratch/peibo/RQ3/Data/data/raw/std_2018.csv") |
| ap.add_argument("--out", default="/scratch/peibo/RQ3/Data/data/processed/cross_city_benchmark_clean/metro_mapping_clean.json") |
| ap.add_argument("--existing", default="/scratch/peibo/RQ3/Data/data/processed/metro_mapping_v2.json") |
| ap.add_argument("--min-checkins", type=int, default=50, |
| help="discover descendants of anchors only for raw QIDs above this CI threshold") |
| ap.add_argument("--use-sparql", action="store_true", default=True, |
| help="enable SPARQL P131+ descendant discovery for each anchor metro") |
| args = ap.parse_args() |
|
|
| out_path = Path(args.out) |
| out_path.parent.mkdir(parents=True, exist_ok=True) |
| t0 = time.time() |
|
|
| |
| step(t0, f"loading existing {args.existing}") |
| existing = json.load(open(args.existing)) |
| base_map: dict[str, str] = dict(existing.get("metro_map", {})) |
| base_labels: dict[str, str] = dict(existing.get("labels", {})) |
| step(t0, f" v2 has {len(base_map):,} entries ({sum(1 for k,v in base_map.items() if k!=v):,} non-identity)") |
|
|
| |
| step(t0, f"enumerating raw venue_city QIDs (>= {args.min_checkins} CIs)") |
| big = enumerate_raw_cities(Path(args.raw), args.min_checkins) |
| raw_qids = {q for q, _ in big} |
| step(t0, f" {len(raw_qids):,} raw QIDs to consider") |
|
|
| |
| step(t0, "applying METRO_DEFINITIONS (hand-curated)") |
| metro_map = {q: q for q in raw_qids} |
| metro_map.update(base_map) |
|
|
| n_added_manual = 0 |
| for anchor, defn in METRO_DEFINITIONS.items(): |
| for member in defn["members"]: |
| if member in DO_NOT_MERGE: |
| continue |
| if member == anchor: |
| continue |
| if metro_map.get(member) != anchor: |
| metro_map[member] = anchor |
| n_added_manual += 1 |
| |
| |
| |
| |
| all_anchors = set(METRO_DEFINITIONS.keys()) |
| for anchor in all_anchors: |
| metro_map[anchor] = anchor |
| step(t0, f" added/updated {n_added_manual:,} curated mappings; " |
| f"forced {len(all_anchors):,} anchors to identity") |
|
|
| |
| if args.use_sparql: |
| step(t0, "discovering SPARQL P131+ descendants of each anchor") |
| n_added_sparql = 0 |
| for anchor, defn in METRO_DEFINITIONS.items(): |
| descs = discover_p131_descendants(anchor) |
| for d in descs: |
| if d in DO_NOT_MERGE: |
| continue |
| if d == anchor: |
| continue |
| |
| |
| if d in raw_qids and metro_map.get(d, d) == d: |
| metro_map[d] = anchor |
| n_added_sparql += 1 |
| step(t0, f" {anchor} ({defn['name']}): {len(descs):,} descendants found, " |
| f"{sum(1 for d in descs if d in raw_qids):,} matched raw QIDs") |
| step(t0, f" added {n_added_sparql:,} SPARQL-discovered mappings") |
|
|
| |
| n_forced = 0 |
| for q in DO_NOT_MERGE: |
| if q in metro_map and metro_map[q] != q: |
| metro_map[q] = q |
| n_forced += 1 |
| step(t0, f" forced {n_forced:,} DO_NOT_MERGE QIDs back to identity") |
|
|
| |
| step(t0, "computing transitive closure") |
| def resolve(q): |
| seen = {q} |
| while metro_map.get(q, q) != q and metro_map[q] not in seen: |
| q = metro_map[q] |
| seen.add(q) |
| return q |
| metro_map = {k: resolve(k) for k in metro_map} |
|
|
| rewritten = sum(1 for k, v in metro_map.items() if k != v) |
| targets = set(metro_map.values()) |
| step(t0, f" total: {len(metro_map):,} entries, {rewritten:,} rewrites, " |
| f"{len(targets):,} distinct metro targets") |
|
|
| |
| step(t0, "fetching labels for all sources + targets") |
| label_map = dict(base_labels) |
| universe = set(metro_map.keys()) | set(metro_map.values()) |
| missing = sorted(q for q in universe if q not in label_map or not label_map[q]) |
| if missing: |
| step(t0, f" fetching {len(missing):,} missing labels (batched)") |
| label_map.update(labels_batch(missing)) |
|
|
| |
| out = { |
| "metro_map": metro_map, |
| "labels": label_map, |
| "build_log": { |
| "raw_csv": args.raw, |
| "min_checkins": args.min_checkins, |
| "raw_qids_considered": len(raw_qids), |
| "rewritten_qids": rewritten, |
| "distinct_metro_targets": len(targets), |
| "metro_definitions": {a: d["name"] for a, d in METRO_DEFINITIONS.items()}, |
| "do_not_merge": sorted(DO_NOT_MERGE), |
| }, |
| } |
| out_path.write_text(json.dumps(out, ensure_ascii=False, indent=2)) |
| step(t0, f"wrote {out_path} ({out_path.stat().st_size/1024:.1f} KB)") |
|
|
| |
| print("\nTop 20 raw QIDs and their metro assignment:") |
| print(f" {'qid':10s} {'raw_label':25s} {'->target':10s} target_label") |
| for q, n in big[:20]: |
| target = metro_map.get(q, q) |
| rl = label_map.get(q, '?')[:25] |
| tl = label_map.get(target, '?')[:25] |
| print(f" {q:10s} {rl:25s} -> {target:10s} {tl} ({n:,} CIs)") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|