neolifer commited on
Commit
3befc7c
·
verified ·
1 Parent(s): f3f42aa

Upload folder using huggingface_hub

Browse files
MANIFEST.json ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset": "Trip World",
3
+ "generated_at": "2026-05-05T22:28:45.365895+00:00",
4
+ "files": [
5
+ {
6
+ "path": "README.md",
7
+ "size_bytes": 23469,
8
+ "sha256": "9ddd2b7a87a6eab02615519a6b700752fb7800740fb96f89d0813db24a6d9a91"
9
+ },
10
+ {
11
+ "path": "_scripts/00_build_metro_map.py",
12
+ "size_bytes": 25849,
13
+ "sha256": "cd7f25a0516edb421e81636e37a9fa8a55584fa2ed06fed3c12ac1773ed03567"
14
+ },
15
+ {
16
+ "path": "_scripts/01_consolidate_filter.py",
17
+ "size_bytes": 5289,
18
+ "sha256": "0e5c3a29c2df1f08aceccc686b2892a4ab120e161ed2e373d446241f095ae765"
19
+ },
20
+ {
21
+ "path": "_scripts/02_hometown_discovery.py",
22
+ "size_bytes": 3580,
23
+ "sha256": "748ae827e6136e4d8fe19e335112ba035bd9424a5464b4c2e40bfa00da39716d"
24
+ },
25
+ {
26
+ "path": "_scripts/03_build_travelers.py",
27
+ "size_bytes": 3582,
28
+ "sha256": "a8ef6b5a7da35480a7b5f4ec4cb3faea06117133a37b8e3496dffbc5a934979f"
29
+ },
30
+ {
31
+ "path": "_scripts/04_build_travel_behaviors.py",
32
+ "size_bytes": 3277,
33
+ "sha256": "7c2e64df23a33a9053b1b51c429c3505c2b3fb76f7d80532a268528ee770a1b0"
34
+ },
35
+ {
36
+ "path": "_scripts/05_build_pois.py",
37
+ "size_bytes": 3711,
38
+ "sha256": "92ef5f7521cfe2ca39d7ac17ec4d42599f77cd0de00e50b856c6dedcbae69a6c"
39
+ },
40
+ {
41
+ "path": "_scripts/06_build_region_labels.py",
42
+ "size_bytes": 2681,
43
+ "sha256": "b83f1644e2e8ac811f1f4cf4ffdedd77fbb5590a8fb043d4f7ab9f2d63397f8b"
44
+ },
45
+ {
46
+ "path": "_scripts/07_subset_metadata.py",
47
+ "size_bytes": 1459,
48
+ "sha256": "a5d879b4c71babeb58b2f0a0440cb178393389c495a49d0812832ffb0009caa6"
49
+ },
50
+ {
51
+ "path": "_scripts/08_subset_reviews.py",
52
+ "size_bytes": 1998,
53
+ "sha256": "abb67be5115a05bd6eb7808517dd72df1107404866ddeb77c87c361d8a6cb794"
54
+ },
55
+ {
56
+ "path": "_scripts/09_validate.py",
57
+ "size_bytes": 3835,
58
+ "sha256": "789c0b79340539b003e55c0473bc62a7060a0eb15fb52870cad9f73781eea735"
59
+ },
60
+ {
61
+ "path": "_scripts/10_enrich_new_pois.py",
62
+ "size_bytes": 6970,
63
+ "sha256": "72f591ae9991ca02e847355308466f5a1a92825d23795adec9acbec5b364c13b"
64
+ },
65
+ {
66
+ "path": "_scripts/11_fsq_api_recover.py",
67
+ "size_bytes": 16289,
68
+ "sha256": "130cb8a98764e1bf84dcc3b00a4e94a5e63026276d16f78d816567b60772c4e4"
69
+ },
70
+ {
71
+ "path": "_scripts/12_ucsd_bridge.py",
72
+ "size_bytes": 14575,
73
+ "sha256": "6a0744ca1623294f0e0534edd0233e98b6b3e6522f0cd00a6e5fcf12b0037b9c"
74
+ },
75
+ {
76
+ "path": "_scripts/13_merge_ucsd_into_metadata.py",
77
+ "size_bytes": 6356,
78
+ "sha256": "939ab7cf2ab06762923d8cd76a9066ddcc14d4b02b3b1124fecc70ecbec2922b"
79
+ },
80
+ {
81
+ "path": "_scripts/14_merge_gcp_search_results.py",
82
+ "size_bytes": 12310,
83
+ "sha256": "25befa67bbd7d9108f93b1436b11c2fe1b38ebf81f98cc63f0c60b1ace111a82"
84
+ },
85
+ {
86
+ "path": "_scripts/15_merge_stage2_reviews.py",
87
+ "size_bytes": 7847,
88
+ "sha256": "fb3930ea05174d6508f42076055a4637e9553dd39a63edae213d6df19daa84cc"
89
+ },
90
+ {
91
+ "path": "_scripts/16_unify_reviews.py",
92
+ "size_bytes": 7196,
93
+ "sha256": "480bb93e479580cecdb18d3eaa2d6cd32ab755028228d9b3ebae3bbef2229d55"
94
+ },
95
+ {
96
+ "path": "_scripts/lib_wikidata.py",
97
+ "size_bytes": 5360,
98
+ "sha256": "9fb66e3aca1516e14693fa5f1f66e879f389c8ce22514e9edad6ebcc8deb4531"
99
+ },
100
+ {
101
+ "path": "_scripts/viz_clean_raw.py",
102
+ "size_bytes": 22248,
103
+ "sha256": "24a730d7bd73a536bc14f3c3cfc03dac45823dc505bfd8bd2107c75a2d186f54"
104
+ },
105
+ {
106
+ "path": "_scripts/viz_traj_length.py",
107
+ "size_bytes": 3993,
108
+ "sha256": "3e57d0a39ff9055f14c07a04b73359a9065dd8d3f0bbf3c0d51c597e8a9e3445"
109
+ },
110
+ {
111
+ "path": "metadata/metadata_all.parquet",
112
+ "size_bytes": 119796103,
113
+ "sha256": "20c8affe6092df1202074e4458672a57e77d96505ede4fb63fa65b0b3d0b22d3",
114
+ "rows": 687173
115
+ },
116
+ {
117
+ "path": "metadata/place_attributes.parquet",
118
+ "size_bytes": 5580621,
119
+ "sha256": "4c31fda0a865c6773ff4067bb20ebd16c2ffde8925ded0da3b26d322d942c3b8",
120
+ "rows": 28776
121
+ },
122
+ {
123
+ "path": "metro_mapping_clean.json",
124
+ "size_bytes": 410138,
125
+ "sha256": "53086b8988147692f8e649f4df5c96b914cfe1b5c3c52f9d90807190b404066b"
126
+ },
127
+ {
128
+ "path": "pois.parquet",
129
+ "size_bytes": 69707931,
130
+ "sha256": "43c3d385700ca050bb1b109ab98481dddce85150b4a8f1cc455fa4994b8f3f0e",
131
+ "rows": 687173
132
+ },
133
+ {
134
+ "path": "region_labels.parquet",
135
+ "size_bytes": 19217,
136
+ "sha256": "98134206f3ae04366de219e181380a5c9c302873391ccc9109fa491fe9f11c59",
137
+ "rows": 1173
138
+ },
139
+ {
140
+ "path": "reviews/reviews_all.parquet",
141
+ "size_bytes": 23400867153,
142
+ "sha256": "60aa08489743419a26475a842398040dfdc9a508572cb51aa19e864966f10a7c",
143
+ "rows": 186760186
144
+ },
145
+ {
146
+ "path": "travel_behaviors.parquet",
147
+ "size_bytes": 151509028,
148
+ "sha256": "59d473611daca78404fda149832012562e11469cd0339094c92d2f86d4655034",
149
+ "rows": 518567
150
+ }
151
+ ]
152
+ }
README.md CHANGED
@@ -1,3 +1,521 @@
1
- ---
2
- license: cc-by-nc-4.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: Trip World
3
+ license: cc-by-nc-4.0
4
+ license_name: trip-world-noncommercial
5
+ license_link: LICENSE
6
+ language:
7
+ - en
8
+ - ja
9
+ - tr
10
+ - ms
11
+ - pt
12
+ - th
13
+ - es
14
+ - multilingual
15
+ multilinguality:
16
+ - multilingual
17
+ size_categories:
18
+ - 100M<n<1B
19
+ task_categories:
20
+ - text-classification
21
+ - text-retrieval
22
+ - summarization
23
+ - other
24
+ task_ids:
25
+ - sentiment-classification
26
+ - multi-class-classification
27
+ tags:
28
+ - POI
29
+ - trajectory-recommendation
30
+ - next-location-prediction
31
+ - check-ins
32
+ - mobility
33
+ - tourism
34
+ - cross-city
35
+ - foursquare
36
+ - google-maps
37
+ - reviews
38
+ annotations_creators:
39
+ - machine-generated
40
+ - found
41
+ language_creators:
42
+ - found
43
+ source_datasets:
44
+ - extended
45
+ configs:
46
+ - config_name: travel_behaviors
47
+ data_files: travel_behaviors.parquet
48
+ - config_name: pois
49
+ data_files: pois.parquet
50
+ - config_name: regions
51
+ data_files: region_labels.parquet
52
+ - config_name: metadata
53
+ data_files: metadata/metadata_all.parquet
54
+ - config_name: place_attributes
55
+ data_files: metadata/place_attributes.parquet
56
+ - config_name: reviews
57
+ data_files: reviews/reviews_all.parquet
58
+ ---
59
+
60
+ # Trip World
61
+
62
+ **Trip World** is a publicly redistributable, METRO-level cross-city travel
63
+ benchmark. It pairs a large corpus of out-of-town travel sequences with
64
+ rich Foursquare and Google Maps point-of-interest (POI) metadata and an
65
+ unified Google reviews corpus. The dataset is designed to support:
66
+
67
+ - **Trajectory recommendation** — recommend a sequence of POIs in an
68
+ unfamiliar city, given the traveller's home-city behaviour and a
69
+ desired start / end / length.
70
+ - **Cross-city POI ranking and next-POI prediction** — score POIs in a
71
+ destination region by likelihood for an out-of-town visitor.
72
+ - **Place modelling** — text/category/sentiment work driven by 186 M
73
+ Google reviews and structured FSQ + Google attributes for 687 K POIs.
74
+ - **Tourism and mobility analytics** — aggregate analyses of travel
75
+ flows between 1,173 cities in 90+ countries.
76
+
77
+ The release is built on top of the STD-2018 check-in stream, with metro-
78
+ consolidation, hometown discovery, traveller filtering, and POI
79
+ enrichment applied; see *Provenance* below for the exact pipeline.
80
+
81
+
82
+ ## Headline statistics
83
+
84
+ | Quantity | Value |
85
+ |------------------------------------------------|---------------:|
86
+ | Travel-behavior records (τ) | **518,567** |
87
+ | Distinct travellers | **148,402** |
88
+ | Hometown regions / destination regions | 723 / 1,165 |
89
+ | Distinct (hometown → destination) pairs | 6,246 |
90
+ | Qualifying check-ins | 7,416,219 |
91
+ | Distinct trails (sessions) | 2,723,551 |
92
+ | Distinct POIs | 687,173 |
93
+ | POIs with Google metadata | 309,941 (45%) |
94
+ | POIs with ≥ 1 review | 285,693 (42%) |
95
+ | Total reviews | **186,760,186**|
96
+ | POIs with extra place attributes (desc / hours / price) | 28,776 |
97
+ | Distinct cities (Wikidata QIDs) | 1,173 |
98
+ | Time span | 2017-10-03 — 2018-10-20 |
99
+
100
+ Geographic coverage is strongest in East Asia and the Mediterranean
101
+ (Japan, Turkey, Malaysia, USA, Brazil, Thailand, Mexico, Philippines …).
102
+ See the figures bundled with the source repository for breakdowns.
103
+
104
+
105
+ ## Definitions
106
+
107
+ A **travel-behavior record** captures one traveller's activity around
108
+ one out-of-town destination. Following the dataset's formal definition,
109
+ each τ record is a five-tuple
110
+
111
+ > τ = (u, c_h, c_o, r_h, r_o)
112
+
113
+ with the following components:
114
+
115
+ | Symbol | Meaning |
116
+ |--------|---------------------------------------------------------------|
117
+ | `u` | the traveller (anonymous integer ID, 1..148,402) |
118
+ | `r_h` | their identified hometown region (Wikidata city QID) |
119
+ | `r_o` | the out-of-town destination region (Wikidata city QID) |
120
+ | `c_h` | the traveller's check-in stream **at home** around this trip |
121
+ | `c_o` | the traveller's check-in stream **at the destination** |
122
+
123
+ `c_h` and `c_o` are sequences of `(trail_id, venue_id, venue_category,
124
+ venue_schema, ts)` records. Each `trail_id` identifies a single
125
+ contiguous session of check-ins (one "trajectory" in the trajectory-
126
+ recommendation sense); a single τ record may contain several distinct
127
+ trails on each side because the same traveller can have multiple home
128
+ sessions and multiple visits to the same destination.
129
+
130
+ A **POI** is identified by a Foursquare place ID
131
+ (`foursquare:<24-hex>`). Each POI is annotated with a Wikidata-QID
132
+ locality (the city it belongs to), a Foursquare venue category, a
133
+ schema.org venue type, and (for ~45 % of POIs) the corresponding Google
134
+ Maps CID and rich Google metadata.
135
+
136
+
137
+ ## Layout
138
+
139
+ ```
140
+ trip_world/
141
+ ├── README.md (this file)
142
+ ├── MANIFEST.json — file list with sizes, sha256, and row counts
143
+ ├── metro_mapping_clean.json — metro consolidation map (municipality QID → parent metro QID)
144
+ ├── travel_behaviors.parquet — 518,567 τ records
145
+ ├── pois.parquet — 687,173 POI summaries (per-POI usage stats + flat google_*)
146
+ ├── region_labels.parquet — 1,173 (region_id → city name + country)
147
+ ├── metadata/
148
+ │ ├── metadata_all.parquet — 687,173 rows; full Foursquare + Google metadata per POI
149
+ │ └── place_attributes.parquet — 28,776 rows; description / hours / price for the most enriched POIs
150
+ ├── reviews/
151
+ │ └── reviews_all.parquet — 186,760,186 unified Google reviews
152
+ └── _scripts/ — full build-pipeline source code (reproduces the dataset)
153
+ ```
154
+
155
+
156
+ ## Schema (column reference)
157
+
158
+ ### `travel_behaviors.parquet` (518,567 rows)
159
+
160
+ | Column | Type | Notes |
161
+ |---------------|-----------------------------------|-------|
162
+ | `user_id` | int64 | 1..148,402, fresh public IDs (see *Privacy*) |
163
+ | `r_h` | string | hometown region — Wikidata QID, e.g. `Q35178` |
164
+ | `r_o` | string | destination region — Wikidata QID |
165
+ | `n_home_ci` | int64 | total home-side check-ins in `c_h` |
166
+ | `n_travel_ci` | int64 | total destination-side check-ins in `c_o` |
167
+ | `c_h` | list<struct> | home check-ins (see element schema below) |
168
+ | `c_o` | list<struct> | destination check-ins (same element schema) |
169
+
170
+ Each element of `c_h` / `c_o` is:
171
+
172
+ | Field | Type | Notes |
173
+ |--------------------|----------------------------|-------|
174
+ | `trail_id` | int64 | 1..2,723,551 (fresh public IDs) — same trail can re-appear across τ records |
175
+ | `venue_id` | string | `foursquare:<24-hex>` POI key |
176
+ | `venue_category` | string | Foursquare category UUID (4-byte hex, optional) |
177
+ | `venue_schema` | string | schema.org venue type, e.g. `schema:CafeOrCoffeeShop` |
178
+ | `ts` | timestamp[us, UTC] | observation time |
179
+
180
+ ### `pois.parquet` (687,173 rows)
181
+
182
+ POI-level summary, optimised for the 99 % of analyses that only need
183
+ the flat columns. Every POI in the benchmark appears exactly once.
184
+
185
+ | Column | Type | Notes |
186
+ |-----------------------|---------------------|-------|
187
+ | `fsq_place_id` | string | primary key |
188
+ | `locality` | string | Wikidata QID of the city |
189
+ | `venue_category` | string | Foursquare category UUID |
190
+ | `venue_schema` | string | schema.org type |
191
+ | `n_checkins` | int64 | total check-ins for this POI in the dataset |
192
+ | `n_users_visited` | int64 | distinct travellers who visited |
193
+ | `google_cid` | string \| null | Google Maps customer ID (= `place_id` in some APIs) |
194
+ | `google_name` | string \| null | Google business name |
195
+ | `google_full_address` | string \| null | Google formatted address |
196
+ | `google_address` | string \| null | Google street address |
197
+ | `google_website` | string \| null | Google business website |
198
+ | `google_rating` | double \| null | average Google star rating |
199
+ | `google_num_reviews` | int64 \| null | Google review count |
200
+ | `google_categories` | list<string> \| null| Google category labels |
201
+ | `google_place_id` | string \| null | Google Places API ID (when known) |
202
+ | `google_gmaps_url` | string \| null | canonical maps.google.com URL |
203
+ | `google_meta_source` | string | provenance tag identifying which collection step produced this metadata |
204
+ | `has_google_metadata` | bool | convenience flag |
205
+ | `n_reviews` | int64 | reviews available for this POI |
206
+ | `n_reviews_with_text` | int64 | reviews with non-empty text |
207
+ | `review_source` | string | provenance tag |
208
+ | `has_reviews` | bool | convenience flag |
209
+
210
+ ### `metadata/metadata_all.parquet` (687,173 rows)
211
+
212
+ Per-POI Foursquare + Google metadata. Same `fsq_place_id` primary key
213
+ as `pois.parquet`; richer FSQ fields (name, lat/lon, address, country,
214
+ website, …). Personal-leaning Foursquare contact fields
215
+ (`fsq_email`, `fsq_tel`, `fsq_facebook_id`, `fsq_instagram`,
216
+ `fsq_twitter`) are intentionally **not** present.
217
+
218
+ Notable columns: `fsq_name`, `fsq_latitude`, `fsq_longitude`,
219
+ `fsq_address`, `fsq_locality`, `fsq_region`, `fsq_country`,
220
+ `fsq_postcode`, `fsq_formatted_address`, `fsq_category_ids`,
221
+ `fsq_category_labels`, `fsq_website`, `fsq_date_created`,
222
+ `fsq_date_refreshed`, `fsq_date_closed`.
223
+
224
+ The `google_*` columns mirror those in `pois.parquet`.
225
+
226
+ ### `metadata/place_attributes.parquet` (28,776 rows)
227
+
228
+ Rich place-level attributes for the most enriched POIs (descriptions,
229
+ opening hours, price tier, free-form attributes).
230
+
231
+ | Column | Type | Notes |
232
+ |---------------------|--------|-------|
233
+ | `fsq_place_id` | string | join key |
234
+ | `google_cid` | string | the Google CID this enrichment came from |
235
+ | `search_query` | string | query used to recover the place |
236
+ | `match_dist_m` | double | metres between FSQ point and Google point |
237
+ | `match_name_sim` | double | normalized name-similarity score |
238
+ | `description_short` | string | one-line description |
239
+ | `description_long` | string | longer description |
240
+ | `hours_today` | string | today's opening hours, free-text |
241
+ | `hours_week` | string | weekly hours, free-text |
242
+ | `price_token` | string | Google price symbol (`$`, `$$`, …) |
243
+ | `price_min` | string | min price (when known) |
244
+ | `price_max` | string | max price (when known) |
245
+ | `attributes` | string | JSON-encoded attribute bag |
246
+ | `n_inline_reviews` | int64 | count of reviews scraped at enrichment time |
247
+ | `fetched_at` | string | timestamp of enrichment fetch |
248
+
249
+ ### `region_labels.parquet` (1,173 rows)
250
+
251
+ | Column | Type | Example |
252
+ |----------------|--------|--------------|
253
+ | `region_id` | string | `Q100` |
254
+ | `city_name` | string | `Boston` |
255
+ | `country_qid` | string | `wd:Q30` |
256
+ | `country_name` | string | `United States` |
257
+
258
+ ### `reviews/reviews_all.parquet` (186,760,186 rows)
259
+
260
+ Unified Google reviews corpus, one row per review.
261
+
262
+ | Column | Type | Notes |
263
+ |------------------|-----------------------|-------|
264
+ | `fsq_place_id` | string | links to `pois.parquet` |
265
+ | `google_cid` | string | links to `metadata_all.parquet` |
266
+ | `review_id` | string | Google's review ID |
267
+ | `rating` | int64 | 1..5 |
268
+ | `text` | string | original review text (may be empty) |
269
+ | `text_translated`| string \| null | Google's machine translation, if any |
270
+ | `lang` | string \| null | BCP-47 language tag |
271
+ | `relative_time` | string \| null | Google's "3 weeks ago" string |
272
+ | `timestamp_us` | int64 | absolute review time, microseconds since epoch |
273
+ | `review_time` | timestamp[us, UTC] | same value, parsed |
274
+ | `owner_reply` | string \| null | business-owner reply text, if any |
275
+ | `source` | string | provenance tag identifying which collection step produced this review |
276
+ | `author_pid` | string | salted blake2b 16-hex pseudonym (see *Privacy*) |
277
+
278
+ The display name and Google profile ID of each reviewer are **removed
279
+ from the public release**; the `author_pid` column lets you link
280
+ multiple reviews from the same author *within* the dataset without
281
+ exposing real identities.
282
+
283
+ ### `metro_mapping_clean.json`
284
+
285
+ A JSON dictionary mapping individual municipality QIDs to the parent
286
+ metro QID used as `region_id` everywhere else. Useful if you want to
287
+ recover the original sub-municipal granularity, or extend the mapping.
288
+
289
+
290
+ ## Quick start
291
+
292
+ The release uses Apache Parquet throughout; any tool that reads parquet
293
+ will work. Below are minimal examples in three common stacks.
294
+
295
+ ### Python — pandas / pyarrow
296
+
297
+ ```python
298
+ import pandas as pd, pyarrow.parquet as pq
299
+ ROOT = "/path/to/trip_world"
300
+
301
+ travel = pq.read_table(f"{ROOT}/travel_behaviors.parquet").to_pandas()
302
+ pois = pq.read_table(f"{ROOT}/pois.parquet").to_pandas()
303
+ regions = pq.read_table(f"{ROOT}/region_labels.parquet").to_pandas()
304
+
305
+ # How many trips originate from each city?
306
+ top_origins = (travel.merge(regions, left_on="r_h", right_on="region_id")
307
+ .groupby("city_name").size()
308
+ .sort_values(ascending=False).head(10))
309
+ print(top_origins)
310
+ ```
311
+
312
+ ### Python — DuckDB (recommended for the 22 GB review file)
313
+
314
+ DuckDB streams parquet without loading everything into RAM and supports
315
+ the full SQL surface, including joins across files.
316
+
317
+ ```python
318
+ import duckdb
319
+ con = duckdb.connect()
320
+
321
+ con.execute(f"""
322
+ CREATE VIEW travel AS SELECT * FROM '{ROOT}/travel_behaviors.parquet';
323
+ CREATE VIEW pois AS SELECT * FROM '{ROOT}/pois.parquet';
324
+ CREATE VIEW regions AS SELECT * FROM '{ROOT}/region_labels.parquet';
325
+ CREATE VIEW reviews AS SELECT * FROM '{ROOT}/reviews/reviews_all.parquet';
326
+ """)
327
+
328
+ # Top destinations for travellers from Boston (Q100):
329
+ con.sql("""
330
+ SELECT regions.city_name, COUNT(*) AS trips
331
+ FROM travel JOIN regions ON travel.r_o = regions.region_id
332
+ WHERE travel.r_h = 'Q100'
333
+ GROUP BY regions.city_name
334
+ ORDER BY trips DESC
335
+ LIMIT 10
336
+ """).show()
337
+
338
+ # Average review rating per category in Tokyo:
339
+ con.sql("""
340
+ SELECT pois.venue_schema,
341
+ AVG(reviews.rating) AS avg_rating,
342
+ COUNT(*) AS n
343
+ FROM reviews
344
+ JOIN pois ON reviews.fsq_place_id = pois.fsq_place_id
345
+ WHERE pois.locality = 'Q1490' -- Tokyo
346
+ GROUP BY pois.venue_schema
347
+ HAVING COUNT(*) > 100
348
+ ORDER BY avg_rating DESC
349
+ """).show()
350
+ ```
351
+
352
+ ### Iterating over the trajectories of one traveller
353
+
354
+ ```python
355
+ import pyarrow.parquet as pq, pandas as pd
356
+ tb = pq.read_table(f"{ROOT}/travel_behaviors.parquet").to_pandas()
357
+
358
+ row = tb.iloc[0]
359
+ print(f"User {row['user_id']} travelled from {row['r_h']} to {row['r_o']}")
360
+ print(f" {row['n_home_ci']} home check-ins, {row['n_travel_ci']} destination check-ins")
361
+
362
+ # Group destination check-ins by trail (= individual trajectory):
363
+ import collections
364
+ trails = collections.defaultdict(list)
365
+ for ck in row["c_o"]:
366
+ trails[ck["trail_id"]].append(ck)
367
+
368
+ for trail_id, points in trails.items():
369
+ points.sort(key=lambda p: p["ts"])
370
+ venues = " → ".join(p["venue_schema"] for p in points)
371
+ print(f" trail {trail_id}: {venues}")
372
+ ```
373
+
374
+ ### Counting reviews per place without loading all 22 GB
375
+
376
+ ```python
377
+ con.sql("""
378
+ SELECT fsq_place_id, COUNT(*) AS n_reviews
379
+ FROM '{ROOT}/reviews/reviews_all.parquet'
380
+ GROUP BY fsq_place_id
381
+ ORDER BY n_reviews DESC
382
+ LIMIT 20
383
+ """.format(ROOT=ROOT)).show()
384
+ ```
385
+
386
+
387
+ ## Common join patterns
388
+
389
+ | To go from … | … to … | Join key |
390
+ |--------------|------------------------------|--------------------------------------------|
391
+ | τ record | hometown / destination name | `travel.r_h = regions.region_id` (and `r_o`) |
392
+ | τ record | per-POI usage / Google meta | element `venue_id = pois.fsq_place_id` |
393
+ | τ record | full FSQ + Google metadata | element `venue_id = metadata_all.fsq_place_id` |
394
+ | POI summary | rich place attributes | `pois.fsq_place_id = place_attributes.fsq_place_id` |
395
+ | POI summary | reviews | `pois.fsq_place_id = reviews.fsq_place_id` |
396
+ | Reviews | place-level Google ratings | `reviews.google_cid = pois.google_cid` |
397
+ | Reviews | author identity (within set) | `reviews.author_pid` (no external linking) |
398
+ | Region | municipalities folded into it| `metro_mapping_clean.json[municipality_qid] == region_id` |
399
+
400
+
401
+ ## Privacy and redaction
402
+
403
+ The following transforms have been applied relative to the build-time
404
+ working set so the release can be redistributed without exposing
405
+ individual identities:
406
+
407
+ 1. **User IDs.** `user_id` in `travel_behaviors.parquet` is remapped
408
+ to a fresh consecutive 1..148,402 sequence; original
409
+ STD-2018-derived IDs are not present.
410
+
411
+ 2. **Trail IDs.** `trail_id` inside each `c_h` / `c_o` element is
412
+ likewise remapped to a fresh consecutive 1..2,723,551 sequence.
413
+
414
+ 3. **Reviewer identity.** Reviewer display names (`author`) are
415
+ removed entirely. The original numeric Google `author_id` is
416
+ replaced with a salted blake2b pseudonym `author_pid` (16 hex
417
+ characters per author). The salt is generated at release time and
418
+ kept private; cross-review author linking remains possible *inside*
419
+ the dataset but cannot be inverted to a real Google profile.
420
+
421
+ 4. **Foursquare contact fields.** The columns `fsq_email`, `fsq_tel`,
422
+ `fsq_facebook_id`, `fsq_instagram`, `fsq_twitter` are dropped from
423
+ `metadata_all.parquet`.
424
+
425
+ 5. **Review text.** Review bodies are kept verbatim (they are the
426
+ dataset's primary signal). Users of this release should be aware
427
+ that user-generated text may incidentally contain personal
428
+ references and should treat downstream analyses accordingly.
429
+
430
+ If you discover residual identifying information that we missed, please
431
+ contact the maintainers so it can be redacted in the next release.
432
+
433
+
434
+ ## Reproducibility
435
+
436
+ The build-pipeline source is shipped under `_scripts/` for
437
+ documentation and audit purposes. **Re-running it end-to-end requires
438
+ several external data sources that are not part of this release** — see
439
+ the table below. The released parquet files are the canonical
440
+ artefacts; the scripts let you verify *how* they were produced and
441
+ re-derive subsets you may need.
442
+
443
+ ### What the scripts can re-derive
444
+
445
+ | Stage(s) | Output | External data needed |
446
+ |----------|--------|----------------------|
447
+ | 0–6 | metro map, τ records, POIs, region labels | STD-2018 raw check-in CSV |
448
+ | 7 | per-POI Foursquare metadata | Foursquare Open Source Places parquet dump |
449
+ | 10 | extra FSQ enrichment for new POIs | Foursquare Open Source Places parquet dump |
450
+ | 11 | FSQ-API rescue of unresolved POIs | Foursquare Places API key |
451
+ | 12–13 | UCSD-bridge Google metadata for new POIs | UCSD all20 + benchmark POI corpus |
452
+ | 14–16 | merged Google reviews + place attributes | **raw GCP scrape shards (not redistributable; the scrape code is not included)** |
453
+
454
+ In other words, the structural side of Trip World (τ records, POIs,
455
+ region labels, FSQ metadata) can be reproduced if you supply STD-2018
456
+ and an FSQ-OS dump. The Google reviews corpus cannot be re-derived
457
+ from this release alone — it is provided as a static parquet because
458
+ the scrape that produced it is not redistributable.
459
+
460
+ ### Configuring paths
461
+
462
+ All scripts read their filesystem locations from environment variables
463
+ so the source tree contains no personal paths. Defaults assume the
464
+ script is launched from inside the release's `_scripts/` subfolder.
465
+
466
+ ```bash
467
+ export TRIP_WORLD_ROOT=/path/to/trip_world # default: ../ relative to the script
468
+ export STD_2018_PATH=/path/to/std_2018.csv # raw STD-2018 stream
469
+ export FSQ_OS_PARQUET_GLOB="/path/to/fsq_os/places/parquet/*.parquet"
470
+ export PRECURSOR_BUILD_ROOT=/path/to/previous_build # optional; an earlier output of this pipeline whose POI metadata and reviews stages 5/7/8/16 inherit from. Omit unless you are rebuilding incrementally on top of a prior run.
471
+ export GMAPS_FULL_ROOT=/path/to/gmaps_full_dataset # optional, only for stage 12
472
+ export DUCKDB_TMP_DIR=/tmp/duckdb_trip_world # any large local scratch directory
473
+ export FSQ_API_KEY=fsq3... # only if running stage 11
474
+ ```
475
+
476
+ ### Stage-by-stage map
477
+
478
+ ```
479
+ _scripts/00_build_metro_map.py — metro consolidation map (Wikidata SPARQL)
480
+ _scripts/01_consolidate_filter.py — apply consolidation, filter to MIN_PAIR
481
+ _scripts/02_hometown_discovery.py — temporal-decay hometown identification
482
+ _scripts/03_build_travelers.py — split travellers / non-travellers
483
+ _scripts/04_build_travel_behaviors.py — emit τ records
484
+ _scripts/05_build_pois.py — per-POI usage stats
485
+ _scripts/06_build_region_labels.py — Wikidata-derived city names
486
+ _scripts/07_subset_metadata.py — slice FSQ-OS metadata
487
+ _scripts/08_subset_reviews.py — slice reviews
488
+ _scripts/09_validate.py — invariants + descriptive stats
489
+ _scripts/10_enrich_new_pois.py — local-dump enrichment for new POIs
490
+ _scripts/11_fsq_api_recover.py — live FSQ Places API recovery
491
+ _scripts/12_ucsd_bridge.py — UCSD all20+bench match
492
+ _scripts/13_merge_ucsd_into_metadata.py — merge UCSD matches into metadata
493
+ _scripts/14_merge_gcp_search_results.py — merge Stage-1 GCP scrape shards (shards not shipped)
494
+ _scripts/15_merge_stage2_reviews.py — merge Stage-2 listugcposts shards (shards not shipped)
495
+ _scripts/16_unify_reviews.py — final review unification
496
+ _scripts/lib_wikidata.py — small Wikidata helper
497
+ _scripts/viz_clean_raw.py — descriptive figures
498
+ _scripts/viz_traj_length.py — trajectory-length figure
499
+ ```
500
+
501
+ No API keys are embedded in any released script; stages that hit
502
+ external services (Wikidata SPARQL, FSQ Places API) read credentials
503
+ from environment variables or CLI flags exclusively.
504
+
505
+
506
+ ## Citation
507
+
508
+ If you use Trip World in academic work, please cite the accompanying
509
+ paper (BibTeX entry to be released alongside the official publication).
510
+
511
+
512
+ ## License
513
+
514
+ The Trip World release is distributed for **non-commercial research
515
+ use** only. Redistributions must preserve this README and the
516
+ provenance scripts in `_scripts/`. Use of the dataset implies
517
+ acceptance of the upstream Foursquare Open Source Places licence and
518
+ the Google Maps Platform Terms of Service for any further analysis
519
+ that re-fetches data from those services.
520
+
521
+ Released on 2026-05-05.
_scripts/00_build_metro_map.py ADDED
@@ -0,0 +1,656 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Build the METRO-level metro_mapping_clean.json for the Trip World build pipeline.
3
+
4
+ The a precursor build used CITY-level consolidation, which left commuter-belt
5
+ municipalities (Yokohama -> Tokyo, Suita -> Osaka, ...) as separate
6
+ "destinations". This produced ~14% phantom intra-metro travel records.
7
+ The Trip World build pipeline uses METRO-level consolidation: any administrative entity
8
+ inside a known metropolitan area collapses to a single anchor QID.
9
+
10
+ Sources:
11
+ 1) Optional pre-existing metro map provided via an existing metro map seed (optional, supplied via the --existing CLI flag; carried over verbatim and only extended) (carried through if set; only adds, never removes).
12
+ 2) Hand-curated METRO_DEFINITIONS giving each anchor metro and the cities,
13
+ districts and prefectures inside its commuter belt. Member QIDs are
14
+ drawn from Wikidata (verified by name lookup -- see _scripts/lookup_qids.txt).
15
+ 3) SPARQL P131+ descendants of each anchor (gathers any sub-municipal entity
16
+ reachable via "located in administrative entity" within the metro).
17
+ 4) Foursquare-internal "Q49xxxxxxx / Q27347xxx / Q35xxxxxxx" QIDs that lack
18
+ proper P131 chains -- explicitly listed below by raw_QID -> metro_QID.
19
+
20
+ Output: $TRIP_WORLD_ROOT/metro_mapping_clean.json
21
+ """
22
+ from __future__ import annotations
23
+ import argparse, csv, json, time, collections
24
+ from pathlib import Path
25
+ from lib_wikidata import sparql, labels_batch
26
+ import os
27
+
28
+ # ---------------------------------------------------------------- METRO DEFINITIONS
29
+
30
+ # Anchor metro QID -> human-readable name and member sub-entity QIDs.
31
+ # Each member is a Wikidata QID (city, district, ward, prefecture, governorate)
32
+ # that should collapse to the anchor. Members include:
33
+ # * the anchor itself (no-op identity)
34
+ # * core city wards / boroughs / special wards
35
+ # * commuter-belt municipalities
36
+ # * the prefecture(s)/province(s)/state(s) that *primarily* serve the metro
37
+ # (NOT vast prefectures with rural areas spanning multiple metros, e.g.
38
+ # Hokkaido or Saitama-mountain regions are kept out)
39
+ METRO_DEFINITIONS: dict[str, dict] = {
40
+ # ---- Greater Tokyo (Shutoken) ----
41
+ "Q1490": {
42
+ "name": "Tokyo (Greater Tokyo Area)",
43
+ "members": [
44
+ "Q1490", # Tokyo (anchor)
45
+ "Q308891", # ward area of Tokyo
46
+ "Q956318", # special ward of Tokyo (the type itself)
47
+ # core 23 special wards
48
+ "Q161176", # Chiyoda
49
+ "Q281289", # Chuo
50
+ "Q281254", # Minato
51
+ "Q235923", # Shinjuku
52
+ "Q170204", # Bunkyo
53
+ "Q277338", # Taito
54
+ "Q281286", # Sumida
55
+ "Q220977", # Koto
56
+ "Q281295", # Shinagawa
57
+ "Q220957", # Meguro
58
+ "Q260106", # Ota
59
+ "Q160438", # Setagaya
60
+ "Q207601", # Shibuya
61
+ "Q263552", # Nakano
62
+ "Q277331", # Suginami
63
+ "Q275007", # Toshima
64
+ "Q281324", # Kita
65
+ "Q277021", # Arakawa
66
+ "Q220962", # Itabashi
67
+ "Q207370", # Nerima
68
+ "Q227773", # Adachi
69
+ "Q281321", # Katsushika
70
+ "Q281332", # Edogawa
71
+ # Tama region (Western Tokyo) cities
72
+ "Q391093", # Hachioji
73
+ "Q486868", # Tachikawa
74
+ "Q406798", # Musashino
75
+ "Q486876", # Mitaka
76
+ "Q210667", # Chofu
77
+ "Q1133105", # Fuchu
78
+ "Q317813", # Fussa
79
+ "Q390788", # Higashiyamato
80
+ # Greater Tokyo commuter cities (Kanagawa)
81
+ "Q38283", # Yokohama
82
+ "Q201136", # Kawasaki
83
+ "Q406798", # (dup)
84
+ "Q461920", # Fujisawa
85
+ "Q319330", # Yokosuka
86
+ "Q277260", # Sagamihara
87
+ "Q319737", # Atsugi
88
+ "Q1057611", # Hiratsuka
89
+ "Q132860", # Kamakura
90
+ # Greater Tokyo commuter cities (Saitama)
91
+ "Q205616", # Saitama (city)
92
+ "Q380049", # Kawaguchi
93
+ "Q425418", # Soka
94
+ "Q425556", # Tokorozawa
95
+ "Q390655", # Asaka
96
+ "Q425481", # Koshigaya
97
+ # Greater Tokyo commuter cities (Chiba)
98
+ "Q121054", # Chiba (city)
99
+ "Q319729", # Urayasu (canonical Wikidata)
100
+ "Q271417", # Funabashi
101
+ "Q487247", # Matsudo
102
+ "Q425556", # (dup)
103
+ "Q486883", # Ichikawa
104
+ "Q200988", # Kashiwa
105
+ # Prefectures that are essentially the Greater Tokyo commuter belt
106
+ "Q127513", # Kanagawa Prefecture
107
+ "Q128186", # Saitama Prefecture
108
+ "Q80011", # Chiba Prefecture
109
+ # Foursquare-internal Tokyo / Greater Tokyo QIDs (Q49xxxxxxx)
110
+ "Q49295377", # Yokohama-area (Foursquare-internal, P131->Kanagawa)
111
+ "Q49369715", # 浦�� Urayasu (Foursquare-internal)
112
+ "Q49369649", # likely Tokyo area
113
+ "Q49371464", # likely Tokyo area
114
+ "Q49371967", # likely Tokyo area
115
+ "Q49371923", # likely Tokyo area
116
+ "Q49371907", # likely Tokyo area
117
+ "Q49371895", # likely Tokyo area
118
+ "Q49371841", # likely Tokyo area
119
+ "Q49371829", # likely Tokyo area
120
+ "Q49371792", # likely Tokyo area
121
+ "Q49371745", # likely Tokyo area
122
+ # Verified via Wikidata coords / P131:
123
+ "Q35730142", # Minami-rinkan, Yamato Kanagawa
124
+ "Q35722099", # Machida (P131->Q1490 directly)
125
+ "Q386697", # Yamato (Kanagawa parent of Minami-rinkan)
126
+ "Q387136", # Kawaguchi (Saitama, P131->Saitama)
127
+ "Q273798", # Narita (Chiba)
128
+ "Q49371923", # Ōi (Saitama)
129
+ # Foursquare-internal QIDs at coords inside Greater Tokyo (lat 35.6-35.9, lon 139.4-139.8)
130
+ "Q49353821", # coords (35.67,139.40) - Tokyo SW
131
+ "Q49355990", # coords (35.69,139.55) - Tokyo W
132
+ "Q49371464", # coords (35.88,139.63) - Saitama
133
+ # NOTE: We do *not* blanket-collapse all Q49xxxxxxx into Tokyo.
134
+ # Only ones whose P131 chain (verified via SPARQL below) leads to
135
+ # Kanagawa / Saitama / Chiba / Tokyo prefectures, OR whose coords
136
+ # lie inside the Greater Tokyo bounding box.
137
+ ],
138
+ },
139
+
140
+ # ---- Keihanshin (Greater Osaka) ----
141
+ "Q35765": {
142
+ "name": "Osaka (Keihanshin)",
143
+ "members": [
144
+ "Q35765", # Osaka (anchor)
145
+ "Q122723", # Osaka Prefecture
146
+ "Q34600", # Kyoto
147
+ "Q120730", # Kyoto Prefecture
148
+ # NOTE: Nagoya (Q11751) is intentionally NOT in Keihanshin -- it's its own metro
149
+ "Q130290", # Hyogo Prefecture
150
+ "Q133054", # Nara Prefecture
151
+ "Q187153", # Sakai
152
+ "Q220655", # Nishinomiya
153
+ "Q725514", # Ashiya
154
+ "Q653510", # Suita (canonical)
155
+ "Q49368443", # Suita (Foursquare-internal)
156
+ "Q231318", # Higashiosaka
157
+ "Q486398", # Toyonaka
158
+ "Q499375", # Amagasaki
159
+ "Q734474", # Itami
160
+ "Q200994", # Otsu
161
+ "Q48320", # Kobe (corrected QID; was Q244 which is Roman numeral)
162
+ # Foursquare-internal Osaka-area QIDs (verified via P131 chain)
163
+ "Q49368443", # (dup) Suita
164
+ ],
165
+ },
166
+
167
+ # Remove Nagoya from Osaka definition; it's its own metro.
168
+ # ---- Chukyo (Greater Nagoya) ----
169
+ "Q11751": {
170
+ "name": "Nagoya (Chukyo)",
171
+ "members": [
172
+ "Q11751", # Nagoya (anchor)
173
+ "Q80434", # Aichi Prefecture
174
+ "Q131277", # Gifu Prefecture
175
+ "Q128196", # Mie Prefecture
176
+ "Q188996", # Toyota
177
+ "Q486392", # Toyohashi
178
+ "Q462000", # Okazaki
179
+ "Q462009", # Ichinomiya
180
+ "Q499390", # Kasugai
181
+ ],
182
+ },
183
+
184
+ # ---- Greater Istanbul ----
185
+ "Q406": {
186
+ "name": "Istanbul",
187
+ "members": [
188
+ "Q406", # Istanbul (anchor)
189
+ "Q534799", # Istanbul Province
190
+ "Q326339", # Üsküdar
191
+ "Q746516", # Bağcılar
192
+ "Q1006881", # Şişli (canonical district)
193
+ "Q49371964", # Şişli (Foursquare-internal "yerleşim")
194
+ "Q179351", # ! Westminster -> handled separately, NOT here
195
+ # ^^ removed; just being defensive about not overloading the entry.
196
+ "Q3473299", # Beşiktaş
197
+ "Q1023876", # Kadıköy
198
+ "Q1247058", # Bakırköy
199
+ "Q1067075", # Kartal
200
+ "Q1023901", # Maltepe
201
+ "Q605884", # Pendik
202
+ "Q604919", # Tuzla
203
+ "Q1135036", # Ataşehir
204
+ "Q1019002", # Beylikdüzü
205
+ ],
206
+ },
207
+
208
+ # ---- Greater Ankara ----
209
+ "Q3640": {
210
+ "name": "Ankara",
211
+ "members": [
212
+ "Q3640", # Ankara (anchor)
213
+ "Q2297724", # Ankara Province
214
+ "Q3928674", # Hudavendigar vilayet (historical/Foursquare alt)
215
+ "Q608459", # Çankaya
216
+ "Q625728", # Keçiören
217
+ ],
218
+ },
219
+
220
+ # ---- Greater Izmir ----
221
+ "Q35997": {
222
+ "name": "İzmir",
223
+ "members": [
224
+ "Q35997", # İzmir (anchor)
225
+ "Q344490", # İzmir Province
226
+ "Q3123584", # Karabağlar district
227
+ "Q615098", # Konak
228
+ "Q615075", # Bornova
229
+ "Q1190403", # (Edessa - actually Şanlıurfa; will be filtered below)
230
+ ],
231
+ },
232
+
233
+ # ---- Greater Kuwait City ----
234
+ "Q35178": {
235
+ "name": "Kuwait City",
236
+ "members": [
237
+ "Q35178", # Kuwait City (anchor)
238
+ "Q3235220", # Hawally
239
+ "Q3495478", # Sabah Al-Salem
240
+ "Q4704795", # Al Shamiya
241
+ "Q747432", # Hawalli Governorate
242
+ "Q372316", # Al Asimah Governorate
243
+ "Q953508", # Eastern Province (NOT Kuwait -- Saudi! filter out below)
244
+ "Q185122", # Al Farwaniyah Governorate
245
+ "Q1057620", # Mubarak Al-Kabeer Governorate
246
+ "Q310948", # Al Ahmadi Governorate
247
+ "Q83341", # Jahra Governorate
248
+ "Q3221814", # Salmiya
249
+ "Q14708037", # Salwa
250
+ "Q5894717", # Jabriya
251
+ # Kuwait Q27347xxx series (Foursquare-internal, all P17=Q817 by coordinate)
252
+ "Q27347020", # in Kuwait
253
+ "Q27347063", # Al Dasma
254
+ "Q27347142", # in Kuwait
255
+ "Q1046645", # parent of Al Dasma; collapse upward
256
+ # additional Kuwaiti districts discovered during validation
257
+ "Q3505782", # Salmiya (P131->Hawalli Gov)
258
+ "Q4120400", # Mubarak Al-Kabeer (P17=Q817, no P131)
259
+ "Q3495485", # Fahaheel District (P131->Ahmadi Gov)
260
+ "Q552354", # Ahmadi Governorate
261
+ "Q1077024", # Al Jahra
262
+ "Q405701", # Jahra Governorate
263
+ ],
264
+ },
265
+
266
+ # ---- Greater Mexico City ----
267
+ "Q1489": {
268
+ "name": "Mexico City",
269
+ "members": [
270
+ "Q1489", # Mexico City (anchor)
271
+ # All v2's existing delegacion mappings carried through automatically
272
+ "Q1502190", # State of Mexico (commuter belt, debatable)
273
+ "Q21509", # Naucalpan
274
+ "Q161113", # Tlalnepantla
275
+ "Q244366", # Ecatepec
276
+ "Q205344", # Nezahualcóyotl
277
+ ],
278
+ },
279
+
280
+ # ---- Greater Manila ----
281
+ "Q13580": {
282
+ "name": "Metro Manila",
283
+ "members": [
284
+ "Q13580", # Metro Manila (anchor)
285
+ "Q1461", # Manila proper
286
+ "Q1475", # Quezon City
287
+ "Q1508", # Makati
288
+ "Q9085", # Mandaluyong
289
+ "Q31475562", # Bagong Pag-asa (already in v2)
290
+ "Q9248", # Pasig
291
+ "Q12972", # Taguig
292
+ "Q190482", # Caloocan
293
+ "Q47265", # Pasay
294
+ "Q24856", # Parañaque
295
+ "Q31476", # Las Piñas
296
+ "Q23681", # Muntinlupa
297
+ "Q161115", # Marikina
298
+ "Q190428", # Valenzuela
299
+ "Q31476", # (dup)
300
+ ],
301
+ },
302
+
303
+ # ---- Greater São Paulo ----
304
+ "Q174": {
305
+ "name": "São Paulo",
306
+ "members": [
307
+ "Q174", # São Paulo (anchor)
308
+ "Q175", # São Paulo state (debatable; whole state)
309
+ "Q201161", # Guarulhos
310
+ "Q140714", # Osasco
311
+ "Q188800", # Santo André
312
+ "Q188820", # São Bernardo do Campo
313
+ "Q188824", # São Caetano do Sul
314
+ "Q201161", # (dup)
315
+ ],
316
+ },
317
+
318
+ # ---- Greater Rio de Janeiro ----
319
+ "Q8678": {
320
+ "name": "Rio de Janeiro",
321
+ "members": [
322
+ "Q8678", # Rio de Janeiro (city, anchor)
323
+ "Q41428", # Rio de Janeiro state
324
+ "Q188897", # Nova Iguaçu
325
+ "Q983459", # Nilópolis
326
+ "Q186363", # Niterói
327
+ "Q188867", # Duque de Caxias
328
+ "Q189070", # São Gonçalo
329
+ "Q189158", # Belford Roxo
330
+ ],
331
+ },
332
+
333
+ # ---- Greater Bangkok ----
334
+ "Q1861": {
335
+ "name": "Bangkok",
336
+ "members": [
337
+ "Q1861", # Bangkok (anchor)
338
+ "Q242932", # Nonthaburi Province
339
+ "Q475212", # Bang Kruai
340
+ "Q15199204", # Bang Kruai (Foursquare alt)
341
+ "Q768864", # Nonthaburi (city)
342
+ "Q205454", # Pak Kret
343
+ "Q244408", # Pathum Thani Province
344
+ "Q244399", # Samut Prakan Province
345
+ ],
346
+ },
347
+
348
+ # ---- Greater London (already in v2, extending) ----
349
+ "Q84": {
350
+ "name": "London",
351
+ "members": [
352
+ "Q84", # London (anchor)
353
+ "Q179351", # Westminster
354
+ # All London boroughs (32 + City of London)
355
+ "Q201808", # Camden
356
+ "Q204022", # Islington (note: also a v2 target)
357
+ "Q205817", # London Borough of Islington (already a v2 target!)
358
+ "Q204008", # Hackney
359
+ "Q204009", # Tower Hamlets
360
+ "Q204008", # (dup)
361
+ "Q207017", # Lambeth
362
+ "Q207018", # Southwark
363
+ "Q207020", # Wandsworth
364
+ "Q204010", # Kensington and Chelsea
365
+ "Q205677", # Hammersmith and Fulham
366
+ "Q204023", # Haringey
367
+ "Q204008", # (dup)
368
+ "Q207016", # Lewisham
369
+ "Q207021", # Greenwich
370
+ "Q207022", # Newham
371
+ "Q207023", # Waltham Forest
372
+ "Q204023", # (dup)
373
+ "Q204022", # (dup)
374
+ ],
375
+ },
376
+
377
+ # ---- New York City (already in v2 with Manhattan/Brooklyn/etc.) ----
378
+ "Q60": {
379
+ "name": "New York City",
380
+ "members": [
381
+ "Q60", # NYC (anchor)
382
+ "Q11299", # Manhattan
383
+ "Q18424", # Brooklyn
384
+ "Q18432", # Queens
385
+ "Q18426", # Bronx
386
+ "Q18437", # Staten Island
387
+ # Plus the v2 already maps East Village, East Harlem, Hell's Kitchen
388
+ # under Q11299; transitive_close will reroute them all to Q60.
389
+ ],
390
+ },
391
+
392
+ # ---- Greater Chicago (already in v2; extending if needed) ----
393
+ "Q1297": {
394
+ "name": "Chicago",
395
+ "members": ["Q1297"],
396
+ },
397
+
398
+ # ---- Greater Buenos Aires (already in v2) ----
399
+ "Q1486": {
400
+ "name": "Buenos Aires",
401
+ "members": ["Q1486"],
402
+ },
403
+
404
+ # ---- Greater Kuala Lumpur (Klang Valley) ----
405
+ "Q1865": {
406
+ "name": "Kuala Lumpur (Klang Valley)",
407
+ "members": [
408
+ "Q1865", # Kuala Lumpur (anchor)
409
+ "Q864965", # Petaling Jaya
410
+ "Q2701266", # Petaling District
411
+ "Q189710", # Selangor (state - debatable; keep cause Klang Valley spans it)
412
+ "Q221275", # Subang Jaya
413
+ "Q815117", # Klang
414
+ # NOTE: Johor Bahru (Q2193190) is a SEPARATE metro in southern Malaysia
415
+ "Q864964", # Shah Alam
416
+ "Q1018830", # Kajang
417
+ "Q1018828", # Ampang Jaya
418
+ "Q500033", # Shah Alam (P131->Petaling District)
419
+ "Q2366087", # Balakong (P131->place in Selangor)
420
+ "Q4251470", # parent of Balakong
421
+ ],
422
+ },
423
+
424
+ # ---- Greater Riyadh ----
425
+ "Q3692": {
426
+ "name": "Riyadh",
427
+ "members": [
428
+ "Q3692", # Riyadh (anchor)
429
+ "Q41475", # Riyadh Province
430
+ ],
431
+ },
432
+
433
+ # ---- Greater Sendai ----
434
+ "Q46747": {
435
+ "name": "Sendai",
436
+ "members": [
437
+ "Q46747", # Sendai (anchor)
438
+ "Q47896", # Miyagi Prefecture
439
+ ],
440
+ },
441
+
442
+ # ---- Greater Sapporo ----
443
+ "Q37951": {
444
+ "name": "Sapporo",
445
+ "members": [
446
+ "Q37951", # Sapporo (anchor; Q35531 was wrong)
447
+ "Q1037393", # Hokkaido (huge region; debatable -- but Sapporo is by far the dominant city)
448
+ "Q1997315", # Ishikari Subprefecture
449
+ "Q49295332", # P131 -> Hokkaido (Foursquare-internal)
450
+ "Q693237", # Chitose (P131->Ishikari Subprefecture)
451
+ ],
452
+ },
453
+
454
+ # ---- Greater Fukuoka ----
455
+ "Q26600": {
456
+ "name": "Fukuoka",
457
+ "members": [
458
+ "Q26600", # Fukuoka (anchor; Q41051 was wrong, that's an Italian comune)
459
+ "Q123258", # Fukuoka Prefecture
460
+ "Q49295241", # P131 -> Fukuoka Prefecture (Foursquare-internal)
461
+ ],
462
+ },
463
+ }
464
+
465
+
466
+ # QIDs that are EXPLICITLY NOT to be merged (they look like leaks but aren't).
467
+ # E.g. Q49295241 has label "" but P131 -> Fukuoka Prefecture (a different metro).
468
+ DO_NOT_MERGE: set[str] = {
469
+ # These Q49xxxxxxx ones live in NON-Tokyo prefectures per their P131 chain.
470
+ # (Q49295241 is now in Greater Fukuoka definition; Q49295332 is in Greater Sapporo via Hokkaido)
471
+ "Q49295248",
472
+ "Q49355990",
473
+ "Q49353249",
474
+ "Q49353821",
475
+ "Q49755161",
476
+ # Misc Wikidata items that landed in venue_city but are nonsense
477
+ "Q132894", # "Pterocarpus" (tree genus, not Yokohama!)
478
+ "Q1392079", # "Terry George" (a person)
479
+ "Q21", # England (region/country, too coarse)
480
+ "Q26952", # Alvis Car Co. (not a city)
481
+ "Q1190403", # Edessa / Şanlıurfa, not Izmir
482
+ "Q953508", # Saudi Eastern Province, not Kuwait
483
+ }
484
+
485
+ # ---------------------------------------------------------------- helpers
486
+
487
+ def step(t0, msg):
488
+ print(f"[{time.time()-t0:6.1f}s] {msg}", flush=True)
489
+
490
+
491
+ def enumerate_raw_cities(raw_csv: Path, min_ci: int) -> list[tuple[str, int]]:
492
+ counter: collections.Counter[str] = collections.Counter()
493
+ with raw_csv.open() as f:
494
+ rd = csv.DictReader(f)
495
+ for row in rd:
496
+ v = row.get("venue_city")
497
+ if v:
498
+ counter[v] += 1
499
+ big = [(q.replace("wd:", ""), n) for q, n in counter.items() if n >= min_ci]
500
+ big.sort(key=lambda x: -x[1])
501
+ return big
502
+
503
+
504
+ def discover_p131_descendants(anchor_qid: str, max_results: int = 100000) -> set[str]:
505
+ """Return all entities reachable as wdt:P131+ wd:<anchor>."""
506
+ q = f"""
507
+ SELECT ?desc WHERE {{
508
+ ?desc wdt:P131+ wd:{anchor_qid} .
509
+ }} LIMIT {max_results}
510
+ """
511
+ try:
512
+ rows = sparql(q)
513
+ return {r["desc"]["value"].rsplit("/", 1)[-1] for r in rows}
514
+ except Exception as e:
515
+ print(f" P131+ for {anchor_qid} failed: {e}")
516
+ return set()
517
+
518
+
519
+ # ---------------------------------------------------------------- main
520
+
521
+ def main():
522
+ ap = argparse.ArgumentParser()
523
+ ap.add_argument("--raw", default=os.environ.get("STD_2018_PATH"))
524
+ ap.add_argument("--out",
525
+ default=os.environ.get("METRO_MAP_OUT",
526
+ str(Path(os.environ.get("TRIP_WORLD_ROOT", Path(__file__).resolve().parent.parent)) / "metro_mapping_clean.json")))
527
+ ap.add_argument("--existing", default=None)
528
+ ap.add_argument("--min-checkins", type=int, default=50,
529
+ help="discover descendants of anchors only for raw QIDs above this CI threshold")
530
+ ap.add_argument("--use-sparql", action="store_true", default=True,
531
+ help="enable SPARQL P131+ descendant discovery for each anchor metro")
532
+ args = ap.parse_args()
533
+
534
+ out_path = Path(args.out)
535
+ out_path.parent.mkdir(parents=True, exist_ok=True)
536
+ t0 = time.time()
537
+
538
+ # Step 1: load existing v2 map
539
+ step(t0, f"loading existing {args.existing}")
540
+ existing = json.load(open(args.existing))
541
+ base_map: dict[str, str] = dict(existing.get("metro_map", {}))
542
+ base_labels: dict[str, str] = dict(existing.get("labels", {}))
543
+ step(t0, f" v2 has {len(base_map):,} entries ({sum(1 for k,v in base_map.items() if k!=v):,} non-identity)")
544
+
545
+ # Step 2: enumerate raw QIDs to know which are worth mapping
546
+ step(t0, f"enumerating raw venue_city QIDs (>= {args.min_checkins} CIs)")
547
+ big = enumerate_raw_cities(Path(args.raw), args.min_checkins)
548
+ raw_qids = {q for q, _ in big}
549
+ step(t0, f" {len(raw_qids):,} raw QIDs to consider")
550
+
551
+ # Step 3: build map = identity for everyone, then apply hand-curated members
552
+ step(t0, "applying METRO_DEFINITIONS (hand-curated)")
553
+ metro_map = {q: q for q in raw_qids}
554
+ metro_map.update(base_map) # carry through v2
555
+
556
+ n_added_manual = 0
557
+ for anchor, defn in METRO_DEFINITIONS.items():
558
+ for member in defn["members"]:
559
+ if member in DO_NOT_MERGE:
560
+ continue
561
+ if member == anchor:
562
+ continue
563
+ if metro_map.get(member) != anchor:
564
+ metro_map[member] = anchor
565
+ n_added_manual += 1
566
+ # CRITICAL: enforce anchor -> anchor for every anchor *after* all members
567
+ # are placed. Without this, an anchor that was listed as a "member" of a
568
+ # different metro earlier in iteration order ends up demoted (e.g. Nagoya
569
+ # accidentally listed under Osaka would lose its Nagoya identity).
570
+ all_anchors = set(METRO_DEFINITIONS.keys())
571
+ for anchor in all_anchors:
572
+ metro_map[anchor] = anchor
573
+ step(t0, f" added/updated {n_added_manual:,} curated mappings; "
574
+ f"forced {len(all_anchors):,} anchors to identity")
575
+
576
+ # Step 4: SPARQL P131+ descendant discovery per anchor
577
+ if args.use_sparql:
578
+ step(t0, "discovering SPARQL P131+ descendants of each anchor")
579
+ n_added_sparql = 0
580
+ for anchor, defn in METRO_DEFINITIONS.items():
581
+ descs = discover_p131_descendants(anchor)
582
+ for d in descs:
583
+ if d in DO_NOT_MERGE:
584
+ continue
585
+ if d == anchor:
586
+ continue
587
+ # Only assign if d is a raw QID we care about, and not already mapped elsewhere
588
+ # (members override SPARQL, but SPARQL extends to discovered descendants)
589
+ if d in raw_qids and metro_map.get(d, d) == d:
590
+ metro_map[d] = anchor
591
+ n_added_sparql += 1
592
+ step(t0, f" {anchor} ({defn['name']}): {len(descs):,} descendants found, "
593
+ f"{sum(1 for d in descs if d in raw_qids):,} matched raw QIDs")
594
+ step(t0, f" added {n_added_sparql:,} SPARQL-discovered mappings")
595
+
596
+ # Step 5: enforce DO_NOT_MERGE (force identity on these)
597
+ n_forced = 0
598
+ for q in DO_NOT_MERGE:
599
+ if q in metro_map and metro_map[q] != q:
600
+ metro_map[q] = q
601
+ n_forced += 1
602
+ step(t0, f" forced {n_forced:,} DO_NOT_MERGE QIDs back to identity")
603
+
604
+ # Step 6: transitive close
605
+ step(t0, "computing transitive closure")
606
+ def resolve(q):
607
+ seen = {q}
608
+ while metro_map.get(q, q) != q and metro_map[q] not in seen:
609
+ q = metro_map[q]
610
+ seen.add(q)
611
+ return q
612
+ metro_map = {k: resolve(k) for k in metro_map}
613
+
614
+ rewritten = sum(1 for k, v in metro_map.items() if k != v)
615
+ targets = set(metro_map.values())
616
+ step(t0, f" total: {len(metro_map):,} entries, {rewritten:,} rewrites, "
617
+ f"{len(targets):,} distinct metro targets")
618
+
619
+ # Step 7: collect labels for everything
620
+ step(t0, "fetching labels for all sources + targets")
621
+ label_map = dict(base_labels)
622
+ universe = set(metro_map.keys()) | set(metro_map.values())
623
+ missing = sorted(q for q in universe if q not in label_map or not label_map[q])
624
+ if missing:
625
+ step(t0, f" fetching {len(missing):,} missing labels (batched)")
626
+ label_map.update(labels_batch(missing))
627
+
628
+ # Step 8: dump
629
+ out = {
630
+ "metro_map": metro_map,
631
+ "labels": label_map,
632
+ "build_log": {
633
+ "raw_csv": args.raw,
634
+ "min_checkins": args.min_checkins,
635
+ "raw_qids_considered": len(raw_qids),
636
+ "rewritten_qids": rewritten,
637
+ "distinct_metro_targets": len(targets),
638
+ "metro_definitions": {a: d["name"] for a, d in METRO_DEFINITIONS.items()},
639
+ "do_not_merge": sorted(DO_NOT_MERGE),
640
+ },
641
+ }
642
+ out_path.write_text(json.dumps(out, ensure_ascii=False, indent=2))
643
+ step(t0, f"wrote {out_path} ({out_path.stat().st_size/1024:.1f} KB)")
644
+
645
+ # Quick sanity: top 20 raw QIDs and their assigned metro
646
+ print("\nTop 20 raw QIDs and their metro assignment:")
647
+ print(f" {'qid':10s} {'raw_label':25s} {'->target':10s} target_label")
648
+ for q, n in big[:20]:
649
+ target = metro_map.get(q, q)
650
+ rl = label_map.get(q, '?')[:25]
651
+ tl = label_map.get(target, '?')[:25]
652
+ print(f" {q:10s} {rl:25s} -> {target:10s} {tl} ({n:,} CIs)")
653
+
654
+
655
+ if __name__ == "__main__":
656
+ main()
_scripts/01_consolidate_filter.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 1 of the Trip World build pipeline.
3
+
4
+ Reads raw ${STD_2018_PATH}, applies
5
+ metro_mapping_clean.json to the venue_city QID (producing region_id),
6
+ then enforces:
7
+
8
+ (a) POI popularity: drop POIs with < 2 visits in the *consolidated* stream
9
+ (b) Region density: drop regions with < 100 distinct POIs after (a)
10
+
11
+ Output: _intermediate/checkins_consolidated.parquet
12
+ Columns: trail_id, user_id, venue_id, venue_category, venue_schema,
13
+ venue_city_qid, venue_country_qid, ts, region_id
14
+ (Same schema as the precursor build/checkins_filtered.parquet so
15
+ downstream stages can reuse the same query patterns.)
16
+ """
17
+ import duckdb, json, os, time
18
+ from pathlib import Path
19
+
20
+ ROOT = Path(os.environ.get("TRIP_WORLD_ROOT", Path(__file__).resolve().parent.parent))
21
+ RAW = os.environ["STD_2018_PATH"]
22
+ MAP = ROOT / "metro_mapping_clean.json"
23
+ OUT = ROOT / "_intermediate" / "checkins_consolidated.parquet"
24
+ OUT.parent.mkdir(parents=True, exist_ok=True)
25
+
26
+ t0 = time.time()
27
+ def step(msg): print(f"[{time.time()-t0:6.1f}s] {msg}", flush=True)
28
+
29
+ # Load metro map
30
+ mm = json.load(MAP.open())["metro_map"]
31
+ step(f"loaded metro_map ({len(mm):,} entries, {sum(1 for k,v in mm.items() if k!=v):,} non-identity)")
32
+
33
+ # Materialise as a small parquet (DuckDB joins efficiently against parquet)
34
+ import pyarrow as pa, pyarrow.parquet as pq
35
+ import os
36
+ mm_tbl = pa.Table.from_pylist([{"raw": k, "metro": v} for k, v in mm.items()])
37
+ mm_path = ROOT / "_intermediate" / "metro_map.parquet"
38
+ pq.write_table(mm_tbl, mm_path, compression="zstd")
39
+ step(f"wrote {mm_path}")
40
+
41
+ con = duckdb.connect()
42
+ con.execute("PRAGMA threads=32")
43
+ con.execute("SET memory_limit='48GB'")
44
+ con.execute("SET preserve_insertion_order=false")
45
+ con.execute(f"SET temp_directory='{os.environ.get('DUCKDB_TMP_DIR', '/tmp/duckdb_trip_world')}'")
46
+
47
+ # ---------------- Step A: load raw stream + apply metro_map -------------------
48
+ step("loading raw std_2018.csv into DuckDB and applying metro_map ...")
49
+ con.execute(f"""
50
+ CREATE TABLE raw AS
51
+ SELECT
52
+ trail_id, user_id, venue_id, venue_category, venue_schema,
53
+ venue_city AS venue_city_qid,
54
+ venue_country AS venue_country_qid,
55
+ TRY_CAST(timestamp AS TIMESTAMPTZ) AS ts
56
+ FROM read_csv_auto('{RAW}', sample_size=-1)
57
+ """)
58
+ n_raw = con.execute("SELECT COUNT(*) FROM raw").fetchone()[0]
59
+ n_users = con.execute("SELECT COUNT(DISTINCT user_id) FROM raw").fetchone()[0]
60
+ n_pois = con.execute("SELECT COUNT(DISTINCT venue_id) FROM raw").fetchone()[0]
61
+ n_cities= con.execute("SELECT COUNT(DISTINCT venue_city_qid) FROM raw").fetchone()[0]
62
+ step(f" raw: {n_raw:,} rows, {n_users:,} users, {n_pois:,} POIs, {n_cities:,} venue_city QIDs")
63
+
64
+ # Strip "wd:" prefix to match metro_map keys, then left-join.
65
+ con.execute(f"""
66
+ CREATE TABLE consolidated AS
67
+ SELECT
68
+ raw.trail_id, raw.user_id, raw.venue_id, raw.venue_category, raw.venue_schema,
69
+ raw.venue_city_qid, raw.venue_country_qid, raw.ts,
70
+ COALESCE(mm.metro, REPLACE(raw.venue_city_qid, 'wd:', '')) AS region_id
71
+ FROM raw
72
+ LEFT JOIN read_parquet('{mm_path}') mm
73
+ ON mm.raw = REPLACE(raw.venue_city_qid, 'wd:', '')
74
+ """)
75
+ n_dist_regions = con.execute("SELECT COUNT(DISTINCT region_id) FROM consolidated").fetchone()[0]
76
+ step(f" consolidated: {n_dist_regions:,} distinct region_id values")
77
+
78
+ # ---------------- Step B: POI popularity filter -------------------------------
79
+ step("applying POI popularity filter (visits per POI >= 2) ...")
80
+ con.execute("""
81
+ CREATE TABLE poi_popular AS
82
+ SELECT venue_id FROM consolidated
83
+ GROUP BY venue_id HAVING COUNT(*) >= 2
84
+ """)
85
+ n_pop_pois = con.execute("SELECT COUNT(*) FROM poi_popular").fetchone()[0]
86
+ step(f" popular POIs: {n_pop_pois:,} (kept) of {n_pois:,}")
87
+
88
+ con.execute("""
89
+ CREATE TABLE filtered_pop AS
90
+ SELECT c.* FROM consolidated c JOIN poi_popular p USING (venue_id)
91
+ """)
92
+ n_pop_rows = con.execute("SELECT COUNT(*) FROM filtered_pop").fetchone()[0]
93
+ step(f" rows after popularity filter: {n_pop_rows:,}")
94
+
95
+ # ---------------- Step C: region density filter -------------------------------
96
+ step("applying region density filter (>= 100 distinct POIs per region) ...")
97
+ con.execute("""
98
+ CREATE TABLE region_dense AS
99
+ SELECT region_id FROM (
100
+ SELECT region_id, COUNT(DISTINCT venue_id) AS n_pois
101
+ FROM filtered_pop GROUP BY region_id
102
+ ) WHERE n_pois >= 100
103
+ """)
104
+ n_dense_regions = con.execute("SELECT COUNT(*) FROM region_dense").fetchone()[0]
105
+ step(f" dense regions: {n_dense_regions:,} (kept)")
106
+
107
+ con.execute(f"""
108
+ COPY (
109
+ SELECT f.* FROM filtered_pop f JOIN region_dense d USING (region_id)
110
+ ) TO '{OUT}' (FORMAT PARQUET, COMPRESSION 'zstd', ROW_GROUP_SIZE 50000)
111
+ """)
112
+ n_final = con.execute(f"SELECT COUNT(*) FROM read_parquet('{OUT}')").fetchone()[0]
113
+ n_final_users = con.execute(f"SELECT COUNT(DISTINCT user_id) FROM read_parquet('{OUT}')").fetchone()[0]
114
+ n_final_pois = con.execute(f"SELECT COUNT(DISTINCT venue_id) FROM read_parquet('{OUT}')").fetchone()[0]
115
+ n_final_reg = con.execute(f"SELECT COUNT(DISTINCT region_id) FROM read_parquet('{OUT}')").fetchone()[0]
116
+ sz = OUT.stat().st_size / 1e6
117
+
118
+ print()
119
+ print("=== Stage 1 output ===")
120
+ print(f" file: {OUT} ({sz:.1f} MB)")
121
+ print(f" rows: {n_final:,}")
122
+ print(f" users: {n_final_users:,}")
123
+ print(f" POIs: {n_final_pois:,}")
124
+ print(f" dense regions: {n_final_reg:,}")
125
+ print(f" total elapsed: {time.time()-t0:.1f}s")
_scripts/02_hometown_discovery.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 2 of the Trip World build pipeline: hometown discovery.
3
+
4
+ For each user u, compute the supporting value
5
+ phi(u, r) = sum_{c_i in r} theta^(-delta_t_i / T) / (N + eps)
6
+ across each candidate region r the user has check-ins in. Pick r_h = argmax phi,
7
+ then drop users whose hometown has fewer than --min-home-ci check-ins.
8
+
9
+ Constants
10
+ ---------
11
+ theta = 2 (matches the doc; halves weight every T days)
12
+ T = 180 days (typical "season" window)
13
+ eps = 1 (denominator regulariser)
14
+ observation_time = MAX(ts) in the consolidated stream
15
+
16
+ Output: _intermediate/users_hometown.parquet
17
+ Columns: user_id, r_h, phi_home, n_home_ci
18
+ """
19
+ import duckdb, time, math
20
+ from pathlib import Path
21
+ import os
22
+
23
+ ROOT = Path(os.environ.get("TRIP_WORLD_ROOT", Path(__file__).resolve().parent.parent))
24
+ IN = ROOT / "_intermediate" / "checkins_consolidated.parquet"
25
+ OUT = ROOT / "_intermediate" / "users_hometown.parquet"
26
+
27
+ THETA = 2.0
28
+ T_DAYS = 180.0
29
+ EPS = 1.0
30
+ MIN_HOME_CI = 4
31
+
32
+ t0 = time.time()
33
+ def step(msg): print(f"[{time.time()-t0:6.1f}s] {msg}", flush=True)
34
+
35
+ con = duckdb.connect()
36
+ con.execute("PRAGMA threads=32")
37
+ con.execute("SET memory_limit='48GB'")
38
+ con.execute("SET preserve_insertion_order=false")
39
+ con.execute(f"SET temp_directory='{os.environ.get('DUCKDB_TMP_DIR', '/tmp/duckdb_trip_world')}'")
40
+
41
+ # Determine observation_time (max ts in stream) once.
42
+ obs_ts = con.execute(f"SELECT MAX(ts) FROM read_parquet('{IN}')").fetchone()[0]
43
+ step(f"observation time: {obs_ts}")
44
+
45
+ # Compute phi(u, r) per (user, region) and N (total CIs) per user, then pick winner.
46
+ # delta_t in days = epoch_seconds(obs_ts - ts) / 86400
47
+ step("computing phi(u, r) and selecting hometown ...")
48
+ con.execute(f"""
49
+ CREATE TABLE phi AS
50
+ WITH per_user_total AS (
51
+ SELECT user_id, COUNT(*) AS N
52
+ FROM read_parquet('{IN}')
53
+ GROUP BY user_id
54
+ ),
55
+ weighted AS (
56
+ SELECT user_id, region_id,
57
+ POW({THETA}, -EXTRACT(EPOCH FROM (TIMESTAMP '{obs_ts}' - ts)) / 86400.0 / {T_DAYS}) AS w
58
+ FROM read_parquet('{IN}')
59
+ )
60
+ SELECT w.user_id,
61
+ w.region_id,
62
+ SUM(w.w) AS sum_w,
63
+ COUNT(*) AS n_ci,
64
+ SUM(w.w) / (any_value(t.N) + {EPS}) AS phi
65
+ FROM weighted w
66
+ JOIN per_user_total t USING (user_id)
67
+ GROUP BY w.user_id, w.region_id
68
+ """)
69
+ step(f" phi rows: {con.execute('SELECT COUNT(*) FROM phi').fetchone()[0]:,}")
70
+
71
+ # Pick hometown = argmax phi per user
72
+ step("picking r_h = argmax phi per user ...")
73
+ con.execute("""
74
+ CREATE TABLE users_hometown_raw AS
75
+ SELECT user_id, region_id AS r_h, phi AS phi_home, n_ci AS n_home_ci
76
+ FROM (
77
+ SELECT *,
78
+ ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY phi DESC, n_ci DESC, region_id) AS rn
79
+ FROM phi
80
+ )
81
+ WHERE rn = 1
82
+ """)
83
+ n_users_pre = con.execute("SELECT COUNT(*) FROM users_hometown_raw").fetchone()[0]
84
+ step(f" candidate hometowns assigned: {n_users_pre:,} users")
85
+
86
+ # Filter: |c_h| >= MIN_HOME_CI
87
+ step(f"applying |c_h| >= {MIN_HOME_CI} filter ...")
88
+ con.execute(f"""
89
+ COPY (
90
+ SELECT user_id, r_h, phi_home, n_home_ci
91
+ FROM users_hometown_raw
92
+ WHERE n_home_ci >= {MIN_HOME_CI}
93
+ ORDER BY user_id
94
+ ) TO '{OUT}' (FORMAT PARQUET, COMPRESSION 'zstd')
95
+ """)
96
+ n_kept = con.execute(f"SELECT COUNT(*) FROM read_parquet('{OUT}')").fetchone()[0]
97
+ n_dist_homes = con.execute(f"SELECT COUNT(DISTINCT r_h) FROM read_parquet('{OUT}')").fetchone()[0]
98
+ sz = OUT.stat().st_size / 1e6
99
+ print()
100
+ print("=== Stage 2 output ===")
101
+ print(f" file: {OUT} ({sz:.1f} MB)")
102
+ print(f" users with hometown: {n_kept:,} (dropped {n_users_pre-n_kept:,})")
103
+ print(f" distinct hometowns: {n_dist_homes:,}")
104
+ print(f" total elapsed: {time.time()-t0:.1f}s")
_scripts/03_build_travelers.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 3 of the Trip World build pipeline.
3
+
4
+ Given users_hometown.parquet (each user's r_h) and the consolidated check-in
5
+ stream, identify (user, r_o) pairs where:
6
+ (a) r_o != r_h
7
+ (b) the user has at least --min-travel-ci check-ins in r_o
8
+ (c) the (r_h, r_o) pair appears at least --min-pair-freq times across users
9
+
10
+ Output: _intermediate/travelers.parquet
11
+ Columns: user_id, r_h, r_o, n_home_ci, n_travel_ci
12
+ """
13
+ import duckdb, time
14
+ from pathlib import Path
15
+ import os
16
+
17
+ ROOT = Path(os.environ.get("TRIP_WORLD_ROOT", Path(__file__).resolve().parent.parent))
18
+ INC = ROOT / "_intermediate" / "checkins_consolidated.parquet"
19
+ INH = ROOT / "_intermediate" / "users_hometown.parquet"
20
+ OUT = ROOT / "_intermediate" / "travelers.parquet"
21
+
22
+ MIN_TRAVEL_CI = 2
23
+ MIN_PAIR_FREQ = 10
24
+
25
+ t0 = time.time()
26
+ def step(msg): print(f"[{time.time()-t0:6.1f}s] {msg}", flush=True)
27
+
28
+ con = duckdb.connect()
29
+ con.execute("PRAGMA threads=32")
30
+ con.execute("SET memory_limit='48GB'")
31
+ con.execute("SET preserve_insertion_order=false")
32
+ con.execute(f"SET temp_directory='{os.environ.get('DUCKDB_TMP_DIR', '/tmp/duckdb_trip_world')}'")
33
+
34
+ # --- Step A: per (user, region) check-in counts -------------------------------
35
+ step("counting check-ins per (user, region) ...")
36
+ con.execute(f"""
37
+ CREATE TABLE ur_counts AS
38
+ SELECT user_id, region_id, COUNT(*) AS n_ci
39
+ FROM read_parquet('{INC}')
40
+ GROUP BY user_id, region_id
41
+ """)
42
+
43
+ # --- Step B: candidate destination tuples (user, r_h, r_o, n_travel_ci) -------
44
+ step("forming candidate (user, r_h, r_o, n_travel_ci) tuples ...")
45
+ con.execute(f"""
46
+ CREATE TABLE candidates AS
47
+ SELECT
48
+ h.user_id,
49
+ h.r_h,
50
+ c.region_id AS r_o,
51
+ h.n_home_ci,
52
+ c.n_ci AS n_travel_ci
53
+ FROM read_parquet('{INH}') h
54
+ JOIN ur_counts c USING (user_id)
55
+ WHERE c.region_id <> h.r_h
56
+ AND c.n_ci >= {MIN_TRAVEL_CI}
57
+ """)
58
+ n_cand = con.execute("SELECT COUNT(*) FROM candidates").fetchone()[0]
59
+ step(f" candidates after |c_o| >= {MIN_TRAVEL_CI}: {n_cand:,}")
60
+
61
+ # --- Step C: pair frequency filter -------------------------------------------
62
+ step(f"applying (r_h, r_o) pair frequency >= {MIN_PAIR_FREQ} filter ...")
63
+ con.execute(f"""
64
+ CREATE TABLE pair_freq AS
65
+ SELECT r_h, r_o, COUNT(*) AS pair_n
66
+ FROM candidates GROUP BY r_h, r_o HAVING pair_n >= {MIN_PAIR_FREQ}
67
+ """)
68
+ n_pairs = con.execute("SELECT COUNT(*) FROM pair_freq").fetchone()[0]
69
+ step(f" pairs surviving: {n_pairs:,}")
70
+
71
+ con.execute(f"""
72
+ COPY (
73
+ SELECT c.user_id, c.r_h, c.r_o, c.n_home_ci, c.n_travel_ci
74
+ FROM candidates c JOIN pair_freq p USING (r_h, r_o)
75
+ ORDER BY c.user_id
76
+ ) TO '{OUT}' (FORMAT PARQUET, COMPRESSION 'zstd', ROW_GROUP_SIZE 50000)
77
+ """)
78
+
79
+ n_kept = con.execute(f"SELECT COUNT(*) FROM read_parquet('{OUT}')").fetchone()[0]
80
+ n_users = con.execute(f"SELECT COUNT(DISTINCT user_id) FROM read_parquet('{OUT}')").fetchone()[0]
81
+ n_homes = con.execute(f"SELECT COUNT(DISTINCT r_h) FROM read_parquet('{OUT}')").fetchone()[0]
82
+ n_dests = con.execute(f"SELECT COUNT(DISTINCT r_o) FROM read_parquet('{OUT}')").fetchone()[0]
83
+
84
+ # Sanity: there must be ZERO phantom rows (r_h == r_o) by construction
85
+ n_phantom = con.execute(f"SELECT COUNT(*) FROM read_parquet('{OUT}') WHERE r_h = r_o").fetchone()[0]
86
+
87
+ print()
88
+ print("=== Stage 3 output ===")
89
+ print(f" file: {OUT} ({OUT.stat().st_size/1e6:.1f} MB)")
90
+ print(f" travel-behavior rows: {n_kept:,}")
91
+ print(f" unique travelers: {n_users:,}")
92
+ print(f" unique hometowns: {n_homes:,}")
93
+ print(f" unique destinations: {n_dests:,}")
94
+ print(f" unique pairs: {n_pairs:,}")
95
+ print(f" phantom rows: {n_phantom} (must be 0)")
96
+ print(f" total elapsed: {time.time()-t0:.1f}s")
_scripts/04_build_travel_behaviors.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 4: assemble the final travel_behaviors.parquet (one row per τ).
3
+
4
+ Joins travelers + consolidated check-ins, packing each user's hometown / travel
5
+ check-in sequence into list<struct> columns. Schema matches the precursor build:
6
+
7
+ user_id int64
8
+ r_h, r_o string (bare metro QID, no 'wd:' prefix)
9
+ n_home_ci int64
10
+ n_travel_ci int64
11
+ c_h list<struct{trail_id, venue_id, venue_category, venue_schema, ts}>
12
+ c_o list<struct<...same...>>
13
+ """
14
+ import duckdb, time, os
15
+ from pathlib import Path
16
+ import os
17
+
18
+ ROOT = Path(os.environ.get("TRIP_WORLD_ROOT", Path(__file__).resolve().parent.parent))
19
+ INC = ROOT / "_intermediate" / "checkins_consolidated.parquet"
20
+ INT = ROOT / "_intermediate" / "travelers.parquet"
21
+ OUT = ROOT / "travel_behaviors.parquet"
22
+
23
+ t0 = time.time()
24
+ def step(msg): print(f"[{time.time()-t0:6.1f}s] {msg}", flush=True)
25
+
26
+ con = duckdb.connect()
27
+ con.execute("PRAGMA threads=32")
28
+ con.execute("SET memory_limit='48GB'")
29
+ con.execute("SET preserve_insertion_order=false")
30
+ con.execute(f"SET temp_directory='{os.environ.get('DUCKDB_TMP_DIR', '/tmp/duckdb_trip_world')}'")
31
+
32
+ step("loading inputs ...")
33
+ con.execute(f"CREATE TABLE travelers AS SELECT * FROM '{INT}'")
34
+ con.execute(f"""
35
+ CREATE TABLE ck AS
36
+ SELECT user_id, region_id, trail_id, venue_id, venue_category, venue_schema, ts
37
+ FROM '{INC}'
38
+ """)
39
+ n_tr = con.execute("SELECT COUNT(*) FROM travelers").fetchone()[0]
40
+ n_ck = con.execute("SELECT COUNT(*) FROM ck").fetchone()[0]
41
+ step(f" travelers: {n_tr:,}, check-ins: {n_ck:,}")
42
+
43
+ step("building per-(user, region) ordered check-in lists ...")
44
+ con.execute("""
45
+ CREATE TABLE user_region_seq AS
46
+ SELECT
47
+ user_id, region_id,
48
+ list({
49
+ 'trail_id': trail_id,
50
+ 'venue_id': venue_id,
51
+ 'venue_category': venue_category,
52
+ 'venue_schema': venue_schema,
53
+ 'ts': ts
54
+ } ORDER BY ts) AS seq
55
+ FROM ck
56
+ GROUP BY user_id, region_id
57
+ """)
58
+ n_seq = con.execute("SELECT COUNT(*) FROM user_region_seq").fetchone()[0]
59
+ step(f" user-region sequences: {n_seq:,}")
60
+
61
+ step(f"writing {OUT} ...")
62
+ con.execute(f"""
63
+ COPY (
64
+ SELECT
65
+ t.user_id, t.r_h, t.r_o, t.n_home_ci, t.n_travel_ci,
66
+ h.seq AS c_h,
67
+ o.seq AS c_o
68
+ FROM travelers t
69
+ LEFT JOIN user_region_seq h ON h.user_id = t.user_id AND h.region_id = t.r_h
70
+ LEFT JOIN user_region_seq o ON o.user_id = t.user_id AND o.region_id = t.r_o
71
+ ) TO '{OUT}' (FORMAT PARQUET, COMPRESSION 'zstd', ROW_GROUP_SIZE 50000)
72
+ """)
73
+ sz = OUT.stat().st_size / 1e6
74
+
75
+ # Verify
76
+ r = con.execute(f"""
77
+ SELECT
78
+ COUNT(*) AS n_rows,
79
+ COUNT(DISTINCT user_id) AS n_users,
80
+ COUNT(DISTINCT r_h) AS n_homes,
81
+ COUNT(DISTINCT r_o) AS n_dests,
82
+ SUM(CASE WHEN r_h = r_o THEN 1 ELSE 0 END) AS n_phantom,
83
+ SUM(CASE WHEN c_h IS NULL THEN 1 ELSE 0 END) AS missing_c_h,
84
+ SUM(CASE WHEN c_o IS NULL THEN 1 ELSE 0 END) AS missing_c_o,
85
+ AVG(len(c_h))::DOUBLE AS avg_ch,
86
+ AVG(len(c_o))::DOUBLE AS avg_co
87
+ FROM '{OUT}'
88
+ """).fetchone()
89
+
90
+ print()
91
+ print("=== Stage 4 output ===")
92
+ print(f" file: {OUT} ({sz:.1f} MB)")
93
+ for k, v in zip(['rows','users','homes','dests','phantom','missing_c_h','missing_c_o','avg_c_h','avg_c_o'], r):
94
+ if isinstance(v, (int,)):
95
+ print(f" {k:14s}: {v:,}")
96
+ else:
97
+ print(f" {k:14s}: {v:.2f}")
98
+ print(f" total elapsed: {time.time()-t0:.1f}s")
_scripts/05_build_pois.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 5: build $TRIP_WORLD_ROOT/pois.parquet
3
+
4
+ For every POI that survives the Trip World build pipeline (i.e. appears in
5
+ checkins_consolidated.parquet, which already enforces popularity >= 2 AND
6
+ region density >= 100), inherit per-POI metadata (FSQ-OS + Google + review
7
+ counts) from a precursor build at $PRECURSOR_BUILD_ROOT/pois.parquet, and
8
+ re-map the `locality` column with the Trip World metro map.
9
+
10
+ The $PRECURSOR_BUILD_ROOT env var should point at a previous output of this
11
+ same pipeline whose POI metadata we want to extend; if you are bootstrapping
12
+ from scratch you can either skip this stage or supply an empty parquet — POIs
13
+ not present in the precursor will simply carry NULLs for the inherited
14
+ FSQ-OS / Google / review-count fields.
15
+ """
16
+ import duckdb, json, time
17
+ from pathlib import Path
18
+ import os
19
+
20
+ ROOT = Path(os.environ.get("TRIP_WORLD_ROOT", Path(__file__).resolve().parent.parent))
21
+ INC = ROOT / "_intermediate" / "checkins_consolidated.parquet"
22
+ V1_POIS = str(Path(os.environ["PRECURSOR_BUILD_ROOT"]) / "pois.parquet")
23
+ MM = ROOT / "_intermediate" / "metro_map.parquet"
24
+ OUT = ROOT / "pois.parquet"
25
+
26
+ t0 = time.time()
27
+ def step(msg): print(f"[{time.time()-t0:6.1f}s] {msg}", flush=True)
28
+
29
+ con = duckdb.connect()
30
+ con.execute("PRAGMA threads=32")
31
+ con.execute("SET memory_limit='32GB'")
32
+ con.execute(f"SET temp_directory='{os.environ.get('DUCKDB_TMP_DIR', '/tmp/duckdb_trip_world')}'")
33
+
34
+ step("collecting per-POI visit counts and locality from clean checkins ...")
35
+ con.execute(f"""
36
+ CREATE TABLE poi_facts AS
37
+ SELECT
38
+ venue_id AS fsq_place_id,
39
+ ANY_VALUE(region_id) AS locality, -- region_id == metro QID under clean map
40
+ ANY_VALUE(venue_category) AS venue_category,
41
+ ANY_VALUE(venue_schema) AS venue_schema,
42
+ COUNT(*) AS n_checkins,
43
+ COUNT(DISTINCT user_id) AS n_users_visited
44
+ FROM '{INC}' GROUP BY 1
45
+ """)
46
+ n_pois = con.execute("SELECT COUNT(*) FROM poi_facts").fetchone()[0]
47
+ step(f" {n_pois:,} surviving POIs")
48
+
49
+ step("loading precursor pois.parquet for metadata inheritance ...")
50
+ con.execute(f"CREATE TABLE prev AS SELECT * FROM '{V1_POIS}'")
51
+
52
+ step("writing clean pois.parquet (left join on precursor metadata, locality from clean) ...")
53
+ con.execute(f"""
54
+ COPY (
55
+ SELECT
56
+ pf.fsq_place_id,
57
+ pf.locality,
58
+ pf.venue_category,
59
+ pf.venue_schema,
60
+ pf.n_checkins::BIGINT AS n_checkins,
61
+ pf.n_users_visited::BIGINT AS n_users_visited,
62
+ p.google_cid, p.google_name, p.google_full_address, p.google_address,
63
+ p.google_website, p.google_rating, p.google_num_reviews, p.google_categories,
64
+ p.google_place_id, p.google_gmaps_url,
65
+ COALESCE(p.google_meta_source, 'none') AS google_meta_source,
66
+ COALESCE(p.has_google_metadata, FALSE) AS has_google_metadata,
67
+ COALESCE(p.n_reviews, 0)::BIGINT AS n_reviews,
68
+ COALESCE(p.n_reviews_with_text, 0)::BIGINT AS n_reviews_with_text,
69
+ p.review_source,
70
+ COALESCE(p.has_reviews, FALSE) AS has_reviews
71
+ FROM poi_facts pf
72
+ LEFT JOIN prev p USING (fsq_place_id)
73
+ ) TO '{OUT}' (FORMAT PARQUET, COMPRESSION 'zstd', ROW_GROUP_SIZE 200000)
74
+ """)
75
+
76
+ # Verify
77
+ r = con.execute(f"""
78
+ SELECT COUNT(*),
79
+ SUM(CASE WHEN has_google_metadata THEN 1 ELSE 0 END),
80
+ SUM(CASE WHEN has_reviews THEN 1 ELSE 0 END),
81
+ SUM(n_reviews), SUM(n_reviews_with_text)
82
+ FROM '{OUT}'
83
+ """).fetchone()
84
+ sz = OUT.stat().st_size / 1e6
85
+ print()
86
+ print("=== Stage 5 output ===")
87
+ print(f" file: {OUT} ({sz:.1f} MB)")
88
+ print(f" POIs: {r[0]:,}")
89
+ print(f" with Google meta: {r[1]:,} ({r[1]/r[0]*100:.1f}%)")
90
+ print(f" with reviews: {r[2]:,} ({r[2]/r[0]*100:.1f}%)")
91
+ print(f" total reviews: {r[3]:,}")
92
+ print(f" total reviews w/text:{r[4]:,}")
93
+ print(f" total elapsed: {time.time()-t0:.1f}s")
_scripts/06_build_region_labels.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 6: build $TRIP_WORLD_ROOT/region_labels.parquet
3
+
4
+ For every region_id that appears as r_h or r_o in the clean travel_behaviors,
5
+ emit one row with: region_id, city_name, country_qid, country_name.
6
+
7
+ The country is the dominant venue_country_qid among check-ins in that region
8
+ (matches the precursor logic).
9
+ """
10
+ import duckdb, json, pyarrow as pa, pyarrow.parquet as pq, time
11
+ from pathlib import Path
12
+ import os
13
+
14
+ ROOT = Path(os.environ.get("TRIP_WORLD_ROOT", Path(__file__).resolve().parent.parent))
15
+ INC = ROOT / "_intermediate" / "checkins_consolidated.parquet"
16
+ TB = ROOT / "travel_behaviors.parquet"
17
+ MAP = ROOT / "metro_mapping_clean.json"
18
+ OUT = ROOT / "region_labels.parquet"
19
+
20
+ t0 = time.time()
21
+ def step(msg): print(f"[{time.time()-t0:6.1f}s] {msg}", flush=True)
22
+
23
+ labels = json.load(MAP.open())["labels"]
24
+ step(f"loaded {len(labels):,} labels from metro_mapping_clean.json")
25
+
26
+ con = duckdb.connect()
27
+ con.execute("PRAGMA threads=16")
28
+
29
+ # All distinct region IDs in benchmark
30
+ qids = set(r[0] for r in con.execute(f"""
31
+ SELECT DISTINCT r_h FROM '{TB}'
32
+ UNION
33
+ SELECT DISTINCT r_o FROM '{TB}'
34
+ """).fetchall())
35
+ step(f" {len(qids):,} distinct benchmark region IDs")
36
+
37
+ # Dominant country per region
38
+ con.execute(f"""
39
+ CREATE TABLE rc AS
40
+ SELECT region_id, venue_country_qid AS country_qid, COUNT(*) AS n
41
+ FROM '{INC}' GROUP BY 1, 2
42
+ """)
43
+ con.execute("""
44
+ CREATE TABLE rc_top AS
45
+ SELECT region_id, country_qid, n
46
+ FROM (
47
+ SELECT *, ROW_NUMBER() OVER (PARTITION BY region_id ORDER BY n DESC) AS rn
48
+ FROM rc
49
+ ) WHERE rn = 1
50
+ """)
51
+ country_map = {r[0]: r[1] for r in con.execute(
52
+ "SELECT region_id, country_qid FROM rc_top").fetchall()}
53
+ step(f" built country map for {len(country_map):,} regions")
54
+
55
+ rows = []
56
+ n_no_city = n_no_ctry = 0
57
+ for qid in sorted(qids):
58
+ bare = qid.replace("wd:", "")
59
+ city_name = labels.get(bare)
60
+ if not city_name:
61
+ n_no_city += 1
62
+ cq = country_map.get(qid)
63
+ cq_bare = cq.replace("wd:", "") if cq else None
64
+ cn = labels.get(cq_bare) if cq_bare else None
65
+ if not cn:
66
+ n_no_ctry += 1
67
+ rows.append({
68
+ "region_id": qid,
69
+ "city_name": city_name,
70
+ "country_qid": f"wd:{cq_bare}" if cq_bare else None,
71
+ "country_name": cn,
72
+ })
73
+
74
+ tbl = pa.Table.from_pylist(rows)
75
+ pq.write_table(tbl, OUT, compression="zstd")
76
+ sz = OUT.stat().st_size / 1024
77
+ print()
78
+ print("=== Stage 6 output ===")
79
+ print(f" file: {OUT} ({sz:.1f} KB)")
80
+ print(f" rows: {len(rows):,}")
81
+ print(f" with city_name: {len(rows) - n_no_city:,} ({(len(rows)-n_no_city)/len(rows)*100:.1f}%)")
82
+ print(f" with country_name: {len(rows) - n_no_ctry:,}")
83
+ print(f" total elapsed: {time.time()-t0:.1f}s")
_scripts/07_subset_metadata.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 7: subset metadata/metadata_all.parquet to only POIs in Trip World.
3
+ Output: $TRIP_WORLD_ROOT/metadata/metadata_all.parquet
4
+ """
5
+ import duckdb, time, os
6
+ from pathlib import Path
7
+ import os
8
+
9
+ ROOT = Path(os.environ.get("TRIP_WORLD_ROOT", Path(__file__).resolve().parent.parent))
10
+ SRC = str(Path(os.environ["PRECURSOR_BUILD_ROOT"]) / "metadata" / "metadata_all.parquet")
11
+ POIS = ROOT / "pois.parquet"
12
+ OUT = ROOT / "metadata" / "metadata_all.parquet"
13
+ OUT.parent.mkdir(parents=True, exist_ok=True)
14
+
15
+ t0 = time.time()
16
+ def step(msg): print(f"[{time.time()-t0:6.1f}s] {msg}", flush=True)
17
+
18
+ con = duckdb.connect()
19
+ con.execute("PRAGMA threads=32")
20
+ con.execute("SET memory_limit='32GB'")
21
+
22
+ step(f"reading Trip World POI universe from {POIS}")
23
+ con.execute(f"CREATE TABLE keep_ids AS SELECT fsq_place_id FROM '{POIS}'")
24
+ n_keep = con.execute("SELECT COUNT(*) FROM keep_ids").fetchone()[0]
25
+ step(f" {n_keep:,} clean POIs to keep")
26
+
27
+ step(f"streaming subset of {SRC} ...")
28
+ con.execute(f"""
29
+ COPY (
30
+ SELECT m.* FROM '{SRC}' m
31
+ SEMI JOIN keep_ids k USING (fsq_place_id)
32
+ ) TO '{OUT}' (FORMAT PARQUET, COMPRESSION 'zstd', ROW_GROUP_SIZE 200000)
33
+ """)
34
+ n_out = con.execute(f"SELECT COUNT(*) FROM '{OUT}'").fetchone()[0]
35
+ sz = OUT.stat().st_size / 1e6
36
+ print()
37
+ print("=== Stage 7 output ===")
38
+ print(f" file: {OUT} ({sz:.1f} MB)")
39
+ print(f" metadata rows: {n_out:,} of {n_keep:,} POIs ({n_out/n_keep*100:.1f}% covered)")
40
+ print(f" total elapsed: {time.time()-t0:.1f}s")
_scripts/08_subset_reviews.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 8: subset reviews/reviews_all.parquet to only POIs in Trip World.
3
+
4
+ Source precursor reviews/ contains six per-source parquet files plus a unified
5
+ reviews_all.parquet (~13 GB). We only re-emit the unified file -- it's
6
+ the only one downstream pipelines actually read (reviews_*.parquet glob
7
+ matches reviews_all.parquet so it's de-facto the canonical).
8
+ """
9
+ import duckdb, time
10
+ from pathlib import Path
11
+ import os
12
+
13
+ ROOT = Path(os.environ.get("TRIP_WORLD_ROOT", Path(__file__).resolve().parent.parent))
14
+ SRC = str(Path(os.environ["PRECURSOR_BUILD_ROOT"]) / "reviews" / "reviews_all.parquet")
15
+ POIS = ROOT / "pois.parquet"
16
+ OUT = ROOT / "reviews" / "reviews_all.parquet"
17
+ OUT.parent.mkdir(parents=True, exist_ok=True)
18
+
19
+ t0 = time.time()
20
+ def step(msg): print(f"[{time.time()-t0:6.1f}s] {msg}", flush=True)
21
+
22
+ con = duckdb.connect()
23
+ con.execute("PRAGMA threads=32")
24
+ con.execute("SET memory_limit='48GB'")
25
+ con.execute("SET preserve_insertion_order=false")
26
+ con.execute(f"SET temp_directory='{os.environ.get('DUCKDB_TMP_DIR', '/tmp/duckdb_trip_world')}'")
27
+
28
+ step(f"reading Trip World POI universe from {POIS}")
29
+ con.execute(f"CREATE TABLE keep_ids AS SELECT fsq_place_id FROM '{POIS}'")
30
+ n_keep = con.execute("SELECT COUNT(*) FROM keep_ids").fetchone()[0]
31
+ step(f" {n_keep:,} POIs to keep")
32
+
33
+ step(f"streaming + filtering {SRC} ... (this takes a few minutes)")
34
+ con.execute(f"""
35
+ COPY (
36
+ SELECT r.* FROM '{SRC}' r
37
+ SEMI JOIN keep_ids k USING (fsq_place_id)
38
+ ) TO '{OUT}' (FORMAT PARQUET, COMPRESSION 'zstd', ROW_GROUP_SIZE 200000)
39
+ """)
40
+ n_rev = con.execute(f"SELECT COUNT(*) FROM '{OUT}'").fetchone()[0]
41
+ n_pois_with_reviews = con.execute(
42
+ f"SELECT COUNT(DISTINCT fsq_place_id) FROM '{OUT}'").fetchone()[0]
43
+ sz = OUT.stat().st_size / 1e6
44
+ print()
45
+ print("=== Stage 8 output ===")
46
+ print(f" file: {OUT} ({sz/1024:.2f} GB)")
47
+ print(f" reviews: {n_rev:,}")
48
+ print(f" POIs with reviews: {n_pois_with_reviews:,} of {n_keep:,}")
49
+ print(f" total elapsed: {time.time()-t0:.1f}s")
_scripts/09_validate.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 9: validate Trip World and write README.md.
3
+
4
+ Validations:
5
+ - travel_behaviors: 0 rows where r_h == r_o
6
+ - travel_behaviors: every r_h, r_o is in region_labels.parquet
7
+ - pois: every fsq_place_id in checkins_consolidated also in pois.parquet
8
+ - region_labels: every region_id is reached by some travel record
9
+ """
10
+ import duckdb, json, time, os
11
+ from pathlib import Path
12
+
13
+ ROOT = Path(os.environ.get("TRIP_WORLD_ROOT", Path(__file__).resolve().parent.parent))
14
+ TB = ROOT / "travel_behaviors.parquet"
15
+ POIS = ROOT / "pois.parquet"
16
+ RL = ROOT / "region_labels.parquet"
17
+ META = ROOT / "metadata" / "metadata_all.parquet"
18
+ REVIEWS = ROOT / "reviews" / "reviews_all.parquet"
19
+ INC = ROOT / "_intermediate" / "checkins_consolidated.parquet"
20
+ MAP = ROOT / "metro_mapping_clean.json"
21
+
22
+ t0 = time.time()
23
+ def step(msg): print(f"[{time.time()-t0:6.1f}s] {msg}", flush=True)
24
+
25
+ con = duckdb.connect()
26
+ con.execute("PRAGMA threads=32")
27
+ con.execute("SET memory_limit='32GB'")
28
+
29
+ # ---- validations ----
30
+ step("validating ...")
31
+ v = {}
32
+ v["tb_rows"] = con.execute(f"SELECT COUNT(*) FROM '{TB}'").fetchone()[0]
33
+ v["tb_phantom"] = con.execute(f"SELECT COUNT(*) FROM '{TB}' WHERE r_h = r_o").fetchone()[0]
34
+ v["tb_users"] = con.execute(f"SELECT COUNT(DISTINCT user_id) FROM '{TB}'").fetchone()[0]
35
+ v["tb_homes"] = con.execute(f"SELECT COUNT(DISTINCT r_h) FROM '{TB}'").fetchone()[0]
36
+ v["tb_dests"] = con.execute(f"SELECT COUNT(DISTINCT r_o) FROM '{TB}'").fetchone()[0]
37
+ v["tb_pairs"] = con.execute(f"SELECT COUNT(*) FROM (SELECT DISTINCT r_h, r_o FROM '{TB}')").fetchone()[0]
38
+ v["tb_avg_ch"] = con.execute(f"SELECT AVG(n_home_ci) FROM '{TB}'").fetchone()[0]
39
+ v["tb_avg_co"] = con.execute(f"SELECT AVG(n_travel_ci) FROM '{TB}'").fetchone()[0]
40
+ v["tb_unique_ci_h"] = con.execute(f"""
41
+ SELECT SUM(n) FROM (
42
+ SELECT user_id, ANY_VALUE(n_home_ci) AS n FROM '{TB}' GROUP BY user_id
43
+ )
44
+ """).fetchone()[0]
45
+ v["tb_total_ci_o"] = con.execute(f"SELECT SUM(n_travel_ci) FROM '{TB}'").fetchone()[0]
46
+ v["tb_total_ci"] = v["tb_unique_ci_h"] + v["tb_total_ci_o"]
47
+
48
+ v["pois_rows"] = con.execute(f"SELECT COUNT(*) FROM '{POIS}'").fetchone()[0]
49
+ v["pois_with_meta"] = con.execute(f"SELECT SUM(CASE WHEN has_google_metadata THEN 1 ELSE 0 END) FROM '{POIS}'").fetchone()[0]
50
+ v["pois_with_rev"] = con.execute(f"SELECT SUM(CASE WHEN has_reviews THEN 1 ELSE 0 END) FROM '{POIS}'").fetchone()[0]
51
+ v["pois_total_reviews"] = con.execute(f"SELECT SUM(n_reviews) FROM '{POIS}'").fetchone()[0]
52
+ v["pois_reviews_text"] = con.execute(f"SELECT SUM(n_reviews_with_text) FROM '{POIS}'").fetchone()[0]
53
+
54
+ v["rl_rows"] = con.execute(f"SELECT COUNT(*) FROM '{RL}'").fetchone()[0]
55
+
56
+ # referential integrity
57
+ v["rh_missing_in_rl"] = con.execute(f"""
58
+ SELECT COUNT(*) FROM (
59
+ SELECT DISTINCT r_h FROM '{TB}' EXCEPT SELECT region_id FROM '{RL}'
60
+ )
61
+ """).fetchone()[0]
62
+ v["ro_missing_in_rl"] = con.execute(f"""
63
+ SELECT COUNT(*) FROM (
64
+ SELECT DISTINCT r_o FROM '{TB}' EXCEPT SELECT region_id FROM '{RL}'
65
+ )
66
+ """).fetchone()[0]
67
+
68
+ # distinct trails in c_h ∪ c_o
69
+ v["distinct_trails"] = con.execute(f"""
70
+ SELECT COUNT(DISTINCT trail_id) FROM (
71
+ SELECT UNNEST(c_h).trail_id AS trail_id FROM '{TB}'
72
+ UNION ALL
73
+ SELECT UNNEST(c_o).trail_id AS trail_id FROM '{TB}'
74
+ )
75
+ """).fetchone()[0]
76
+
77
+ # time span
78
+ ts_range = con.execute(f"""
79
+ SELECT MIN(ts), MAX(ts) FROM (
80
+ SELECT UNNEST(c_h).ts AS ts FROM '{TB}'
81
+ UNION ALL
82
+ SELECT UNNEST(c_o).ts AS ts FROM '{TB}'
83
+ )
84
+ """).fetchone()
85
+ v["ts_min"], v["ts_max"] = ts_range
86
+
87
+ step("done validating")
88
+ for k, val in v.items():
89
+ print(f" {k:24s}: {val}")
90
+
91
+ # The public-facing README.md is maintained separately and ships at the
92
+ # top level of the dataset release; this script does not regenerate it.
93
+ # The validation results above are sufficient to confirm a successful build.
94
+ print(f"\n total elapsed: {time.time()-t0:.1f}s")
_scripts/10_enrich_new_pois.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 10 (post-build enrichment): hydrate the NEW POIs (those in the clean
3
+ benchmark but absent from precursor metadata) with FSQ-OS December-2024 lat/lon and
4
+ the rest of the FSQ metadata fields.
5
+
6
+ Step A: Identify new-POI universe = pois.parquet - metadata_all.parquet
7
+ Step B: SEMI JOIN against the LOCAL FSQ-OS Dec 2024 dump
8
+ (${FSQ_OS_PARQUET_GLOB})
9
+ Step C: Append the resolved rows to metadata_all.parquet (rewriting it)
10
+ Step D: Dump the unresolved fsq_place_id list to fsq_unresolved.txt for
11
+ downstream FSQ Places API recovery.
12
+
13
+ After this stage:
14
+ metadata/metadata_all.parquet carries FSQ rows for the precursor build
15
+ plus the locally-resolved newly-added POIs
16
+ fsq_unresolved.txt lists POIs needing the FSQ API
17
+ """
18
+ import duckdb, time
19
+ from pathlib import Path
20
+ import os
21
+
22
+ ROOT = Path(os.environ.get("TRIP_WORLD_ROOT", Path(__file__).resolve().parent.parent))
23
+ POIS = ROOT / "pois.parquet"
24
+ META = ROOT / "metadata" / "metadata_all.parquet"
25
+ FSQ_OS = os.environ["FSQ_OS_PARQUET_GLOB"]
26
+ UNRES = ROOT / "fsq_unresolved.txt"
27
+
28
+ t0 = time.time()
29
+ def step(msg): print(f"[{time.time()-t0:6.1f}s] {msg}", flush=True)
30
+
31
+ con = duckdb.connect()
32
+ con.execute("PRAGMA threads=32")
33
+ con.execute("SET memory_limit='48GB'")
34
+ con.execute("SET preserve_insertion_order=false")
35
+ con.execute(f"SET temp_directory='{os.environ.get('DUCKDB_TMP_DIR', '/tmp/duckdb_trip_world')}'")
36
+
37
+ # ---- A. find new POIs (in clean but not yet in metadata_all) -----------------
38
+ step("identifying new POIs (in clean pois.parquet but not in metadata_all) ...")
39
+ con.execute(f"""
40
+ CREATE TABLE clean_pois AS
41
+ SELECT fsq_place_id, locality, venue_category, venue_schema
42
+ FROM '{POIS}'
43
+ """)
44
+ con.execute(f"""
45
+ CREATE TABLE existing_meta_ids AS
46
+ SELECT fsq_place_id FROM '{META}'
47
+ """)
48
+ con.execute("""
49
+ CREATE TABLE new_ids AS
50
+ SELECT cp.fsq_place_id, cp.locality, cp.venue_category, cp.venue_schema,
51
+ regexp_replace(cp.fsq_place_id, '^foursquare:', '') AS bare_id
52
+ FROM clean_pois cp
53
+ ANTI JOIN existing_meta_ids e USING (fsq_place_id)
54
+ """)
55
+ n_new = con.execute("SELECT COUNT(*) FROM new_ids").fetchone()[0]
56
+ step(f" {n_new:,} new POIs to enrich")
57
+
58
+ if n_new == 0:
59
+ print("Nothing to do.")
60
+ raise SystemExit(0)
61
+
62
+ # ---- B. resolve from local FSQ-OS Dec 2024 dump ------------------------------
63
+ step("looking up new POIs in local FSQ-OS Dec 2024 dump (~6.8 GB, may take ~1 min) ...")
64
+ con.execute(f"""
65
+ CREATE TABLE resolved_local AS
66
+ SELECT
67
+ ('foursquare:' || fsq.fsq_place_id) AS fsq_place_id,
68
+ fsq.name AS fsq_name,
69
+ fsq.latitude AS fsq_latitude,
70
+ fsq.longitude AS fsq_longitude,
71
+ fsq.address AS fsq_address,
72
+ fsq.locality AS fsq_locality,
73
+ fsq.region AS fsq_region,
74
+ fsq.country AS fsq_country,
75
+ fsq.postcode AS fsq_postcode,
76
+ CASE WHEN fsq.address IS NOT NULL OR fsq.locality IS NOT NULL
77
+ THEN concat_ws(', ', fsq.address, fsq.locality, fsq.region, fsq.country) END AS fsq_formatted_address,
78
+ fsq.fsq_category_ids,
79
+ fsq.fsq_category_labels,
80
+ fsq.website AS fsq_website,
81
+ fsq.tel AS fsq_tel,
82
+ fsq.email AS fsq_email,
83
+ fsq.facebook_id AS fsq_facebook_id,
84
+ fsq.instagram AS fsq_instagram,
85
+ fsq.twitter AS fsq_twitter,
86
+ fsq.date_created AS fsq_date_created,
87
+ fsq.date_refreshed AS fsq_date_refreshed,
88
+ fsq.date_closed AS fsq_date_closed,
89
+ 'fsq_os_dec_2024' AS fsq_meta_source,
90
+ TRUE AS has_fsq_metadata
91
+ FROM read_parquet('{FSQ_OS}') fsq
92
+ SEMI JOIN new_ids n ON n.bare_id = fsq.fsq_place_id
93
+ """)
94
+ n_resolved = con.execute("SELECT COUNT(*) FROM resolved_local").fetchone()[0]
95
+ step(f" {n_resolved:,} new POIs resolved locally ({n_resolved/n_new*100:.1f}% coverage)")
96
+
97
+ # ---- C. write expanded metadata_all.parquet ---------------------------------
98
+ # Approach: read existing META + resolved_local + remaining nulls, UNION ALL.
99
+ step("writing expanded metadata_all.parquet ...")
100
+
101
+ # Bench-side fields for new POIs (carry through locality/category/schema as benchmark_*).
102
+ con.execute("""
103
+ CREATE TABLE new_bench AS
104
+ SELECT fsq_place_id,
105
+ NULL AS benchmark_name,
106
+ locality AS benchmark_locality,
107
+ venue_category AS benchmark_venue_category,
108
+ venue_schema AS benchmark_venue_schema
109
+ FROM new_ids
110
+ """)
111
+
112
+ # A row for every new POI: bench fields + (resolved or null) FSQ + null Google fields.
113
+ META_TMP = ROOT / "metadata" / "metadata_all_v2.parquet"
114
+ con.execute(f"""
115
+ COPY (
116
+ -- existing rows
117
+ SELECT * FROM '{META}'
118
+ UNION ALL BY NAME
119
+ -- new rows: left-join resolved_local, fill nulls for missing
120
+ SELECT
121
+ nb.fsq_place_id,
122
+ nb.benchmark_name,
123
+ nb.benchmark_locality,
124
+ nb.benchmark_venue_category,
125
+ nb.benchmark_venue_schema,
126
+ rl.fsq_name, rl.fsq_latitude, rl.fsq_longitude,
127
+ rl.fsq_address, rl.fsq_locality, rl.fsq_region, rl.fsq_country,
128
+ rl.fsq_postcode, rl.fsq_formatted_address,
129
+ rl.fsq_category_ids, rl.fsq_category_labels,
130
+ rl.fsq_website, rl.fsq_tel, rl.fsq_email,
131
+ rl.fsq_facebook_id, rl.fsq_instagram, rl.fsq_twitter,
132
+ rl.fsq_date_created, rl.fsq_date_refreshed, rl.fsq_date_closed,
133
+ COALESCE(rl.fsq_meta_source, 'unresolved') AS fsq_meta_source,
134
+ COALESCE(rl.has_fsq_metadata, FALSE) AS has_fsq_metadata,
135
+ NULL AS google_cid, NULL AS google_name,
136
+ NULL AS google_full_address, NULL AS google_address,
137
+ NULL AS google_website, NULL AS google_rating, NULL AS google_num_reviews,
138
+ NULL AS google_categories, NULL AS google_place_id, NULL AS google_gmaps_url,
139
+ 'none' AS google_meta_source,
140
+ FALSE AS has_google_metadata
141
+ FROM new_bench nb
142
+ LEFT JOIN resolved_local rl USING (fsq_place_id)
143
+ ) TO '{META_TMP}' (FORMAT PARQUET, COMPRESSION 'zstd', ROW_GROUP_SIZE 200000)
144
+ """)
145
+
146
+ # Atomic swap
147
+ META.unlink()
148
+ META_TMP.rename(META)
149
+ n_meta_total = con.execute(f"SELECT COUNT(*) FROM '{META}'").fetchone()[0]
150
+ n_meta_with_fsq = con.execute(f"SELECT SUM(CASE WHEN has_fsq_metadata THEN 1 ELSE 0 END) FROM '{META}'").fetchone()[0]
151
+ n_meta_with_coords = con.execute(f"SELECT SUM(CASE WHEN fsq_latitude IS NOT NULL THEN 1 ELSE 0 END) FROM '{META}'").fetchone()[0]
152
+ sz = META.stat().st_size / 1e6
153
+ step(f" metadata_all.parquet now has {n_meta_total:,} rows ({sz:.0f} MB)")
154
+
155
+ # ---- D. write unresolved list -----------------------------------------------
156
+ n_unres = n_new - n_resolved
157
+ con.execute(f"""
158
+ COPY (
159
+ SELECT n.fsq_place_id
160
+ FROM new_ids n
161
+ ANTI JOIN resolved_local rl USING (fsq_place_id)
162
+ ORDER BY 1
163
+ ) TO '{UNRES}' (HEADER FALSE, DELIMITER ' ')
164
+ """)
165
+ step(f" {n_unres:,} POIs still unresolved -> {UNRES}")
166
+
167
+ print()
168
+ print("=== Stage 10 output ===")
169
+ print(f" metadata rows total: {n_meta_total:,} ({n_meta_total/687173*100:.1f}% of POI universe)")
170
+ print(f" rows with FSQ metadata: {n_meta_with_fsq:,} ({n_meta_with_fsq/n_meta_total*100:.1f}%)")
171
+ print(f" rows with lat/lon: {n_meta_with_coords:,} ({n_meta_with_coords/n_meta_total*100:.1f}%)")
172
+ print(f" POIs needing FSQ API: {n_unres:,}")
173
+ print(f" total elapsed: {time.time()-t0:.1f}s")
_scripts/11_fsq_api_recover.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 11 (optional): recover the remaining unresolved POIs via the FSQ Places
3
+ API.
4
+
5
+ Reads fsq_unresolved.txt (output of Stage 10 -- ~37k entries), hits
6
+ GET https://places-api.foursquare.com/places/{fsq_id} for each, and writes the
7
+ resolved metadata into _intermediate/fsq_api_resolved.parquet. Then folds
8
+ the resolved rows into metadata/metadata_all.parquet.
9
+
10
+ Requires a Foursquare Places API key:
11
+ export FSQ_API_KEY=fsq3xxxxxxxxxxxxxxxxxxxxxxxx
12
+ or pass --api-key on the command line.
13
+
14
+ Rate-limit / retry policy
15
+ -------------------------
16
+ * Default 5 concurrent requests, 250 ms inter-request delay (~20 req/s).
17
+ Adjust with --concurrency / --delay.
18
+ * On HTTP 429: exponential backoff up to --max-backoff seconds.
19
+ * On HTTP 404: POI is permanently gone; record empty row with status='gone'.
20
+ * On HTTP 5xx: retry up to 3 times before recording status='error'.
21
+
22
+ Output
23
+ ------
24
+ * _intermediate/fsq_api_resolved.parquet (one row per requested ID + status)
25
+ * metadata/metadata_all.parquet (rewritten with the new rows merged)
26
+ * fsq_unresolved.txt (rewritten with only POIs that
27
+ failed permanently)
28
+ """
29
+ from __future__ import annotations
30
+ import argparse, asyncio, json, os, ssl, sys, time
31
+ from pathlib import Path
32
+ from typing import Iterable
33
+ import urllib.parse
34
+ import os
35
+
36
+ ROOT = Path(os.environ.get("TRIP_WORLD_ROOT", Path(__file__).resolve().parent.parent))
37
+ META = ROOT / "metadata" / "metadata_all.parquet"
38
+ UNRES_IN = ROOT / "fsq_unresolved.txt"
39
+ UNRES_OUT = ROOT / "fsq_unresolved.txt"
40
+ RESOLVED = ROOT / "_intermediate" / "fsq_api_resolved.parquet"
41
+ CHECKPOINT = ROOT / "_intermediate" / "fsq_api_checkpoint.jsonl" # incremental, append-only
42
+
43
+ API_BASE = "https://places-api.foursquare.com/places"
44
+ SERVICE_ACCOUNT_ID = "fsq3" # marker for fsq_meta_source
45
+
46
+ _ssl = ssl.create_default_context()
47
+
48
+
49
+ class KeyPool:
50
+ """Round-robin pool of API keys with dead-key tracking.
51
+
52
+ A key is marked DEAD when the API responds with HTTP 402 OR a 429 whose
53
+ body contains 'no API credits' (Foursquare's free-tier exhaustion message).
54
+ Other 429s (true rate-limiting) trigger backoff but keep the key alive.
55
+ """
56
+ def __init__(self, keys: list[str]):
57
+ self.keys = list(dict.fromkeys(k.strip() for k in keys if k.strip()))
58
+ self.alive = list(self.keys)
59
+ self._cursor = 0
60
+
61
+ @property
62
+ def n_alive(self) -> int:
63
+ return len(self.alive)
64
+
65
+ @property
66
+ def n_total(self) -> int:
67
+ return len(self.keys)
68
+
69
+ def next_key(self) -> str | None:
70
+ """Return any live key (round-robin). None if pool is empty."""
71
+ if not self.alive:
72
+ return None
73
+ k = self.alive[self._cursor % len(self.alive)]
74
+ self._cursor += 1
75
+ return k
76
+
77
+ def mark_dead(self, key: str, reason: str = "") -> None:
78
+ if key in self.alive:
79
+ self.alive.remove(key)
80
+ tail = key[-8:]
81
+ print(f" [key pool] key ...{tail} marked dead "
82
+ f"({reason}); alive={self.n_alive}/{self.n_total}",
83
+ flush=True)
84
+
85
+
86
+ def _is_no_credits(status: int, body_text: str) -> bool:
87
+ if status == 402:
88
+ return True
89
+ if status == 429 and ("no API credits" in body_text
90
+ or "Purchasing credits" in body_text):
91
+ return True
92
+ return False
93
+
94
+
95
+ async def fetch_one(session, sem, fsq_id: str, pool: KeyPool, delay: float,
96
+ max_backoff: float) -> dict:
97
+ """Fetch one FSQ place by ID with retry/backoff and key rotation."""
98
+ bare = fsq_id.replace("foursquare:", "")
99
+ url = f"{API_BASE}/{urllib.parse.quote(bare)}"
100
+ backoff = 1.0
101
+ for attempt in range(6):
102
+ api_key = pool.next_key()
103
+ if api_key is None:
104
+ return {"fsq_place_id": fsq_id, "status": "no_credits", "raw": None}
105
+ auth = api_key if api_key.lower().startswith("bearer ") else f"Bearer {api_key}"
106
+ headers = {"Authorization": auth,
107
+ "X-Places-Api-Version": "2025-06-17",
108
+ "Accept": "application/json"}
109
+ async with sem:
110
+ await asyncio.sleep(delay)
111
+ try:
112
+ async with session.get(url, headers=headers, ssl=_ssl,
113
+ timeout=30) as r:
114
+ if r.status == 200:
115
+ body = await r.json()
116
+ return {"fsq_place_id": fsq_id, "status": "ok",
117
+ "raw": body}
118
+ elif r.status == 404:
119
+ return {"fsq_place_id": fsq_id, "status": "gone",
120
+ "raw": None}
121
+ elif r.status in (402, 429):
122
+ body_text = await r.text()
123
+ if _is_no_credits(r.status, body_text):
124
+ pool.mark_dead(api_key, f"HTTP {r.status} no_credits")
125
+ continue # try next key on next attempt
126
+ retry_after = float(r.headers.get("Retry-After", backoff))
127
+ await asyncio.sleep(min(retry_after, max_backoff))
128
+ backoff = min(backoff * 2, max_backoff)
129
+ continue
130
+ elif 500 <= r.status < 600:
131
+ await asyncio.sleep(min(backoff, max_backoff))
132
+ backoff = min(backoff * 2, max_backoff)
133
+ continue
134
+ else:
135
+ body = await r.text()
136
+ return {"fsq_place_id": fsq_id,
137
+ "status": f"http_{r.status}",
138
+ "raw": {"error": body[:500]}}
139
+ except Exception as e:
140
+ await asyncio.sleep(min(backoff, max_backoff))
141
+ backoff = min(backoff * 2, max_backoff)
142
+ return {"fsq_place_id": fsq_id, "status": "error", "raw": None}
143
+
144
+
145
+ async def driver(ids: list[str], pool: KeyPool, concurrency: int, delay: float,
146
+ max_backoff: float, checkpoint_path: Path,
147
+ progress_every: int = 500):
148
+ import aiohttp
149
+ connector = aiohttp.TCPConnector(limit=concurrency, force_close=False)
150
+ sem = asyncio.Semaphore(concurrency)
151
+ out = []
152
+ n = len(ids)
153
+ t0 = time.time()
154
+ last_log = 0
155
+ # Append-only JSONL so we can resume mid-run if interrupted.
156
+ checkpoint_path.parent.mkdir(parents=True, exist_ok=True)
157
+ with open(checkpoint_path, "a", buffering=1) as ckpt:
158
+ async with aiohttp.ClientSession(connector=connector) as session:
159
+ tasks = [fetch_one(session, sem, fsq_id, pool, delay, max_backoff)
160
+ for fsq_id in ids]
161
+ for i, coro in enumerate(asyncio.as_completed(tasks), 1):
162
+ r = await coro
163
+ out.append(r)
164
+ ckpt.write(json.dumps(r, ensure_ascii=False) + "\n")
165
+ if i - last_log >= progress_every:
166
+ last_log = i
167
+ rate = i / (time.time() - t0 + 1e-9)
168
+ eta = (n - i) / max(rate, 1e-9)
169
+ ok = sum(1 for x in out if x["status"] == "ok")
170
+ gone = sum(1 for x in out if x["status"] == "gone")
171
+ nc = sum(1 for x in out if x["status"] == "no_credits")
172
+ err = i - ok - gone - nc
173
+ print(f" [{time.time()-t0:5.0f}s] {i:>6}/{n} "
174
+ f"ok={ok} gone={gone} nc={nc} err={err} "
175
+ f"{rate:.1f} req/s ETA={eta/60:.1f} min "
176
+ f"keys_alive={pool.n_alive}/{pool.n_total}", flush=True)
177
+ if pool.n_alive == 0:
178
+ print(f" !! all keys exhausted; cancelling remaining {n-i} tasks",
179
+ flush=True)
180
+ break
181
+ return out
182
+
183
+
184
+ def fsq_payload_to_row(p: dict, fsq_id: str) -> dict:
185
+ """Map an FSQ Places API (2025-06-17 version) response onto our schema.
186
+
187
+ The new API returns lat/lon at the top level (not nested under geocodes),
188
+ and categories use `fsq_category_id`/`name` keys.
189
+ """
190
+ if not p:
191
+ return {"fsq_place_id": fsq_id, "has_fsq_metadata": False,
192
+ "fsq_meta_source": "fsq_api_gone"}
193
+ loc = p.get("location", {}) or {}
194
+ cats = p.get("categories", []) or []
195
+ facebook_id = (p.get("social_media") or {}).get("facebook_id")
196
+ try:
197
+ facebook_id = int(facebook_id) if facebook_id else None
198
+ except (TypeError, ValueError):
199
+ facebook_id = None
200
+ return {
201
+ "fsq_place_id": fsq_id,
202
+ "fsq_name": p.get("name"),
203
+ "fsq_latitude": p.get("latitude"),
204
+ "fsq_longitude": p.get("longitude"),
205
+ "fsq_address": loc.get("address"),
206
+ "fsq_locality": loc.get("locality"),
207
+ "fsq_region": loc.get("region"),
208
+ "fsq_country": loc.get("country"),
209
+ "fsq_postcode": loc.get("postcode"),
210
+ "fsq_formatted_address": loc.get("formatted_address"),
211
+ "fsq_category_ids": [str(c.get("fsq_category_id")) for c in cats
212
+ if c.get("fsq_category_id") is not None],
213
+ "fsq_category_labels": [c.get("name") for c in cats if c.get("name")],
214
+ "fsq_website": p.get("website"),
215
+ "fsq_tel": p.get("tel"),
216
+ "fsq_email": p.get("email"),
217
+ "fsq_facebook_id": facebook_id,
218
+ "fsq_instagram": (p.get("social_media") or {}).get("instagram"),
219
+ "fsq_twitter": (p.get("social_media") or {}).get("twitter"),
220
+ "fsq_date_created": (p.get("date_created") or None),
221
+ "fsq_date_refreshed": (p.get("date_refreshed") or None),
222
+ "fsq_date_closed": (p.get("date_closed") or None),
223
+ "fsq_meta_source": "fsq_api_2025",
224
+ "has_fsq_metadata": True,
225
+ }
226
+
227
+
228
+ def main():
229
+ ap = argparse.ArgumentParser()
230
+ ap.add_argument("--api-key", action="append", default=[],
231
+ help="FSQ Places API bearer token (repeat for multiple keys)")
232
+ ap.add_argument("--api-keys-file",
233
+ help="path to a file containing one bearer token per line")
234
+ ap.add_argument("--concurrency", type=int, default=5)
235
+ ap.add_argument("--delay", type=float, default=0.20,
236
+ help="seconds between consecutive requests per worker")
237
+ ap.add_argument("--max-backoff", type=float, default=30.0)
238
+ ap.add_argument("--limit", type=int, default=0,
239
+ help="if >0, only process the first N unresolved IDs (smoke test)")
240
+ args = ap.parse_args()
241
+
242
+ keys: list[str] = list(args.api_key)
243
+ if args.api_keys_file:
244
+ keys.extend(l.strip() for l in Path(args.api_keys_file).read_text().splitlines()
245
+ if l.strip() and not l.strip().startswith("#"))
246
+ if not keys and os.environ.get("FSQ_API_KEY"):
247
+ keys.append(os.environ["FSQ_API_KEY"].strip())
248
+ keys = list(dict.fromkeys(keys)) # de-dup, preserve order
249
+ if not keys:
250
+ print("ERROR: no FSQ API key. Pass --api-key, --api-keys-file or "
251
+ "set $FSQ_API_KEY.")
252
+ sys.exit(1)
253
+ pool = KeyPool(keys)
254
+ print(f"Loaded {pool.n_total} API key(s) into pool "
255
+ f"(masked: {[k[-8:] for k in pool.keys]})")
256
+
257
+ try:
258
+ import aiohttp # noqa
259
+ except ImportError:
260
+ print("ERROR: aiohttp not installed. Run: pip install aiohttp")
261
+ sys.exit(1)
262
+ import duckdb
263
+ import pyarrow as pa, pyarrow.parquet as pq
264
+
265
+ ids = [l.strip() for l in UNRES_IN.read_text().splitlines() if l.strip()]
266
+
267
+ # Resume support: skip any IDs that already appear in the JSONL checkpoint
268
+ # with a TERMINAL status (ok / gone). Transient errors will be retried.
269
+ already = {}
270
+ if CHECKPOINT.exists():
271
+ with open(CHECKPOINT) as f:
272
+ for line in f:
273
+ try:
274
+ rec = json.loads(line)
275
+ except Exception:
276
+ continue
277
+ if rec.get("status") in ("ok", "gone"):
278
+ already[rec["fsq_place_id"]] = rec
279
+ if already:
280
+ print(f"Resumed checkpoint: skipping {len(already):,} already-resolved ids")
281
+ ids = [i for i in ids if i not in already]
282
+
283
+ if args.limit:
284
+ ids = ids[:args.limit]
285
+ print(f"Will resolve {len(ids):,} POI IDs via FSQ Places API")
286
+ print(f" concurrency={args.concurrency} delay={args.delay}s "
287
+ f"target rate ~{args.concurrency/args.delay:.1f} req/s")
288
+ print()
289
+
290
+ raw_new = asyncio.run(driver(ids, pool, args.concurrency, args.delay,
291
+ args.max_backoff, CHECKPOINT))
292
+ raw = list(already.values()) + raw_new
293
+
294
+ # Build rows
295
+ rows = []
296
+ n_ok = n_gone = n_err = 0
297
+ for r in raw:
298
+ st = r["status"]
299
+ if st == "ok":
300
+ rows.append(fsq_payload_to_row(r["raw"], r["fsq_place_id"]))
301
+ n_ok += 1
302
+ elif st == "gone":
303
+ rows.append({"fsq_place_id": r["fsq_place_id"],
304
+ "fsq_meta_source": "fsq_api_gone",
305
+ "has_fsq_metadata": False})
306
+ n_gone += 1
307
+ else:
308
+ rows.append({"fsq_place_id": r["fsq_place_id"],
309
+ "fsq_meta_source": f"fsq_api_{st}",
310
+ "has_fsq_metadata": False})
311
+ n_err += 1
312
+ print(f"\nRESULT: ok={n_ok} gone={n_gone} err={n_err}")
313
+
314
+ # Write resolved table
315
+ RESOLVED.parent.mkdir(parents=True, exist_ok=True)
316
+ pq.write_table(pa.Table.from_pylist(rows), RESOLVED, compression="zstd")
317
+ print(f"wrote {RESOLVED} ({RESOLVED.stat().st_size/1e6:.1f} MB)")
318
+
319
+ # Fold into metadata_all.parquet
320
+ print("merging into metadata_all.parquet ...")
321
+ con = duckdb.connect()
322
+ con.execute("PRAGMA threads=32")
323
+ con.execute("SET memory_limit='32GB'")
324
+ META_TMP = META.with_suffix(".tmp.parquet")
325
+ con.execute(f"""
326
+ COPY (
327
+ -- existing rows MINUS the IDs we just refetched
328
+ SELECT * FROM '{META}'
329
+ WHERE fsq_place_id NOT IN (SELECT fsq_place_id FROM '{RESOLVED}')
330
+ UNION ALL BY NAME
331
+ -- the new rows (use CAST/COALESCE to keep schema compatible)
332
+ SELECT
333
+ r.fsq_place_id,
334
+ NULL AS benchmark_name,
335
+ NULL AS benchmark_locality,
336
+ NULL AS benchmark_venue_category,
337
+ NULL AS benchmark_venue_schema,
338
+ r.fsq_name, r.fsq_latitude, r.fsq_longitude,
339
+ r.fsq_address, r.fsq_locality, r.fsq_region, r.fsq_country,
340
+ r.fsq_postcode, r.fsq_formatted_address,
341
+ r.fsq_category_ids, r.fsq_category_labels,
342
+ r.fsq_website, r.fsq_tel, r.fsq_email,
343
+ r.fsq_facebook_id, r.fsq_instagram, r.fsq_twitter,
344
+ r.fsq_date_created, r.fsq_date_refreshed, r.fsq_date_closed,
345
+ r.fsq_meta_source, r.has_fsq_metadata,
346
+ NULL AS google_cid, NULL AS google_name,
347
+ NULL AS google_full_address, NULL AS google_address,
348
+ NULL AS google_website, NULL AS google_rating, NULL AS google_num_reviews,
349
+ NULL AS google_categories, NULL AS google_place_id, NULL AS google_gmaps_url,
350
+ 'none' AS google_meta_source,
351
+ FALSE AS has_google_metadata
352
+ FROM '{RESOLVED}' r
353
+ ) TO '{META_TMP}' (FORMAT PARQUET, COMPRESSION 'zstd', ROW_GROUP_SIZE 200000)
354
+ """)
355
+ META.unlink()
356
+ META_TMP.rename(META)
357
+ n_total = con.execute(f"SELECT COUNT(*) FROM '{META}'").fetchone()[0]
358
+ n_with_fsq = con.execute(f"SELECT SUM(CASE WHEN has_fsq_metadata THEN 1 ELSE 0 END) FROM '{META}'").fetchone()[0]
359
+ n_with_coords = con.execute(f"SELECT SUM(CASE WHEN fsq_latitude IS NOT NULL THEN 1 ELSE 0 END) FROM '{META}'").fetchone()[0]
360
+ print(f"metadata_all.parquet rewritten: {n_total:,} rows, "
361
+ f"{n_with_fsq:,} with FSQ ({n_with_fsq/n_total*100:.1f}%), "
362
+ f"{n_with_coords:,} with coords ({n_with_coords/n_total*100:.1f}%)")
363
+
364
+ # Update unresolved list: keep IDs we did NOT attempt this run (i.e. those
365
+ # left over because of --limit), and add back the IDs that errored out.
366
+ attempted = {r["fsq_place_id"] for r in raw}
367
+ failed = {r["fsq_place_id"] for r in raw if r["status"] not in ("ok", "gone")}
368
+ all_unres_now = [i for i in
369
+ [l.strip() for l in UNRES_IN.read_text().splitlines() if l.strip()]
370
+ if (i not in attempted) or (i in failed)]
371
+ UNRES_OUT.write_text("\n".join(all_unres_now))
372
+ print(f" remaining unresolved -> {UNRES_OUT} ({len(all_unres_now):,} ids)")
373
+
374
+
375
+ if __name__ == "__main__":
376
+ main()
_scripts/12_ucsd_bridge.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 12 (UCSD bridge): match the 81,592 NEW clean-benchmark POIs (those
3
+ absent from the precursor build) against the two UCSD POI corpora to inherit Google Maps
4
+ metadata + reviews for free.
5
+
6
+ Strategy
7
+ --------
8
+ The UCSD POIs use FSQ-OS (bare 24-hex) IDs while our benchmark uses FSQ v2
9
+ (`foursquare:<24-hex>`); the two ID spaces don't bridge directly. We
10
+ therefore do a SPATIAL + NAME-SIMILARITY match:
11
+
12
+ 1. Build a unified UCSD POI table (benchmark + all20) keyed by
13
+ (gmap_id, name, lat, lon, gmaps_*, gl_*).
14
+ 2. Bucket both sides into 0.005°-cells (~500 m) and inner-join on bucket.
15
+ 3. Keep candidate pairs within 100 m Haversine distance.
16
+ 4. Compute normalized-name similarity (rapidfuzz token_set_ratio).
17
+ 5. For each new POI, keep its best UCSD match if similarity >= 70 and
18
+ distance <= 100 m.
19
+
20
+ Outputs
21
+ -------
22
+ _intermediate/ucsd_matches.parquet one row per matched new-POI
23
+ _intermediate/ucsd_unified.parquet the unified UCSD source table
24
+
25
+ Empirically the 95 % precision quoted by the precursor README was achieved at
26
+ similarity >= 70 + distance <= 100 m; we keep those thresholds.
27
+ """
28
+ from __future__ import annotations
29
+ import json, math, os, time
30
+ from pathlib import Path
31
+ import duckdb
32
+ import pyarrow as pa, pyarrow.parquet as pq
33
+ from rapidfuzz import fuzz
34
+ from unidecode import unidecode
35
+ import os
36
+
37
+ ROOT = Path(os.environ.get("TRIP_WORLD_ROOT", Path(__file__).resolve().parent.parent))
38
+ GMAPS = Path(os.environ["GMAPS_FULL_ROOT"])
39
+ INTER = ROOT / "_intermediate"
40
+ INTER.mkdir(parents=True, exist_ok=True)
41
+
42
+ UCSD_BENCH = GMAPS / "metadata/ucsd_benchmark_pois.parquet"
43
+ UCSD_ALL20 = GMAPS / "metadata/ucsd_all20_pois.jsonl"
44
+ NEW_POIS_PARQ = INTER / "new_pois_for_match.parquet"
45
+ UCSD_UNIFIED = INTER / "ucsd_unified.parquet"
46
+ MATCHES_OUT = INTER / "ucsd_matches.parquet"
47
+
48
+ # Tunables (proven 95% precision on precursor build)
49
+ MAX_DIST_M = 100.0
50
+ MIN_NAME_SIM = 70.0
51
+ BUCKET_DEG = 0.005 # ~ 555 m
52
+
53
+
54
+ # ---------------------------------------------------------------------------
55
+ # Step 1. Build a unified UCSD POI table
56
+ # ---------------------------------------------------------------------------
57
+
58
+ def build_unified_ucsd() -> int:
59
+ """Materialise UCSD POIs from both sources into one parquet."""
60
+ print("[step 1] reading ucsd_all20_pois.jsonl ...")
61
+ rows_all20 = []
62
+ with open(UCSD_ALL20) as f:
63
+ for line in f:
64
+ try:
65
+ r = json.loads(line)
66
+ except Exception:
67
+ continue
68
+ lat = r.get("gl_latitude")
69
+ lon = r.get("gl_longitude")
70
+ if lat is None or lon is None:
71
+ continue
72
+ rows_all20.append({
73
+ "src": "all20",
74
+ "ucsd_fsq_os_id": r.get("fsq_place_id"),
75
+ "name": r.get("gl_name") or r.get("gmaps_name") or r.get("fsq_name"),
76
+ "lat": float(lat),
77
+ "lon": float(lon),
78
+ "gmap_id": r.get("gmap_id"),
79
+ "gmaps_name": r.get("gmaps_name"),
80
+ "gmaps_full_address": r.get("gmaps_full_address"),
81
+ "gmaps_address": r.get("gmaps_address"),
82
+ "gmaps_website": None,
83
+ "gmaps_rating": r.get("gmaps_rating"),
84
+ "gmaps_num_reviews": r.get("gmaps_num_reviews"),
85
+ "gmaps_categories": r.get("gmaps_categories"),
86
+ "gmaps_url": r.get("gmaps_url"),
87
+ "place_id": r.get("place_id"),
88
+ "gl_name": r.get("gl_name"),
89
+ "gl_address": r.get("gl_address"),
90
+ "gl_avg_rating": r.get("gl_avg_rating"),
91
+ "gl_num_reviews": r.get("gl_num_reviews"),
92
+ "gl_url": r.get("gl_url"),
93
+ "gl_category": r.get("gl_category"),
94
+ "gl_description": r.get("gl_description"),
95
+ "gl_price": r.get("gl_price"),
96
+ "gl_hours": r.get("gl_hours"),
97
+ "gl_state": r.get("gl_state"),
98
+ })
99
+ print(f" all20 rows with coords: {len(rows_all20):,}")
100
+
101
+ print("[step 1] reading ucsd_benchmark_pois.parquet ...")
102
+ # Bench file has no lat/lon columns, so extract them from `gmaps_url`
103
+ # (URLs of form .../@<lat>,<lon>,17z).
104
+ import re
105
+ LATLON_RE = re.compile(r"@(-?\d+\.\d+),(-?\d+\.\d+)")
106
+ con = duckdb.connect()
107
+ con.execute("PRAGMA threads=32")
108
+ bench_q = con.execute(f"""
109
+ SELECT fsq_place_id, fsq_name, cid AS gmap_id,
110
+ gmaps_name, gmaps_full_address, gmaps_address, gmaps_website,
111
+ gmaps_rating, gmaps_num_reviews, gmaps_categories, gmaps_url, place_id,
112
+ gl_name, gl_address, gl_avg_rating, gl_num_reviews, gl_url, gl_category,
113
+ gl_description, gl_price, gl_hours, gl_state
114
+ FROM '{UCSD_BENCH}' WHERE status='ok'
115
+ """)
116
+ bench_rows = bench_q.fetchall()
117
+ cols = [d[0] for d in bench_q.description]
118
+ rows_bench = []
119
+ for tup in bench_rows:
120
+ r = dict(zip(cols, tup))
121
+ url = r.get("gmaps_url") or r.get("gl_url") or ""
122
+ m = LATLON_RE.search(url or "")
123
+ if not m:
124
+ continue
125
+ rows_bench.append({
126
+ "src": "bench",
127
+ "ucsd_fsq_os_id": r["fsq_place_id"],
128
+ "name": r.get("gl_name") or r.get("gmaps_name") or r.get("fsq_name"),
129
+ "lat": float(m.group(1)),
130
+ "lon": float(m.group(2)),
131
+ "gmap_id": r["gmap_id"],
132
+ "gmaps_name": r.get("gmaps_name"),
133
+ "gmaps_full_address": r.get("gmaps_full_address"),
134
+ "gmaps_address": r.get("gmaps_address"),
135
+ "gmaps_website": r.get("gmaps_website"),
136
+ "gmaps_rating": r.get("gmaps_rating"),
137
+ "gmaps_num_reviews": r.get("gmaps_num_reviews"),
138
+ "gmaps_categories": r.get("gmaps_categories"),
139
+ "gmaps_url": r.get("gmaps_url"),
140
+ "place_id": r.get("place_id"),
141
+ "gl_name": r.get("gl_name"),
142
+ "gl_address": r.get("gl_address"),
143
+ "gl_avg_rating": r.get("gl_avg_rating"),
144
+ "gl_num_reviews": r.get("gl_num_reviews"),
145
+ "gl_url": r.get("gl_url"),
146
+ "gl_category": r.get("gl_category"),
147
+ "gl_description": r.get("gl_description"),
148
+ "gl_price": r.get("gl_price"),
149
+ "gl_hours": r.get("gl_hours"),
150
+ "gl_state": r.get("gl_state"),
151
+ })
152
+ print(f" bench rows with parsable coords: {len(rows_bench):,}")
153
+
154
+ all_rows = rows_all20 + rows_bench
155
+
156
+ # Normalize: cast list-typed columns to list-or-None; string-typed to str-or-None.
157
+ LIST_COLS = {"gmaps_categories", "gl_category", "gl_hours"}
158
+ STRING_COLS = {"src", "ucsd_fsq_os_id", "name", "gmap_id", "gmaps_name",
159
+ "gmaps_full_address", "gmaps_address", "gmaps_website",
160
+ "gmaps_url", "place_id",
161
+ "gl_name", "gl_address", "gl_url", "gl_description",
162
+ "gl_price", "gl_state"}
163
+ FLOAT_COLS = {"lat", "lon", "gmaps_rating", "gl_avg_rating"}
164
+ INT_COLS = {"gmaps_num_reviews", "gl_num_reviews"}
165
+ for r in all_rows:
166
+ for c in LIST_COLS:
167
+ v = r.get(c)
168
+ if v is None:
169
+ r[c] = None
170
+ elif isinstance(v, list):
171
+ r[c] = v
172
+ else:
173
+ r[c] = [str(v)]
174
+ for c in STRING_COLS:
175
+ v = r.get(c)
176
+ r[c] = None if v is None else (str(v) if not isinstance(v, str) else v)
177
+ for c in FLOAT_COLS:
178
+ v = r.get(c)
179
+ try: r[c] = None if v is None else float(v)
180
+ except (TypeError, ValueError): r[c] = None
181
+ for c in INT_COLS:
182
+ v = r.get(c)
183
+ try: r[c] = None if v is None else int(v)
184
+ except (TypeError, ValueError): r[c] = None
185
+
186
+ # Build with an explicit schema to avoid type inference surprises.
187
+ schema = pa.schema([
188
+ ("src", pa.string()),
189
+ ("ucsd_fsq_os_id", pa.string()),
190
+ ("name", pa.string()),
191
+ ("lat", pa.float64()),
192
+ ("lon", pa.float64()),
193
+ ("gmap_id", pa.string()),
194
+ ("gmaps_name", pa.string()),
195
+ ("gmaps_full_address", pa.string()),
196
+ ("gmaps_address", pa.string()),
197
+ ("gmaps_website", pa.string()),
198
+ ("gmaps_rating", pa.float64()),
199
+ ("gmaps_num_reviews", pa.int64()),
200
+ ("gmaps_categories", pa.list_(pa.string())),
201
+ ("gmaps_url", pa.string()),
202
+ ("place_id", pa.string()),
203
+ ("gl_name", pa.string()),
204
+ ("gl_address", pa.string()),
205
+ ("gl_avg_rating", pa.float64()),
206
+ ("gl_num_reviews", pa.int64()),
207
+ ("gl_url", pa.string()),
208
+ ("gl_category", pa.list_(pa.string())),
209
+ ("gl_description", pa.string()),
210
+ ("gl_price", pa.string()),
211
+ ("gl_hours", pa.list_(pa.list_(pa.string()))),
212
+ ("gl_state", pa.string()),
213
+ ])
214
+ table = pa.Table.from_pylist(all_rows, schema=schema)
215
+ pq.write_table(table, UCSD_UNIFIED, compression="zstd")
216
+ print(f" wrote unified table: {UCSD_UNIFIED} ({UCSD_UNIFIED.stat().st_size/1e6:.1f} MB, "
217
+ f"{len(all_rows):,} rows)")
218
+ return len(all_rows)
219
+
220
+
221
+ # ---------------------------------------------------------------------------
222
+ # Step 2-5. Bucket-join + filter
223
+ # ---------------------------------------------------------------------------
224
+
225
+ def haversine_m(lat1, lon1, lat2, lon2):
226
+ R = 6371000.0
227
+ p1 = math.radians(lat1); p2 = math.radians(lat2)
228
+ dp = math.radians(lat2 - lat1); dl = math.radians(lon2 - lon1)
229
+ a = math.sin(dp/2)**2 + math.cos(p1)*math.cos(p2)*math.sin(dl/2)**2
230
+ return 2*R*math.asin(min(1.0, math.sqrt(a)))
231
+
232
+
233
+ def normalize_name(s: str | None) -> str:
234
+ if not s: return ""
235
+ return unidecode(str(s)).lower().strip()
236
+
237
+
238
+ def run_bridge():
239
+ print(f"\n[step 2] bucket-join (cell={BUCKET_DEG}deg) ...")
240
+ con = duckdb.connect()
241
+ con.execute("PRAGMA threads=32")
242
+ con.execute(f"SET memory_limit='32GB'")
243
+
244
+ # Build candidate-pair table via bucket join, then keep only pairs where
245
+ # both POIs land in the same OR an immediately-adjacent cell.
246
+ # We expand "same cell" to a 3x3 neighborhood by joining on each of the 9
247
+ # offsets of the UCSD side.
248
+ con.execute(f"""
249
+ CREATE TEMP TABLE new_p AS
250
+ SELECT fsq_place_id AS new_id, fsq_name AS new_name, lat AS new_lat, lon AS new_lon,
251
+ FLOOR(lat / {BUCKET_DEG}) AS by_, FLOOR(lon / {BUCKET_DEG}) AS bx_
252
+ FROM '{NEW_POIS_PARQ}'
253
+ """)
254
+ con.execute(f"""
255
+ CREATE TEMP TABLE ucsd_p AS
256
+ SELECT * EXCLUDE (lat, lon),
257
+ lat AS u_lat, lon AS u_lon,
258
+ FLOOR(lat / {BUCKET_DEG}) AS by_, FLOOR(lon / {BUCKET_DEG}) AS bx_
259
+ FROM '{UCSD_UNIFIED}'
260
+ WHERE name IS NOT NULL
261
+ """)
262
+ n_new = con.execute("SELECT COUNT(*) FROM new_p").fetchone()[0]
263
+ n_ucsd = con.execute("SELECT COUNT(*) FROM ucsd_p").fetchone()[0]
264
+ print(f" new POIs: {n_new:,}")
265
+ print(f" ucsd POIs: {n_ucsd:,}")
266
+
267
+ # 3x3 neighborhood join on bucket coords (each of the 9 offsets).
268
+ # Avoid materialising all 9 unions in memory: compute candidate pairs
269
+ # straight to a temp table.
270
+ con.execute("""
271
+ CREATE TEMP TABLE cand AS
272
+ SELECT n.new_id, n.new_name, n.new_lat, n.new_lon,
273
+ u.ucsd_fsq_os_id, u.gmap_id, u.name AS u_name,
274
+ u.u_lat, u.u_lon, u.src
275
+ FROM new_p n
276
+ JOIN ucsd_p u
277
+ ON u.by_ BETWEEN n.by_ - 1 AND n.by_ + 1
278
+ AND u.bx_ BETWEEN n.bx_ - 1 AND n.bx_ + 1
279
+ """)
280
+ n_cand = con.execute("SELECT COUNT(*) FROM cand").fetchone()[0]
281
+ print(f"[step 3] candidate pairs (bucket-neighbors): {n_cand:,}")
282
+
283
+ if n_cand == 0:
284
+ print("no candidate pairs -- writing empty matches table")
285
+ empty = pa.table({c: pa.array([], type=pa.string()) for c in
286
+ ["fsq_place_id", "ucsd_fsq_os_id", "gmap_id", "match_src",
287
+ "distance_m", "name_sim"]})
288
+ pq.write_table(empty, MATCHES_OUT, compression="zstd")
289
+ return 0
290
+
291
+ # Pull into Python (list of tuples), score, and keep best per new_id.
292
+ print("[step 4] scoring (haversine + token_set_ratio) ...")
293
+ rows = con.execute("""
294
+ SELECT new_id, new_name, new_lat, new_lon, ucsd_fsq_os_id, gmap_id, u_name, u_lat, u_lon, src
295
+ FROM cand
296
+ """).fetchall()
297
+
298
+ best: dict[str, tuple[float, float, dict]] = {}
299
+ t0 = time.time()
300
+ n = len(rows)
301
+ eval_ct = 0
302
+ accept_ct = 0
303
+ for i, (new_id, new_name, n_lat, n_lon, ucsd_fsq_os_id, gmap_id, u_name, u_lat, u_lon, src) in enumerate(rows):
304
+ d = haversine_m(n_lat, n_lon, u_lat, u_lon)
305
+ if d > MAX_DIST_M:
306
+ continue
307
+ sim = fuzz.token_set_ratio(normalize_name(new_name), normalize_name(u_name))
308
+ eval_ct += 1
309
+ if sim < MIN_NAME_SIM:
310
+ continue
311
+ accept_ct += 1
312
+ # Score = sim - distance_in_m * 0.2 (favor close + similar)
313
+ score = sim - d * 0.2
314
+ prev = best.get(new_id)
315
+ if prev is None or score > prev[0]:
316
+ best[new_id] = (score, d, sim, gmap_id, ucsd_fsq_os_id, src)
317
+ if (i + 1) % 200_000 == 0:
318
+ rate = (i + 1) / (time.time() - t0)
319
+ eta = (n - i - 1) / max(rate, 1)
320
+ print(f" scored {i+1:>10,}/{n:,} rate {rate/1000:5.1f}k/s eta {eta:.0f}s "
321
+ f"so_far {len(best):,} matches")
322
+
323
+ print(f"\n[step 4] eval after distance filter: {eval_ct:,} accept: {accept_ct:,}")
324
+ print(f"[step 5] best-per-new-POI: {len(best):,} matches")
325
+
326
+ # Materialise matches table
327
+ out = []
328
+ for new_id, (score, d, sim, gmap_id, ucsd_fsq_os_id, src) in best.items():
329
+ out.append({"fsq_place_id": new_id, "ucsd_fsq_os_id": ucsd_fsq_os_id,
330
+ "gmap_id": gmap_id, "match_src": src,
331
+ "distance_m": d, "name_sim": sim})
332
+ if not out:
333
+ out = [{"fsq_place_id": "_dummy_", "ucsd_fsq_os_id": "", "gmap_id": "",
334
+ "match_src": "", "distance_m": 0.0, "name_sim": 0.0}][:0]
335
+ pq.write_table(pa.Table.from_pylist(out), MATCHES_OUT, compression="zstd")
336
+ print(f"wrote {MATCHES_OUT} ({MATCHES_OUT.stat().st_size/1e6:.2f} MB)")
337
+ return len(best)
338
+
339
+
340
+ def main():
341
+ if not UCSD_UNIFIED.exists():
342
+ build_unified_ucsd()
343
+ else:
344
+ print(f"reusing existing {UCSD_UNIFIED} "
345
+ f"({UCSD_UNIFIED.stat().st_size/1e6:.1f} MB)")
346
+ n = run_bridge()
347
+ print(f"\nDONE. matched {n:,} of 81,592 new POIs.")
348
+
349
+
350
+ if __name__ == "__main__":
351
+ main()
_scripts/13_merge_ucsd_into_metadata.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 13: fold the 1,608 UCSD-matched new POIs' Google metadata into
3
+ metadata_all.parquet.
4
+
5
+ For each matched POI we populate the existing google_* columns:
6
+ google_cid, google_name, google_full_address, google_address,
7
+ google_website, google_rating, google_num_reviews, google_categories,
8
+ google_place_id, google_gmaps_url, google_meta_source, has_google_metadata
9
+
10
+ `google_meta_source` is set to 'ucsd_<src>' (ucsd_all20 / ucsd_bench).
11
+
12
+ We DO NOT overwrite Google fields that are already populated for any POI
13
+ (none of the 1,608 should have any, but this safety check keeps the script
14
+ idempotent on re-run).
15
+ """
16
+ from __future__ import annotations
17
+ from pathlib import Path
18
+ import duckdb
19
+ import os
20
+
21
+ ROOT = Path(os.environ.get("TRIP_WORLD_ROOT", Path(__file__).resolve().parent.parent))
22
+ META = ROOT / "metadata" / "metadata_all.parquet"
23
+ INTER = ROOT / "_intermediate"
24
+ MATCHES = INTER / "ucsd_matches.parquet"
25
+ UNIFIED = INTER / "ucsd_unified.parquet"
26
+ META_TMP = META.with_suffix(".tmp.parquet")
27
+
28
+
29
+ def main():
30
+ con = duckdb.connect()
31
+ con.execute("PRAGMA threads=32")
32
+ con.execute("SET memory_limit='32GB'")
33
+
34
+ n_matches = con.execute(f"SELECT COUNT(*) FROM '{MATCHES}'").fetchone()[0]
35
+ print(f"matches to fold in: {n_matches:,}")
36
+
37
+ # Build the UCSD->google_* enrichment table for the matched fsq_place_ids.
38
+ # We pick the first row per ucsd_fsq_os_id from the unified table (rare
39
+ # duplicates between bench/all20 -- prefer 'bench' which is already
40
+ # validated against the benchmark).
41
+ con.execute(f"""
42
+ CREATE TEMP TABLE ucsd_dedup AS
43
+ SELECT * FROM (
44
+ SELECT *,
45
+ ROW_NUMBER() OVER (PARTITION BY ucsd_fsq_os_id
46
+ ORDER BY CASE WHEN src='bench' THEN 0 ELSE 1 END) AS rn
47
+ FROM '{UNIFIED}'
48
+ ) WHERE rn = 1
49
+ """)
50
+
51
+ con.execute(f"""
52
+ CREATE TEMP TABLE enrich AS
53
+ SELECT
54
+ m.fsq_place_id,
55
+ u.gmap_id AS google_cid_new,
56
+ COALESCE(u.gmaps_name, u.gl_name) AS google_name_new,
57
+ u.gmaps_full_address AS google_full_address_new,
58
+ COALESCE(u.gmaps_address, u.gl_address) AS google_address_new,
59
+ u.gmaps_website AS google_website_new,
60
+ COALESCE(u.gmaps_rating, u.gl_avg_rating) AS google_rating_new,
61
+ COALESCE(u.gmaps_num_reviews, u.gl_num_reviews) AS google_num_reviews_new,
62
+ COALESCE(u.gmaps_categories, u.gl_category) AS google_categories_new,
63
+ u.place_id AS google_place_id_new,
64
+ COALESCE(u.gmaps_url, u.gl_url) AS google_gmaps_url_new,
65
+ ('ucsd_' || u.src) AS google_meta_source_new
66
+ FROM '{MATCHES}' m
67
+ JOIN ucsd_dedup u USING (ucsd_fsq_os_id)
68
+ """)
69
+ n_enrich = con.execute("SELECT COUNT(*) FROM enrich").fetchone()[0]
70
+ print(f" enrichment table size: {n_enrich:,}")
71
+
72
+ # Inspect coverage of the enrichment payload.
73
+ cov = con.execute("""
74
+ SELECT
75
+ SUM(CASE WHEN google_cid_new IS NOT NULL THEN 1 ELSE 0 END) AS cid,
76
+ SUM(CASE WHEN google_name_new IS NOT NULL THEN 1 ELSE 0 END) AS nm,
77
+ SUM(CASE WHEN google_full_address_new IS NOT NULL THEN 1 ELSE 0 END) AS addr,
78
+ SUM(CASE WHEN google_website_new IS NOT NULL THEN 1 ELSE 0 END) AS web,
79
+ SUM(CASE WHEN google_rating_new IS NOT NULL THEN 1 ELSE 0 END) AS rating,
80
+ SUM(CASE WHEN google_categories_new IS NOT NULL THEN 1 ELSE 0 END) AS cats
81
+ FROM enrich
82
+ """).fetchone()
83
+ print(f" field coverage: cid={cov[0]} name={cov[1]} addr={cov[2]} "
84
+ f"web={cov[3]} rating={cov[4]} cats={cov[5]}")
85
+
86
+ # COPY-write a new metadata_all.parquet that overlays google_* fields for
87
+ # POIs in the enrichment table, leaving everything else unchanged.
88
+ print("\nrewriting metadata_all.parquet ...")
89
+ con.execute(f"""
90
+ COPY (
91
+ SELECT
92
+ m.fsq_place_id,
93
+ m.benchmark_name, m.benchmark_locality,
94
+ m.benchmark_venue_category, m.benchmark_venue_schema,
95
+ m.fsq_name, m.fsq_latitude, m.fsq_longitude, m.fsq_address,
96
+ m.fsq_locality, m.fsq_region, m.fsq_country, m.fsq_postcode,
97
+ m.fsq_formatted_address, m.fsq_category_ids, m.fsq_category_labels,
98
+ m.fsq_website, m.fsq_tel, m.fsq_email, m.fsq_facebook_id,
99
+ m.fsq_instagram, m.fsq_twitter,
100
+ m.fsq_date_created, m.fsq_date_refreshed, m.fsq_date_closed,
101
+ m.fsq_meta_source, m.has_fsq_metadata,
102
+ COALESCE(m.google_cid, e.google_cid_new) AS google_cid,
103
+ COALESCE(m.google_name, e.google_name_new) AS google_name,
104
+ COALESCE(m.google_full_address, e.google_full_address_new) AS google_full_address,
105
+ COALESCE(m.google_address, e.google_address_new) AS google_address,
106
+ COALESCE(m.google_website, e.google_website_new) AS google_website,
107
+ COALESCE(m.google_rating, e.google_rating_new) AS google_rating,
108
+ COALESCE(m.google_num_reviews, e.google_num_reviews_new) AS google_num_reviews,
109
+ COALESCE(m.google_categories, e.google_categories_new) AS google_categories,
110
+ COALESCE(m.google_place_id, e.google_place_id_new) AS google_place_id,
111
+ COALESCE(m.google_gmaps_url, e.google_gmaps_url_new) AS google_gmaps_url,
112
+ CASE
113
+ WHEN m.has_google_metadata THEN m.google_meta_source
114
+ WHEN e.google_cid_new IS NOT NULL THEN e.google_meta_source_new
115
+ ELSE m.google_meta_source
116
+ END AS google_meta_source,
117
+ (m.has_google_metadata OR e.google_cid_new IS NOT NULL) AS has_google_metadata
118
+ FROM '{META}' m
119
+ LEFT JOIN enrich e USING (fsq_place_id)
120
+ ) TO '{META_TMP}' (FORMAT PARQUET, COMPRESSION 'zstd', ROW_GROUP_SIZE 200000)
121
+ """)
122
+ META.unlink(); META_TMP.rename(META)
123
+
124
+ n_total = con.execute(f"SELECT COUNT(*) FROM '{META}'").fetchone()[0]
125
+ n_with_g = con.execute(f"SELECT SUM(CASE WHEN has_google_metadata THEN 1 ELSE 0 END) FROM '{META}'").fetchone()[0]
126
+ print(f"\nmetadata_all.parquet rewritten: {n_total:,} rows, "
127
+ f"{n_with_g:,} with Google metadata ({n_with_g/n_total*100:.2f}%)")
128
+
129
+ by_src = con.execute(f"""
130
+ SELECT google_meta_source, COUNT(*) FROM '{META}'
131
+ WHERE google_cid IS NOT NULL GROUP BY 1 ORDER BY 2 DESC
132
+ """).fetchall()
133
+ print("\ngoogle_meta_source breakdown:")
134
+ for s, c in by_src:
135
+ print(f" {s or '(null)':30s} {c:>9,}")
136
+
137
+
138
+ if __name__ == "__main__":
139
+ main()
_scripts/14_merge_gcp_search_results.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 14: fold the GCP search-and-scrape results into Trip World.
3
+
4
+ Reads:
5
+ _intermediate/gcp_search_attrs/shard_*/search_attrs.jsonl
6
+ produced by gmaps_search_gcp/collect.sh
7
+ Each row contains:
8
+ fsq_place_id, status, search_query, match_dist_m, match_name_sim,
9
+ biz: {cid, name, full_address, address, website, rating,
10
+ num_reviews, categories, place_id, gmaps_url, lat, lon},
11
+ description_short, description_long,
12
+ hours_today, hours_week,
13
+ price_token, price_min, price_max,
14
+ attributes: [...],
15
+ inline_reviews: [...],
16
+ raw_size, fetched_at, error
17
+
18
+ Writes:
19
+ metadata/metadata_all.parquet (overwritten with google_* + new
20
+ google_attrs_* cols populated)
21
+ metadata/place_attributes.parquet (NEW: description/hours/price/attrs)
22
+ reviews/google_inline_reviews.parquet (NEW)
23
+
24
+ Idempotent — safe to re-run.
25
+ """
26
+ from __future__ import annotations
27
+ import json, time
28
+ from pathlib import Path
29
+
30
+ import duckdb
31
+ import pyarrow as pa
32
+ import pyarrow.parquet as pq
33
+
34
+ import os
35
+ ROOT = Path(os.environ.get("TRIP_WORLD_ROOT", Path(__file__).resolve().parent.parent))
36
+ META = ROOT / "metadata" / "metadata_all.parquet"
37
+ ATTRS_OUT = ROOT / "metadata" / "place_attributes.parquet"
38
+ REVIEWS_DIR = ROOT / "reviews"
39
+ REVIEWS_OUT = REVIEWS_DIR / "google_inline_reviews.parquet"
40
+ INTER = ROOT / "_intermediate"
41
+ GCP_DIR = INTER / "gcp_search_attrs"
42
+ META_TMP = META.with_suffix(".tmp.parquet")
43
+
44
+
45
+ def log(m): print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True)
46
+
47
+
48
+ def main():
49
+ REVIEWS_DIR.mkdir(parents=True, exist_ok=True)
50
+
51
+ # ------------------------------------------------------------------
52
+ # 1. Load all GCP shards into memory
53
+ # ------------------------------------------------------------------
54
+ log("loading GCP shards ...")
55
+ rows = []
56
+ files = sorted(GCP_DIR.glob("shard_*/search_attrs.jsonl"))
57
+ if not files:
58
+ # Fallback: also look for un-merged worker files
59
+ files = sorted(GCP_DIR.glob("shard_*/search_attrs*.jsonl"))
60
+ log(f" found {len(files)} shard files")
61
+ for fp in files:
62
+ with open(fp) as fh:
63
+ for line in fh:
64
+ try: rows.append(json.loads(line))
65
+ except Exception: continue
66
+ log(f" loaded {len(rows):,} records")
67
+
68
+ # Deduplicate by fsq_place_id, keeping the LATEST 'ok' if any, else last
69
+ by_id: dict[str, dict] = {}
70
+ for r in rows:
71
+ fid = r.get("fsq_place_id")
72
+ if not fid: continue
73
+ prev = by_id.get(fid)
74
+ if prev is None: by_id[fid] = r; continue
75
+ prev_ok = prev.get("status") == "ok"
76
+ cur_ok = r.get("status") == "ok"
77
+ if cur_ok and not prev_ok:
78
+ by_id[fid] = r
79
+ rows = list(by_id.values())
80
+ log(f" after dedup by fsq_place_id: {len(rows):,}")
81
+
82
+ # ------------------------------------------------------------------
83
+ # 2. Build the enrichment table (google_* + place_attributes)
84
+ # ------------------------------------------------------------------
85
+ log("building enrichment tables ...")
86
+ google_rows = [] # for metadata overlay
87
+ attrs_rows = [] # for place_attributes.parquet
88
+ review_rows = [] # for inline_reviews.parquet
89
+ for r in rows:
90
+ fid = r["fsq_place_id"]
91
+ if r.get("status") != "ok": continue
92
+ biz = r.get("biz") or {}
93
+ cid = biz.get("cid")
94
+ if not cid: continue
95
+ google_rows.append({
96
+ "fsq_place_id": fid,
97
+ "google_cid": cid,
98
+ "google_name": biz.get("name"),
99
+ "google_full_address": biz.get("full_address"),
100
+ "google_address": biz.get("address"),
101
+ "google_website": biz.get("website"),
102
+ "google_rating": (float(biz["rating"])
103
+ if biz.get("rating") is not None else None),
104
+ "google_num_reviews": (int(biz["num_reviews"])
105
+ if biz.get("num_reviews") is not None else None),
106
+ "google_categories": biz.get("categories"),
107
+ "google_place_id": biz.get("place_id"),
108
+ "google_gmaps_url": biz.get("gmaps_url"),
109
+ "google_meta_source": "gcp_search_2026",
110
+ })
111
+ attrs_rows.append({
112
+ "fsq_place_id": fid,
113
+ "google_cid": cid,
114
+ "search_query": r.get("search_query"),
115
+ "match_dist_m": r.get("match_dist_m"),
116
+ "match_name_sim": r.get("match_name_sim"),
117
+ "description_short": r.get("description_short"),
118
+ "description_long": r.get("description_long"),
119
+ "hours_today": json.dumps(r.get("hours_today")) if r.get("hours_today") else None,
120
+ "hours_week": json.dumps(r.get("hours_week")) if r.get("hours_week") else None,
121
+ "price_token": r.get("price_token"),
122
+ "price_min": r.get("price_min"),
123
+ "price_max": r.get("price_max"),
124
+ "attributes": json.dumps(r.get("attributes")) if r.get("attributes") else None,
125
+ "n_inline_reviews": len(r.get("inline_reviews") or []),
126
+ "fetched_at": r.get("fetched_at"),
127
+ })
128
+ for rev in (r.get("inline_reviews") or []):
129
+ review_rows.append({
130
+ "fsq_place_id": fid,
131
+ "google_cid": cid,
132
+ "review_id": rev.get("review_id"),
133
+ "rating": rev.get("rating"),
134
+ "text": rev.get("text"),
135
+ "author": rev.get("author"),
136
+ "timestamp_us": rev.get("timestamp_us"),
137
+ "relative_time": rev.get("relative_time"),
138
+ "source": rev.get("source"),
139
+ })
140
+ log(f" google enrichment rows: {len(google_rows):,}")
141
+ log(f" place_attributes rows: {len(attrs_rows):,}")
142
+ log(f" inline_reviews rows: {len(review_rows):,}")
143
+
144
+ # ------------------------------------------------------------------
145
+ # 3. Write place_attributes + inline_reviews parquet (replace, idempotent)
146
+ # ------------------------------------------------------------------
147
+ log("writing place_attributes.parquet ...")
148
+ pq.write_table(
149
+ pa.Table.from_pylist(attrs_rows, schema=pa.schema([
150
+ ("fsq_place_id", pa.string()),
151
+ ("google_cid", pa.string()),
152
+ ("search_query", pa.string()),
153
+ ("match_dist_m", pa.float64()),
154
+ ("match_name_sim", pa.float64()),
155
+ ("description_short", pa.string()),
156
+ ("description_long", pa.string()),
157
+ ("hours_today", pa.string()),
158
+ ("hours_week", pa.string()),
159
+ ("price_token", pa.string()),
160
+ ("price_min", pa.string()),
161
+ ("price_max", pa.string()),
162
+ ("attributes", pa.string()),
163
+ ("n_inline_reviews", pa.int64()),
164
+ ("fetched_at", pa.string()),
165
+ ])),
166
+ ATTRS_OUT, compression="zstd")
167
+ log(f" wrote {ATTRS_OUT} ({ATTRS_OUT.stat().st_size/1e6:.1f} MB)")
168
+
169
+ log("writing google_inline_reviews.parquet ...")
170
+ pq.write_table(
171
+ pa.Table.from_pylist(review_rows, schema=pa.schema([
172
+ ("fsq_place_id", pa.string()),
173
+ ("google_cid", pa.string()),
174
+ ("review_id", pa.string()),
175
+ ("rating", pa.int64()),
176
+ ("text", pa.string()),
177
+ ("author", pa.string()),
178
+ ("timestamp_us", pa.int64()),
179
+ ("relative_time", pa.string()),
180
+ ("source", pa.string()),
181
+ ])),
182
+ REVIEWS_OUT, compression="zstd")
183
+ log(f" wrote {REVIEWS_OUT} ({REVIEWS_OUT.stat().st_size/1e6:.1f} MB)")
184
+
185
+ # ------------------------------------------------------------------
186
+ # 4. Overlay google_* fields into metadata_all.parquet
187
+ # ------------------------------------------------------------------
188
+ log("overlaying google_* into metadata_all.parquet ...")
189
+ enrich_path = INTER / "_gcp_google_overlay.parquet"
190
+ pq.write_table(
191
+ pa.Table.from_pylist(google_rows, schema=pa.schema([
192
+ ("fsq_place_id", pa.string()),
193
+ ("google_cid", pa.string()),
194
+ ("google_name", pa.string()),
195
+ ("google_full_address", pa.string()),
196
+ ("google_address", pa.string()),
197
+ ("google_website", pa.string()),
198
+ ("google_rating", pa.float64()),
199
+ ("google_num_reviews", pa.int64()),
200
+ ("google_categories", pa.list_(pa.string())),
201
+ ("google_place_id", pa.string()),
202
+ ("google_gmaps_url", pa.string()),
203
+ ("google_meta_source", pa.string()),
204
+ ])),
205
+ enrich_path, compression="zstd")
206
+
207
+ con = duckdb.connect()
208
+ con.execute("PRAGMA threads=32")
209
+ con.execute("SET memory_limit='32GB'")
210
+ con.execute(f"""
211
+ COPY (
212
+ SELECT
213
+ m.fsq_place_id,
214
+ m.benchmark_name, m.benchmark_locality,
215
+ m.benchmark_venue_category, m.benchmark_venue_schema,
216
+ m.fsq_name, m.fsq_latitude, m.fsq_longitude, m.fsq_address,
217
+ m.fsq_locality, m.fsq_region, m.fsq_country, m.fsq_postcode,
218
+ m.fsq_formatted_address, m.fsq_category_ids, m.fsq_category_labels,
219
+ m.fsq_website, m.fsq_tel, m.fsq_email, m.fsq_facebook_id,
220
+ m.fsq_instagram, m.fsq_twitter,
221
+ m.fsq_date_created, m.fsq_date_refreshed, m.fsq_date_closed,
222
+ m.fsq_meta_source, m.has_fsq_metadata,
223
+ COALESCE(m.google_cid, e.google_cid) AS google_cid,
224
+ COALESCE(m.google_name, e.google_name) AS google_name,
225
+ COALESCE(m.google_full_address, e.google_full_address) AS google_full_address,
226
+ COALESCE(m.google_address, e.google_address) AS google_address,
227
+ COALESCE(m.google_website, e.google_website) AS google_website,
228
+ COALESCE(m.google_rating, e.google_rating) AS google_rating,
229
+ COALESCE(m.google_num_reviews, e.google_num_reviews) AS google_num_reviews,
230
+ COALESCE(m.google_categories, e.google_categories) AS google_categories,
231
+ COALESCE(m.google_place_id, e.google_place_id) AS google_place_id,
232
+ COALESCE(m.google_gmaps_url, e.google_gmaps_url) AS google_gmaps_url,
233
+ CASE
234
+ WHEN m.has_google_metadata THEN m.google_meta_source
235
+ WHEN e.google_cid IS NOT NULL THEN e.google_meta_source
236
+ ELSE m.google_meta_source
237
+ END AS google_meta_source,
238
+ (m.has_google_metadata OR e.google_cid IS NOT NULL) AS has_google_metadata
239
+ FROM '{META}' m
240
+ LEFT JOIN '{enrich_path}' e USING (fsq_place_id)
241
+ ) TO '{META_TMP}' (FORMAT PARQUET, COMPRESSION 'zstd', ROW_GROUP_SIZE 200000)
242
+ """)
243
+ META.unlink(); META_TMP.rename(META)
244
+ log(f" rewrote {META}")
245
+
246
+ # ------------------------------------------------------------------
247
+ # 5. Final coverage stats
248
+ # ------------------------------------------------------------------
249
+ log("computing final coverage ...")
250
+ n_total = con.execute(f"SELECT COUNT(*) FROM '{META}'").fetchone()[0]
251
+ n_with_g = con.execute(f"SELECT SUM(CASE WHEN has_google_metadata THEN 1 ELSE 0 END) FROM '{META}'").fetchone()[0]
252
+ n_attrs = con.execute(f"SELECT COUNT(*) FROM '{ATTRS_OUT}'").fetchone()[0]
253
+ n_revs = con.execute(f"SELECT COUNT(*) FROM '{REVIEWS_OUT}'").fetchone()[0]
254
+ n_revs_text = con.execute(f"""
255
+ SELECT COUNT(*) FROM '{REVIEWS_OUT}'
256
+ WHERE text IS NOT NULL AND length(text) >= 30
257
+ """).fetchone()[0]
258
+ print()
259
+ print("=" * 60)
260
+ print("FINAL COVERAGE")
261
+ print("=" * 60)
262
+ print(f" metadata_all rows: {n_total:,}")
263
+ print(f" POIs with Google metadata: {n_with_g:,} "
264
+ f"({n_with_g/n_total*100:.2f}%)")
265
+ print(f" POIs with place_attributes: {n_attrs:,} "
266
+ f"({n_attrs/n_total*100:.2f}%)")
267
+ print(f" Inline reviews collected: {n_revs:,}")
268
+ print(f" Reviews with >=30 char text: {n_revs_text:,}")
269
+ print()
270
+
271
+ by_src = con.execute(f"""
272
+ SELECT google_meta_source, COUNT(*) FROM '{META}'
273
+ WHERE google_cid IS NOT NULL GROUP BY 1 ORDER BY 2 DESC
274
+ """).fetchall()
275
+ print("google_meta_source breakdown:")
276
+ for s, c in by_src:
277
+ print(f" {s or '(null)':30s} {c:>9,}")
278
+
279
+
280
+ if __name__ == "__main__":
281
+ main()
_scripts/15_merge_stage2_reviews.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 15: fold the listugcposts (Stage 2) reviews into Trip World.
3
+
4
+ Reads:
5
+ _intermediate/gcp_reviews/reviews_NN.jsonl
6
+ produced by gmaps_reviews_gcp/collect.sh
7
+ Each row contains:
8
+ fsq_place_id, fid, fsq_name, fetched_at, status, num_pages,
9
+ num_reviews,
10
+ reviews: [
11
+ {review_id, author, author_id, timestamp_us, relative_time,
12
+ rating, text, lang, owner_reply}
13
+ ]
14
+
15
+ Writes:
16
+ reviews/reviews_listugcposts.parquet
17
+ flat per-review table for the listugcposts crawl
18
+ reviews/reviews_all.parquet
19
+ union with the existing google_inline_reviews.parquet, deduped on
20
+ review_id, prioritising listugcposts over inline (former is fuller).
21
+
22
+ Idempotent — safe to re-run.
23
+ """
24
+ from __future__ import annotations
25
+ import json, time
26
+ from pathlib import Path
27
+
28
+ import duckdb
29
+ import pyarrow as pa
30
+ import pyarrow.parquet as pq
31
+
32
+ import os
33
+ ROOT = Path(os.environ.get("TRIP_WORLD_ROOT", Path(__file__).resolve().parent.parent))
34
+ INTER = ROOT / "_intermediate"
35
+ GCP_DIR = INTER / "gcp_reviews"
36
+ REVIEWS_DIR = ROOT / "reviews"
37
+
38
+ INLINE = REVIEWS_DIR / "google_inline_reviews.parquet" # from Stage 14
39
+ STAGE2 = REVIEWS_DIR / "reviews_listugcposts.parquet" # output (this script)
40
+ ALL_OUT = REVIEWS_DIR / "reviews_all.parquet" # union output
41
+
42
+
43
+ def log(m): print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True)
44
+
45
+
46
+ def main() -> None:
47
+ REVIEWS_DIR.mkdir(parents=True, exist_ok=True)
48
+
49
+ # ------------------------------------------------------------------
50
+ # 1. Load all listugcposts JSONL files
51
+ # ------------------------------------------------------------------
52
+ log("loading listugcposts JSONL ...")
53
+ files = sorted(GCP_DIR.glob("reviews_*.jsonl"))
54
+ log(f" found {len(files)} files")
55
+ if not files:
56
+ log(" no input — Stage 2 hasn't been collected yet?")
57
+ return
58
+
59
+ # Per-POI dedup: keep the record with most reviews per fsq_place_id.
60
+ poi_rows: dict[str, dict] = {}
61
+ n_lines = 0
62
+ for fp in files:
63
+ with open(fp) as fh:
64
+ for line in fh:
65
+ try:
66
+ r = json.loads(line)
67
+ except Exception:
68
+ continue
69
+ n_lines += 1
70
+ fid = r.get("fsq_place_id")
71
+ if not fid: continue
72
+ prev = poi_rows.get(fid)
73
+ if prev is None or len(r.get("reviews") or []) > len(prev.get("reviews") or []):
74
+ poi_rows[fid] = r
75
+ log(f" read {n_lines:,} rows -> {len(poi_rows):,} unique POIs")
76
+
77
+ # ------------------------------------------------------------------
78
+ # 2. Flatten -> per-review table
79
+ # ------------------------------------------------------------------
80
+ log("flattening to per-review rows ...")
81
+ flat = []
82
+ n_pois_with_reviews = 0
83
+ for fid, r in poi_rows.items():
84
+ revs = r.get("reviews") or []
85
+ if not revs: continue
86
+ n_pois_with_reviews += 1
87
+ cid = r.get("fid")
88
+ for rev in revs:
89
+ flat.append({
90
+ "fsq_place_id": fid,
91
+ "google_cid": cid,
92
+ "review_id": rev.get("review_id"),
93
+ "rating": rev.get("rating"),
94
+ "text": rev.get("text"),
95
+ "author": rev.get("author"),
96
+ "author_id": rev.get("author_id"),
97
+ "timestamp_us": rev.get("timestamp_us"),
98
+ "relative_time": rev.get("relative_time"),
99
+ "lang": rev.get("lang"),
100
+ "owner_reply": rev.get("owner_reply"),
101
+ "source": "listugcposts",
102
+ })
103
+ log(f" POIs with >=1 review: {n_pois_with_reviews:,}")
104
+ log(f" total reviews: {len(flat):,}")
105
+
106
+ # ------------------------------------------------------------------
107
+ # 3. Write reviews_listugcposts.parquet
108
+ # ------------------------------------------------------------------
109
+ log("writing reviews_listugcposts.parquet ...")
110
+ schema = pa.schema([
111
+ ("fsq_place_id", pa.string()),
112
+ ("google_cid", pa.string()),
113
+ ("review_id", pa.string()),
114
+ ("rating", pa.int64()),
115
+ ("text", pa.string()),
116
+ ("author", pa.string()),
117
+ ("author_id", pa.string()),
118
+ ("timestamp_us", pa.int64()),
119
+ ("relative_time", pa.string()),
120
+ ("lang", pa.string()),
121
+ ("owner_reply", pa.string()),
122
+ ("source", pa.string()),
123
+ ])
124
+ pq.write_table(pa.Table.from_pylist(flat, schema=schema),
125
+ STAGE2, compression="zstd")
126
+ log(f" wrote {STAGE2} ({STAGE2.stat().st_size/1e6:.1f} MB)")
127
+
128
+ # ------------------------------------------------------------------
129
+ # 4. Build reviews_all.parquet = union(listugcposts, inline) deduped
130
+ # ------------------------------------------------------------------
131
+ if not INLINE.exists():
132
+ log(f" inline reviews parquet missing ({INLINE}) — writing reviews_all = stage2 only")
133
+ STAGE2.replace(ALL_OUT) if False else None # leave files separate
134
+ import shutil; shutil.copy(STAGE2, ALL_OUT)
135
+ else:
136
+ log("computing union with inline reviews ...")
137
+ con = duckdb.connect()
138
+ con.execute("PRAGMA threads=16")
139
+ con.execute("SET memory_limit='16GB'")
140
+ # Inline reviews don't have author_id / lang / owner_reply; project them as NULL.
141
+ con.execute(f"""
142
+ COPY (
143
+ WITH unioned AS (
144
+ SELECT
145
+ fsq_place_id, google_cid, review_id, rating, text,
146
+ author, author_id, timestamp_us, relative_time, lang, owner_reply,
147
+ source, 1 AS prio
148
+ FROM '{STAGE2}'
149
+ UNION ALL
150
+ SELECT
151
+ fsq_place_id, google_cid, review_id, rating, text,
152
+ author, NULL AS author_id, timestamp_us, relative_time,
153
+ NULL AS lang, NULL AS owner_reply,
154
+ 'inline_preload' AS source, 2 AS prio
155
+ FROM '{INLINE}'
156
+ ),
157
+ ranked AS (
158
+ SELECT *, ROW_NUMBER() OVER (
159
+ PARTITION BY COALESCE(review_id, fsq_place_id || '|' || COALESCE(author,'') || '|' || COALESCE(text,''))
160
+ ORDER BY prio
161
+ ) AS rn
162
+ FROM unioned
163
+ )
164
+ SELECT
165
+ fsq_place_id, google_cid, review_id, rating, text,
166
+ author, author_id, timestamp_us, relative_time, lang, owner_reply, source
167
+ FROM ranked WHERE rn = 1
168
+ ) TO '{ALL_OUT}' (FORMAT PARQUET, COMPRESSION 'zstd', ROW_GROUP_SIZE 200000)
169
+ """)
170
+ log(f" wrote {ALL_OUT} ({ALL_OUT.stat().st_size/1e6:.1f} MB)")
171
+
172
+ # ------------------------------------------------------------------
173
+ # 5. Final stats
174
+ # ------------------------------------------------------------------
175
+ log("computing final stats ...")
176
+ con = duckdb.connect()
177
+ con.execute("PRAGMA threads=16")
178
+ n_revs = con.execute(f"SELECT COUNT(*) FROM '{ALL_OUT}'").fetchone()[0]
179
+ n_text = con.execute(f"SELECT COUNT(*) FROM '{ALL_OUT}' WHERE text IS NOT NULL AND length(text) >= 30").fetchone()[0]
180
+ n_pois = con.execute(f"SELECT COUNT(DISTINCT fsq_place_id) FROM '{ALL_OUT}'").fetchone()[0]
181
+ n_pois_text = con.execute(f"SELECT COUNT(DISTINCT fsq_place_id) FROM '{ALL_OUT}' WHERE text IS NOT NULL AND length(text) >= 30").fetchone()[0]
182
+ by_src = con.execute(f"SELECT source, COUNT(*) FROM '{ALL_OUT}' GROUP BY 1 ORDER BY 2 DESC").fetchall()
183
+
184
+ print()
185
+ print("=" * 60)
186
+ print("FINAL REVIEW COVERAGE (Trip World, new POIs only)")
187
+ print("=" * 60)
188
+ print(f" unique POIs with reviews: {n_pois:,}")
189
+ print(f" unique POIs with text reviews: {n_pois_text:,}")
190
+ print(f" total reviews: {n_revs:,}")
191
+ print(f" reviews with >=30 char text: {n_text:,}")
192
+ print()
193
+ print("by source:")
194
+ for s, c in by_src:
195
+ print(f" {s:30s} {c:>10,}")
196
+
197
+
198
+ if __name__ == "__main__":
199
+ main()
_scripts/16_unify_reviews.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 16: build the unified reviews_all.parquet for Trip World.
3
+
4
+ Combines:
5
+ - Precursor reviews (~96M rows) loaded from
6
+ $PRECURSOR_BUILD_ROOT/reviews/reviews_all.parquet
7
+ The $PRECURSOR_BUILD_ROOT env var should point at a previous output of
8
+ this same pipeline whose review corpus we want to extend; omit this
9
+ stage entirely if you do not have such a precursor build.
10
+ - The newly-collected reviews from this release's stage-14/15 outputs:
11
+ $TRIP_WORLD_ROOT/reviews/reviews_listugcposts.parquet
12
+ $TRIP_WORLD_ROOT/reviews/google_inline_reviews.parquet
13
+ (~15M rows total).
14
+
15
+ Both inputs are filtered to POIs that survived into Trip World, then
16
+ deduplicated on review_id (with a fallback hash on
17
+ fsq_place_id|author|text for rows missing review_id).
18
+
19
+ Schema is the union of all three, with NULLs for missing fields:
20
+ fsq_place_id, google_cid, review_id, author, author_id, rating, text,
21
+ text_translated, lang, relative_time, timestamp_us, review_time,
22
+ owner_reply, source
23
+
24
+ Output:
25
+ $TRIP_WORLD_ROOT/reviews/reviews_all.parquet (overwritten)
26
+ """
27
+ from __future__ import annotations
28
+ import time
29
+ from pathlib import Path
30
+ import duckdb
31
+ import os
32
+
33
+ ROOT_V1 = Path(os.environ["PRECURSOR_BUILD_ROOT"])
34
+ ROOT_CLEAN = Path(os.environ.get("TRIP_WORLD_ROOT", Path(__file__).resolve().parent.parent))
35
+ META_CLEAN = ROOT_CLEAN / "metadata" / "metadata_all.parquet"
36
+
37
+ V1_REVIEWS = ROOT_V1 / "reviews" / "reviews_all.parquet"
38
+ NEW_LISTUGC = ROOT_CLEAN / "reviews" / "reviews_listugcposts.parquet"
39
+ NEW_INLINE = ROOT_CLEAN / "reviews" / "google_inline_reviews.parquet"
40
+
41
+ OUT = ROOT_CLEAN / "reviews" / "reviews_all.parquet"
42
+ OUT_TMP = OUT.with_suffix(".tmp.parquet")
43
+
44
+
45
+ def log(m): print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True)
46
+
47
+
48
+ def main() -> None:
49
+ con = duckdb.connect()
50
+ con.execute("PRAGMA threads=32")
51
+ con.execute("SET memory_limit='48GB'")
52
+
53
+ # ------------------------------------------------------------------
54
+ # 1. Sanity counts before union
55
+ # ------------------------------------------------------------------
56
+ log("counting inputs ...")
57
+ n_prev = con.execute(f"SELECT COUNT(*) FROM '{V1_REVIEWS}'").fetchone()[0]
58
+ n_lu = con.execute(f"SELECT COUNT(*) FROM '{NEW_LISTUGC}'").fetchone()[0]
59
+ n_in = con.execute(f"SELECT COUNT(*) FROM '{NEW_INLINE}'").fetchone()[0]
60
+ log(f" precursor reviews: {n_prev:>12,}")
61
+ log(f" new listugcposts: {n_lu:>12,}")
62
+ log(f" new inline_preload: {n_in:>12,}")
63
+ log(f" raw total before dedup: {n_prev + n_lu + n_in:>12,}")
64
+
65
+ # ------------------------------------------------------------------
66
+ # 2. Build unified, deduped reviews_all.
67
+ # Priority order, highest first:
68
+ # 1) the listugcposts crawl (most reviews per place)
69
+ # 2) precursor-build refetch rows (highest fidelity refetch)
70
+ # 3) precursor-build other source tags
71
+ # 4) inline-preview reviews from the search-page enrichment
72
+ # ------------------------------------------------------------------
73
+ log("building unified table (this can take a few minutes) ...")
74
+ con.execute(f"""
75
+ COPY (
76
+ WITH unioned AS (
77
+ -- precursor reviews (96M)
78
+ SELECT
79
+ fsq_place_id,
80
+ CAST(NULL AS VARCHAR) AS google_cid,
81
+ review_id, author, author_id, rating, text, text_translated,
82
+ lang, relative_time, timestamp_us, review_time,
83
+ CAST(NULL AS VARCHAR) AS owner_reply,
84
+ 'v1_' || source AS source,
85
+ CASE
86
+ WHEN source = 'refetch' THEN 2
87
+ WHEN source = 'migrate' THEN 3
88
+ WHEN source = 'stage1d' THEN 4
89
+ WHEN source = 'playwright' THEN 5
90
+ WHEN source = 'ucsd_all20' THEN 6
91
+ WHEN source = 'ucsd_bench' THEN 7
92
+ ELSE 8
93
+ END AS prio
94
+ FROM '{V1_REVIEWS}'
95
+ UNION ALL
96
+ -- new listugcposts (15M)
97
+ SELECT
98
+ fsq_place_id, google_cid,
99
+ review_id, author, author_id, rating, text,
100
+ CAST(NULL AS VARCHAR) AS text_translated,
101
+ lang, relative_time, timestamp_us,
102
+ CAST(NULL AS TIMESTAMP) AS review_time,
103
+ owner_reply,
104
+ source, -- already 'listugcposts'
105
+ 1 AS prio -- highest priority
106
+ FROM '{NEW_LISTUGC}'
107
+ UNION ALL
108
+ -- new inline preload (from search-and-scrape worker, ~227K rows)
109
+ SELECT
110
+ fsq_place_id, google_cid, review_id, author,
111
+ CAST(NULL AS VARCHAR) AS author_id,
112
+ rating, text,
113
+ CAST(NULL AS VARCHAR) AS text_translated,
114
+ CAST(NULL AS VARCHAR) AS lang,
115
+ relative_time, timestamp_us,
116
+ CAST(NULL AS TIMESTAMP) AS review_time,
117
+ CAST(NULL AS VARCHAR) AS owner_reply,
118
+ 'inline_preload' AS source,
119
+ 9 AS prio -- lowest (always overshadowed)
120
+ FROM '{NEW_INLINE}'
121
+ ),
122
+ ranked AS (
123
+ SELECT *, ROW_NUMBER() OVER (
124
+ PARTITION BY COALESCE(
125
+ review_id,
126
+ fsq_place_id || '|' || COALESCE(author,'') || '|' || COALESCE(text,'')
127
+ )
128
+ ORDER BY prio
129
+ ) AS rn
130
+ FROM unioned
131
+ )
132
+ SELECT
133
+ fsq_place_id, google_cid, review_id, author, author_id, rating,
134
+ text, text_translated, lang, relative_time, timestamp_us, review_time,
135
+ owner_reply, source
136
+ FROM ranked WHERE rn = 1
137
+ ) TO '{OUT_TMP}' (FORMAT PARQUET, COMPRESSION 'zstd', ROW_GROUP_SIZE 200000)
138
+ """)
139
+ OUT.unlink(missing_ok=True)
140
+ OUT_TMP.rename(OUT)
141
+ log(f" wrote {OUT} ({OUT.stat().st_size/1e9:.2f} GB)")
142
+
143
+ # ------------------------------------------------------------------
144
+ # 3. Final stats
145
+ # ------------------------------------------------------------------
146
+ log("computing final stats ...")
147
+ n_revs = con.execute(f"SELECT COUNT(*) FROM '{OUT}'").fetchone()[0]
148
+ n_text = con.execute(f"SELECT COUNT(*) FROM '{OUT}' WHERE text IS NOT NULL AND length(text) >= 30").fetchone()[0]
149
+ n_pois = con.execute(f"SELECT COUNT(DISTINCT fsq_place_id) FROM '{OUT}'").fetchone()[0]
150
+ n_pois_text = con.execute(f"SELECT COUNT(DISTINCT fsq_place_id) FROM '{OUT}' WHERE text IS NOT NULL AND length(text) >= 30").fetchone()[0]
151
+ by_src = con.execute(f"SELECT source, COUNT(*) FROM '{OUT}' GROUP BY 1 ORDER BY 2 DESC").fetchall()
152
+
153
+ n_total_pois = con.execute(f"SELECT COUNT(*) FROM '{META_CLEAN}'").fetchone()[0]
154
+ n_pois_in_clean = con.execute(f"""
155
+ SELECT COUNT(DISTINCT r.fsq_place_id)
156
+ FROM '{OUT}' r
157
+ WHERE r.fsq_place_id IN (SELECT fsq_place_id FROM '{META_CLEAN}')
158
+ """).fetchone()[0]
159
+
160
+ print()
161
+ print("=" * 68)
162
+ print("UNIFIED REVIEWS COVERAGE — Trip World")
163
+ print("=" * 68)
164
+ print(f" total reviews in reviews_all: {n_revs:>12,}")
165
+ print(f" reviews with >=30-char text: {n_text:>12,}")
166
+ print(f" unique POIs with reviews: {n_pois:>12,}")
167
+ print(f" unique POIs with text reviews: {n_pois_text:>12,}")
168
+ print(f" POIs in Trip World (total): {n_total_pois:>12,}")
169
+ print(f" POIs covered (intersected w/ clean): {n_pois_in_clean:>12,} "
170
+ f"({n_pois_in_clean/n_total_pois*100:.2f}%)")
171
+ print()
172
+ print("by source:")
173
+ for s, c in by_src:
174
+ print(f" {s:30s} {c:>13,}")
175
+
176
+
177
+ if __name__ == "__main__":
178
+ main()
_scripts/lib_wikidata.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tiny Wikidata helper used by the Trip World build pipeline.
3
+
4
+ Two entry points:
5
+ - sparql(query) -> list[dict] (POSTs to the public SPARQL endpoint)
6
+ - get_entity(qid) -> dict (REST lookup; returns labels + claims)
7
+ - p131_chain(qid, depth=8) -> list[str] (transitive parents up the P131 ladder)
8
+
9
+ Network access is required. Polite throttling: ~3 requests/sec.
10
+ """
11
+ from __future__ import annotations
12
+ import json, time, urllib.parse, urllib.request, gzip, ssl
13
+ from typing import Iterable
14
+
15
+ UA = "RQ3-clean-pipeline/1.0 (research; contact: rq3-bench@example.org)"
16
+ _LAST_CALL = [0.0]
17
+ _MIN_GAP = 0.30 # seconds between requests
18
+
19
+ _ssl = ssl.create_default_context()
20
+
21
+
22
+ def _throttle():
23
+ gap = time.time() - _LAST_CALL[0]
24
+ if gap < _MIN_GAP:
25
+ time.sleep(_MIN_GAP - gap)
26
+ _LAST_CALL[0] = time.time()
27
+
28
+
29
+ def _http_get(url: str, accept: str = "application/json") -> bytes:
30
+ _throttle()
31
+ req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": accept,
32
+ "Accept-Encoding": "gzip"})
33
+ with urllib.request.urlopen(req, timeout=60, context=_ssl) as r:
34
+ body = r.read()
35
+ if r.headers.get("Content-Encoding") == "gzip":
36
+ body = gzip.decompress(body)
37
+ return body
38
+
39
+
40
+ def _http_post(url: str, body: str, ct: str = "application/sparql-query",
41
+ accept: str = "application/sparql-results+json") -> bytes:
42
+ _throttle()
43
+ req = urllib.request.Request(url, data=body.encode("utf-8"),
44
+ headers={"User-Agent": UA,
45
+ "Content-Type": ct,
46
+ "Accept": accept,
47
+ "Accept-Encoding": "gzip"},
48
+ method="POST")
49
+ with urllib.request.urlopen(req, timeout=120, context=_ssl) as r:
50
+ body = r.read()
51
+ if r.headers.get("Content-Encoding") == "gzip":
52
+ body = gzip.decompress(body)
53
+ return body
54
+
55
+
56
+ def sparql(query: str, retries: int = 3) -> list[dict]:
57
+ """Run a SPARQL query against query.wikidata.org and return the bindings."""
58
+ url = "https://query.wikidata.org/sparql"
59
+ last = None
60
+ for k in range(retries):
61
+ try:
62
+ raw = _http_post(url, query)
63
+ return json.loads(raw)["results"]["bindings"]
64
+ except Exception as e:
65
+ last = e
66
+ time.sleep(2 + 4 * k)
67
+ raise last
68
+
69
+
70
+ def get_entity(qid: str) -> dict:
71
+ """Fetch raw Wikidata JSON for a single QID via Special:EntityData."""
72
+ qid = qid.replace("wd:", "")
73
+ url = f"https://www.wikidata.org/wiki/Special:EntityData/{qid}.json"
74
+ for k in range(3):
75
+ try:
76
+ raw = _http_get(url)
77
+ data = json.loads(raw)
78
+ return list(data["entities"].values())[0]
79
+ except Exception:
80
+ time.sleep(2 + 3 * k)
81
+ raise RuntimeError(f"failed to fetch {qid}")
82
+
83
+
84
+ def p131_chain(qid: str, max_depth: int = 8) -> list[str]:
85
+ """Walk the 'located in administrative entity' (P131) chain upward.
86
+
87
+ Returns ordered ancestor QIDs starting from the immediate parent.
88
+ Stops at the first cycle / missing P131 / depth limit.
89
+ """
90
+ seen = {qid.replace("wd:", "")}
91
+ chain: list[str] = []
92
+ cur = qid.replace("wd:", "")
93
+ for _ in range(max_depth):
94
+ try:
95
+ ent = get_entity(cur)
96
+ except Exception:
97
+ break
98
+ claims = ent.get("claims", {}).get("P131", [])
99
+ if not claims:
100
+ break
101
+ # Take the first non-deprecated parent
102
+ parent = None
103
+ for c in claims:
104
+ if c.get("rank") == "deprecated":
105
+ continue
106
+ try:
107
+ parent = c["mainsnak"]["datavalue"]["value"]["id"]
108
+ break
109
+ except (KeyError, TypeError):
110
+ continue
111
+ if not parent or parent in seen:
112
+ break
113
+ seen.add(parent)
114
+ chain.append(parent)
115
+ cur = parent
116
+ return chain
117
+
118
+
119
+ def labels_batch(qids: Iterable[str]) -> dict[str, str]:
120
+ """Fetch English labels (with Japanese / Turkish / Arabic fallbacks) for a batch of QIDs."""
121
+ qids = [q.replace("wd:", "") for q in qids]
122
+ out: dict[str, str] = {}
123
+ BATCH = 50
124
+ for i in range(0, len(qids), BATCH):
125
+ batch = qids[i:i + BATCH]
126
+ values = " ".join(f"wd:{q}" for q in batch)
127
+ q = f"""
128
+ SELECT ?q ?qLabel WHERE {{
129
+ VALUES ?q {{ {values} }}
130
+ SERVICE wikibase:label {{
131
+ bd:serviceParam wikibase:language "en,ja,tr,ar,es,zh,fr,de" .
132
+ }}
133
+ }}
134
+ """
135
+ try:
136
+ for r in sparql(q):
137
+ qid = r["q"]["value"].rsplit("/", 1)[-1]
138
+ out[qid] = r.get("qLabel", {}).get("value", "")
139
+ except Exception as e:
140
+ print(f" labels_batch failed for batch {i}: {e}")
141
+ return out
142
+
143
+
144
+ if __name__ == "__main__":
145
+ import sys
146
+ if len(sys.argv) > 1:
147
+ qid = sys.argv[1]
148
+ print(f"label: {labels_batch([qid]).get(qid.replace('wd:', ''))}")
149
+ print(f"P131 chain: {p131_chain(qid)}")
150
+ else:
151
+ # Quick smoke test
152
+ print("Tokyo P131:", p131_chain("Q1490"))
153
+ print("Yokohama-area P131:", p131_chain("Q49295377"))
154
+ print("Suita P131:", p131_chain("Q49368443"))
155
+ print("Şişli P131:", p131_chain("Q49371964"))
_scripts/viz_clean_raw.py ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Visualizations for the raw Trip World dataset.
2
+
3
+ Reads the parquet files directly (no derived dataset needed) and writes PDFs
4
+ into $TRIP_WORLD_ROOT/viz/.
5
+
6
+ Figures
7
+ -------
8
+ 1. city_poi_entropy_hist.pdf — Shannon entropy of per-POI visit counts within each region (home vs OOT).
9
+ 2. city_user_entropy_hist.pdf — entropy of check-ins distributed across users per region.
10
+ 3. checkins_per_city_top30.pdf — top-30 regions by # check-ins, home/OOT stacked, with city names.
11
+ 4. trajectory_length_dist.pdf — per-user check-in count histogram + CDF, home vs OOT.
12
+ 5. top_travel_pairs.pdf — top-30 (home → OOT) pairs by # τ records.
13
+ 6. entropy_vs_size_scatter.pdf — entropy vs # check-ins per region.
14
+ 7. world_poi_density.pdf — global heatmap of POI density (log color scale).
15
+ 8. world_city_centroids.pdf — per-city centroids, marker size ∝ # check-ins.
16
+ 9. world_travel_flows.pdf — top-100 home → OOT flows as great-circle arcs.
17
+ 10. country_distribution.pdf — # cities and # check-ins per country.
18
+
19
+ Run:
20
+ python _scripts/viz_clean_raw.py
21
+ """
22
+ import math
23
+ import pickle
24
+ from collections import Counter
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+ import pandas as pd
29
+ import matplotlib
30
+ matplotlib.use("Agg")
31
+ import matplotlib.pyplot as plt
32
+ import cartopy.crs as ccrs
33
+ import cartopy.feature as cfeature
34
+ from matplotlib.colors import LogNorm
35
+ import os
36
+
37
+ ROOT = Path(os.environ.get("TRIP_WORLD_ROOT", Path(__file__).resolve().parent.parent))
38
+ OUT_DIR = ROOT / "viz"
39
+ OUT_DIR.mkdir(parents=True, exist_ok=True)
40
+
41
+
42
+ def shannon(counts):
43
+ counts = np.asarray(counts, dtype=np.float64)
44
+ counts = counts[counts > 0]
45
+ if counts.size == 0:
46
+ return 0.0
47
+ p = counts / counts.sum()
48
+ return float(-(p * np.log2(p)).sum())
49
+
50
+
51
+ def per_group_entropy(df, group_col, count_col):
52
+ """Return (group, total, n_unique, H, H_norm) per group."""
53
+ rows = []
54
+ for g, sub in df.groupby(group_col):
55
+ counts = sub[count_col].values
56
+ H = shannon(counts)
57
+ n_unique = (counts > 0).sum()
58
+ total = int(counts.sum())
59
+ H_uniform = math.log2(n_unique) if n_unique > 1 else 0.0
60
+ H_norm = H / H_uniform if H_uniform > 0 else 0.0
61
+ rows.append((g, total, int(n_unique), H, H_norm))
62
+ return pd.DataFrame(rows, columns=[group_col, "total", "n_unique", "H", "H_norm"])
63
+
64
+
65
+ def add_world_features(ax):
66
+ ax.add_feature(cfeature.LAND.with_scale("110m"), facecolor="#f3f1ec", zorder=0)
67
+ ax.add_feature(cfeature.OCEAN.with_scale("110m"), facecolor="#dfeaf2", zorder=0)
68
+ ax.add_feature(cfeature.COASTLINE.with_scale("110m"), linewidth=0.4, color="#777777", zorder=1)
69
+ ax.add_feature(cfeature.BORDERS.with_scale("110m"), linewidth=0.3, color="#999999", zorder=1)
70
+ ax.set_global()
71
+
72
+
73
+ def main():
74
+ print("[load] travel_behaviors")
75
+ tb = pd.read_parquet(ROOT / "travel_behaviors.parquet")
76
+ print(f" rows={len(tb):,}, users={tb.user_id.nunique():,}, "
77
+ f"home regions={tb.r_h.nunique():,}, oot regions={tb.r_o.nunique():,}")
78
+
79
+ print("[load] pois")
80
+ pois = pd.read_parquet(ROOT / "pois.parquet")[["fsq_place_id", "locality", "n_checkins"]]
81
+ print(f" rows={len(pois):,}")
82
+
83
+ print("[load] metadata_all (for lat/lon)")
84
+ meta = pd.read_parquet(ROOT / "metadata/metadata_all.parquet",
85
+ columns=["fsq_place_id", "fsq_latitude", "fsq_longitude"])
86
+ pois = pois.merge(meta, on="fsq_place_id", how="left")
87
+ print(f" pois with coords: {pois['fsq_latitude'].notna().sum():,} / {len(pois):,}")
88
+
89
+ print("[load] region_labels")
90
+ region_labels = pd.read_parquet(ROOT / "region_labels.parquet")
91
+ region_name = dict(zip(region_labels["region_id"], region_labels["city_name"]))
92
+ region_country = dict(zip(region_labels["region_id"], region_labels["country_name"]))
93
+
94
+ # ------------------------------------------------------------------
95
+ # Build per-(region, venue) home/OOT visit counters by exploding c_h / c_o.
96
+ # ------------------------------------------------------------------
97
+ print("[derive] expanding c_h / c_o into per-checkin (region, venue, user) frame")
98
+ venue_to_locality = dict(zip(pois["fsq_place_id"], pois["locality"]))
99
+
100
+ def explode(df, c_col, r_col):
101
+ # Returns flat DataFrame: user_id, region, venue.
102
+ all_user, all_region, all_venue = [], [], []
103
+ # Faster than apply: iterate rows once.
104
+ for u, r, lst in zip(df["user_id"].values, df[r_col].values, df[c_col].values):
105
+ for ck in lst:
106
+ all_user.append(u)
107
+ all_region.append(r)
108
+ all_venue.append(ck["venue_id"])
109
+ return pd.DataFrame({"user_id": np.asarray(all_user, dtype=np.int64),
110
+ "region": all_region,
111
+ "venue": all_venue})
112
+
113
+ home_ck = explode(tb, "c_h", "r_h")
114
+ oot_ck = explode(tb, "c_o", "r_o")
115
+ print(f" home check-ins: {len(home_ck):,}")
116
+ print(f" oot check-ins: {len(oot_ck):,}")
117
+
118
+ # ------------------------------------------------------------------
119
+ # 1) Per-region POI entropy (home and OOT separately).
120
+ # ------------------------------------------------------------------
121
+ print("[plot] city POI entropy")
122
+ home_poi_counts = (home_ck.groupby(["region", "venue"]).size()
123
+ .reset_index(name="n"))
124
+ oot_poi_counts = (oot_ck.groupby(["region", "venue"]).size()
125
+ .reset_index(name="n"))
126
+
127
+ home_poi_H = per_group_entropy(home_poi_counts, "region", "n")
128
+ oot_poi_H = per_group_entropy(oot_poi_counts, "region", "n")
129
+
130
+ # 2) Per-region user-activity entropy.
131
+ home_user_counts = (home_ck.groupby(["region", "user_id"]).size()
132
+ .reset_index(name="n"))
133
+ oot_user_counts = (oot_ck.groupby(["region", "user_id"]).size()
134
+ .reset_index(name="n"))
135
+ home_user_H = per_group_entropy(home_user_counts, "region", "n")
136
+ oot_user_H = per_group_entropy(oot_user_counts, "region", "n")
137
+
138
+ # Save CSVs for paper tables.
139
+ for df, name in [(home_poi_H, "home_poi_entropy"),
140
+ (oot_poi_H, "oot_poi_entropy"),
141
+ (home_user_H, "home_user_entropy"),
142
+ (oot_user_H, "oot_user_entropy")]:
143
+ df = df.copy()
144
+ df["city_name"] = df["region"].map(region_name)
145
+ df["country"] = df["region"].map(region_country)
146
+ df.to_csv(OUT_DIR / f"{name}.csv", index=False)
147
+
148
+ # ---- Plot 1 ----
149
+ fig, axes = plt.subplots(1, 2, figsize=(11, 4))
150
+ axes[0].hist(home_poi_H["H"], bins=40, alpha=0.6, color="#1f77b4",
151
+ label=f"home (n={len(home_poi_H)})")
152
+ axes[0].hist(oot_poi_H["H"], bins=40, alpha=0.6, color="#d62728",
153
+ label=f"oot (n={len(oot_poi_H)})")
154
+ axes[0].set_xlabel("Shannon entropy (bits) of POI visit distribution")
155
+ axes[0].set_ylabel("# regions")
156
+ axes[0].set_title("Raw POI entropy")
157
+ axes[0].legend()
158
+
159
+ axes[1].hist(home_poi_H["H_norm"], bins=40, alpha=0.6, color="#1f77b4", label="home")
160
+ axes[1].hist(oot_poi_H["H_norm"], bins=40, alpha=0.6, color="#d62728", label="oot")
161
+ axes[1].set_xlabel(r"Normalized entropy $H/\log_2(n_{POIs})$ $\in [0,1]$")
162
+ axes[1].set_title("Normalized POI entropy")
163
+ axes[1].legend()
164
+ fig.suptitle("Per-region POI visit-distribution entropy", fontsize=12)
165
+ fig.tight_layout()
166
+ fig.savefig(OUT_DIR / "city_poi_entropy_hist.pdf", bbox_inches="tight")
167
+ plt.close(fig)
168
+
169
+ # ---- Plot 2 ----
170
+ fig, axes = plt.subplots(1, 2, figsize=(11, 4))
171
+ axes[0].hist(home_user_H["H"], bins=40, alpha=0.6, color="#2ca02c", label="home")
172
+ axes[0].hist(oot_user_H["H"], bins=40, alpha=0.6, color="#9467bd", label="oot")
173
+ axes[0].set_xlabel("Entropy (bits) of check-ins across users")
174
+ axes[0].set_ylabel("# regions")
175
+ axes[0].set_title("Raw user-activity entropy")
176
+ axes[0].legend()
177
+
178
+ axes[1].hist(home_user_H["H_norm"], bins=40, alpha=0.6, color="#2ca02c", label="home")
179
+ axes[1].hist(oot_user_H["H_norm"], bins=40, alpha=0.6, color="#9467bd", label="oot")
180
+ axes[1].set_xlabel(r"Normalized entropy $H/\log_2(n_{users})$ $\in [0,1]$")
181
+ axes[1].set_title("Normalized user-activity entropy")
182
+ axes[1].legend()
183
+ fig.suptitle("Per-region user-activity entropy (low = power-user dominance)", fontsize=12)
184
+ fig.tight_layout()
185
+ fig.savefig(OUT_DIR / "city_user_entropy_hist.pdf", bbox_inches="tight")
186
+ plt.close(fig)
187
+
188
+ # ------------------------------------------------------------------
189
+ # 3) Top-30 regions by total check-ins.
190
+ # ------------------------------------------------------------------
191
+ print("[plot] top-30 cities by check-ins")
192
+ home_per_region = home_ck.groupby("region").size().rename("home")
193
+ oot_per_region = oot_ck.groupby("region").size().rename("oot")
194
+ per_region = pd.concat([home_per_region, oot_per_region], axis=1).fillna(0).astype(np.int64)
195
+ per_region["total"] = per_region["home"] + per_region["oot"]
196
+ top30 = per_region.sort_values("total", ascending=False).head(30)
197
+ top30_labels = [f"{region_name.get(r, r)}\n({region_country.get(r, '?')})" for r in top30.index]
198
+
199
+ fig, ax = plt.subplots(figsize=(13, 6))
200
+ x = np.arange(len(top30))
201
+ ax.bar(x, top30["home"], color="#1f77b4", label="home check-ins")
202
+ ax.bar(x, top30["oot"], bottom=top30["home"], color="#d62728", label="OOT check-ins")
203
+ ax.set_xticks(x)
204
+ ax.set_xticklabels(top30_labels, rotation=60, ha="right", fontsize=7)
205
+ ax.set_ylabel("# check-ins")
206
+ ax.set_title("Top-30 regions by total check-ins (home + OOT)")
207
+ ax.legend()
208
+ fig.tight_layout()
209
+ fig.savefig(OUT_DIR / "checkins_per_city_top30.pdf", bbox_inches="tight")
210
+ plt.close(fig)
211
+
212
+ # ------------------------------------------------------------------
213
+ # 4) Per-user trajectory lengths.
214
+ # ------------------------------------------------------------------
215
+ print("[plot] trajectory lengths")
216
+ user_home = tb.groupby("user_id")["n_home_ci"].sum().values
217
+ user_oot = tb.groupby("user_id")["n_travel_ci"].sum().values
218
+
219
+ fig, axes = plt.subplots(1, 2, figsize=(11, 4))
220
+ axes[0].hist(np.log10(user_home + 1), bins=60, alpha=0.6, color="#1f77b4", label="home")
221
+ axes[0].hist(np.log10(user_oot + 1), bins=60, alpha=0.6, color="#d62728", label="oot")
222
+ axes[0].set_xlabel(r"$\log_{10}$(# check-ins per user)")
223
+ axes[0].set_ylabel("# users")
224
+ axes[0].set_title("Per-user check-in count distribution")
225
+ axes[0].legend()
226
+
227
+ sh = np.sort(user_home)
228
+ so = np.sort(user_oot)
229
+ axes[1].plot(sh, np.arange(1, len(sh) + 1) / len(sh), color="#1f77b4", label="home")
230
+ axes[1].plot(so, np.arange(1, len(so) + 1) / len(so), color="#d62728", label="oot")
231
+ axes[1].set_xscale("log")
232
+ axes[1].set_xlabel("# check-ins per user")
233
+ axes[1].set_ylabel("CDF over users")
234
+ axes[1].set_title("Per-user check-in count CDF")
235
+ axes[1].legend()
236
+ fig.suptitle("How active is each user?", fontsize=12)
237
+ fig.tight_layout()
238
+ fig.savefig(OUT_DIR / "trajectory_length_dist.pdf", bbox_inches="tight")
239
+ plt.close(fig)
240
+
241
+ # ------------------------------------------------------------------
242
+ # 5) Top travel pairs.
243
+ # ------------------------------------------------------------------
244
+ print("[plot] top travel pairs")
245
+ pair_counts = (tb.groupby(["r_h", "r_o"]).size()
246
+ .sort_values(ascending=False))
247
+ top_pairs = pair_counts.head(30)
248
+ pair_labels = [f"{region_name.get(h, h)} → {region_name.get(o, o)}"
249
+ for (h, o) in top_pairs.index]
250
+
251
+ fig, ax = plt.subplots(figsize=(11, 7))
252
+ y = np.arange(len(top_pairs))
253
+ ax.barh(y, top_pairs.values, color="#ff7f0e")
254
+ ax.set_yticks(y)
255
+ ax.set_yticklabels(pair_labels, fontsize=8)
256
+ ax.invert_yaxis()
257
+ ax.set_xlabel("# τ travel-behavior records")
258
+ ax.set_title(f"Top-30 (home → OOT) pairs (of {len(pair_counts):,} pairs total)")
259
+ fig.tight_layout()
260
+ fig.savefig(OUT_DIR / "top_travel_pairs.pdf", bbox_inches="tight")
261
+ plt.close(fig)
262
+
263
+ # ------------------------------------------------------------------
264
+ # 6) Entropy vs city size scatter.
265
+ # ------------------------------------------------------------------
266
+ print("[plot] entropy vs size scatter")
267
+ fig, axes = plt.subplots(1, 2, figsize=(11, 4))
268
+ axes[0].scatter(home_poi_H["total"], home_poi_H["H_norm"], s=8, alpha=0.4,
269
+ color="#1f77b4", label="home")
270
+ axes[0].scatter(oot_poi_H["total"], oot_poi_H["H_norm"], s=8, alpha=0.4,
271
+ color="#d62728", label="oot")
272
+ axes[0].set_xscale("log")
273
+ axes[0].set_xlabel("# check-ins in region")
274
+ axes[0].set_ylabel("Normalized POI entropy")
275
+ axes[0].set_title("POI entropy vs region size")
276
+ axes[0].legend()
277
+
278
+ axes[1].scatter(home_user_H["total"], home_user_H["H_norm"], s=8, alpha=0.4,
279
+ color="#2ca02c", label="home")
280
+ axes[1].scatter(oot_user_H["total"], oot_user_H["H_norm"], s=8, alpha=0.4,
281
+ color="#9467bd", label="oot")
282
+ axes[1].set_xscale("log")
283
+ axes[1].set_xlabel("# check-ins in region")
284
+ axes[1].set_ylabel("Normalized user-activity entropy")
285
+ axes[1].set_title("User entropy vs region size")
286
+ axes[1].legend()
287
+ fig.tight_layout()
288
+ fig.savefig(OUT_DIR / "entropy_vs_size_scatter.pdf", bbox_inches="tight")
289
+ plt.close(fig)
290
+
291
+ # ------------------------------------------------------------------
292
+ # 7) World POI density heatmap.
293
+ # ------------------------------------------------------------------
294
+ print("[plot] world POI density")
295
+ poi_coord = pois.dropna(subset=["fsq_latitude", "fsq_longitude"]).copy()
296
+ poi_coord["weight"] = poi_coord["n_checkins"].astype(np.float64)
297
+
298
+ fig = plt.figure(figsize=(13, 6.5))
299
+ ax = plt.axes(projection=ccrs.Robinson())
300
+ add_world_features(ax)
301
+ h, xedges, yedges = np.histogram2d(
302
+ poi_coord["fsq_longitude"].values,
303
+ poi_coord["fsq_latitude"].values,
304
+ bins=[np.arange(-180, 181, 1), np.arange(-90, 91, 1)],
305
+ weights=poi_coord["weight"].values,
306
+ )
307
+ h = h.T
308
+ h_masked = np.ma.masked_where(h == 0, h)
309
+ mesh = ax.pcolormesh(
310
+ xedges, yedges, h_masked, cmap="magma_r",
311
+ norm=LogNorm(vmin=1, vmax=h_masked.max()),
312
+ transform=ccrs.PlateCarree(), zorder=2,
313
+ )
314
+ cbar = fig.colorbar(mesh, ax=ax, orientation="horizontal", pad=0.04, shrink=0.7)
315
+ cbar.set_label("Total check-ins per 1° × 1° cell (log scale)")
316
+ ax.set_title(f"Global check-in density (n_POIs = {len(poi_coord):,}; "
317
+ f"check-ins = {int(poi_coord['weight'].sum()):,})")
318
+ fig.tight_layout()
319
+ fig.savefig(OUT_DIR / "world_poi_density.pdf", bbox_inches="tight")
320
+ plt.close(fig)
321
+
322
+ # ------------------------------------------------------------------
323
+ # 8) City centroids.
324
+ # ------------------------------------------------------------------
325
+ print("[plot] city centroids")
326
+ pc = poi_coord.copy()
327
+ pc["lat_w"] = pc["fsq_latitude"] * pc["weight"]
328
+ pc["lon_w"] = pc["fsq_longitude"] * pc["weight"]
329
+ centroid_agg = pc.groupby("locality").agg(
330
+ lat=("lat_w", "sum"),
331
+ lon=("lon_w", "sum"),
332
+ weight=("weight", "sum"),
333
+ )
334
+ centroid_agg["lat"] = centroid_agg["lat"] / centroid_agg["weight"]
335
+ centroid_agg["lon"] = centroid_agg["lon"] / centroid_agg["weight"]
336
+
337
+ home_set = set(per_region.index[per_region["home"] > 0])
338
+ oot_set = set(per_region.index[per_region["oot"] > 0])
339
+ both = home_set & oot_set
340
+ only_home = home_set - oot_set
341
+ only_oot = oot_set - home_set
342
+
343
+ rows = []
344
+ for r in centroid_agg.index:
345
+ n_h = int(per_region.loc[r, "home"]) if r in per_region.index else 0
346
+ n_o = int(per_region.loc[r, "oot"]) if r in per_region.index else 0
347
+ if r in both: kind = "both"
348
+ elif r in only_home: kind = "home only"
349
+ elif r in only_oot: kind = "oot only"
350
+ else: continue
351
+ rows.append((r, centroid_agg.loc[r, "lat"], centroid_agg.loc[r, "lon"],
352
+ n_h + n_o, kind))
353
+ cents = pd.DataFrame(rows, columns=["region", "lat", "lon", "n", "kind"])
354
+
355
+ fig = plt.figure(figsize=(13, 6.5))
356
+ ax = plt.axes(projection=ccrs.Robinson())
357
+ add_world_features(ax)
358
+ SIZE_SCALE = 1.5
359
+ sizes = SIZE_SCALE * np.sqrt(cents["n"].values)
360
+ palette = {"both": "#2ca02c", "home only": "#1f77b4", "oot only": "#d62728"}
361
+
362
+ # 1. Plot the real data WITHOUT label= so the legend doesn't auto-pick a
363
+ # representative marker size that differs across kinds.
364
+ for kind, color in palette.items():
365
+ m = cents["kind"] == kind
366
+ ax.scatter(
367
+ cents.loc[m, "lon"], cents.loc[m, "lat"],
368
+ s=sizes[m], c=color, alpha=0.55,
369
+ edgecolor="black", linewidth=0.2,
370
+ transform=ccrs.PlateCarree(), zorder=3,
371
+ )
372
+
373
+ # 2. Empty proxy scatters at a fixed marker size for the kind legend so
374
+ # all three swatches render identically.
375
+ KIND_LEGEND_S = 60
376
+ for kind, color in palette.items():
377
+ n = int((cents["kind"] == kind).sum())
378
+ ax.scatter([], [], s=KIND_LEGEND_S, c=color, alpha=0.55,
379
+ edgecolor="black", linewidth=0.2,
380
+ label=f"{kind} (n={n})",
381
+ transform=ccrs.PlateCarree())
382
+
383
+ # 3. Size-reference proxies (these are intentionally size-varying — they
384
+ # are the *legend's purpose*, not category swatches).
385
+ for ref_n, lbl in [(500, "500"), (10_000, "10K"), (100_000, "100K")]:
386
+ ax.scatter([], [], s=SIZE_SCALE * np.sqrt(ref_n), c="grey", alpha=0.55,
387
+ edgecolor="black", linewidth=0.2,
388
+ label=f"≈ {lbl} check-ins", transform=ccrs.PlateCarree())
389
+
390
+ ax.legend(loc="lower left", fontsize=8, frameon=True, ncol=2)
391
+ ax.set_title(f"Region coverage ({len(cents):,} regions)")
392
+ fig.tight_layout()
393
+ fig.savefig(OUT_DIR / "world_city_centroids.pdf", bbox_inches="tight")
394
+ plt.close(fig)
395
+
396
+ # ------------------------------------------------------------------
397
+ # 9) Top-100 travel flows.
398
+ # ------------------------------------------------------------------
399
+ print("[plot] world travel flows")
400
+ cent_lat = centroid_agg["lat"].to_dict()
401
+ cent_lon = centroid_agg["lon"].to_dict()
402
+ top_flows = pair_counts.head(100)
403
+
404
+ fig = plt.figure(figsize=(13, 6.5))
405
+ ax = plt.axes(projection=ccrs.Robinson())
406
+ add_world_features(ax)
407
+ max_n = int(top_flows.max())
408
+ cmap = plt.get_cmap("plasma")
409
+ n_drawn = 0
410
+ for (h, o), n in top_flows.items():
411
+ if h not in cent_lat or o not in cent_lat:
412
+ continue
413
+ a = (cent_lat[h], cent_lon[h])
414
+ b = (cent_lat[o], cent_lon[o])
415
+ lw = 0.4 + 2.5 * (n / max_n)
416
+ color = cmap(n / max_n)
417
+ ax.plot([a[1], b[1]], [a[0], b[0]],
418
+ transform=ccrs.Geodetic(),
419
+ color=color, alpha=0.65, linewidth=lw, zorder=2)
420
+ ax.scatter([a[1], b[1]], [a[0], b[0]], s=4, c="black",
421
+ transform=ccrs.PlateCarree(), zorder=3)
422
+ n_drawn += 1
423
+ sm = plt.cm.ScalarMappable(cmap=cmap,
424
+ norm=plt.Normalize(vmin=int(top_flows.min()), vmax=max_n))
425
+ sm.set_array([])
426
+ cbar = fig.colorbar(sm, ax=ax, orientation="horizontal", pad=0.04, shrink=0.7)
427
+ cbar.set_label("# τ travel records on this (home → OOT) pair")
428
+ ax.set_title(f"Top-{n_drawn} home → OOT travel flows "
429
+ f"(of {len(pair_counts):,} pairs total)")
430
+ fig.tight_layout()
431
+ fig.savefig(OUT_DIR / "world_travel_flows.pdf", bbox_inches="tight")
432
+ plt.close(fig)
433
+
434
+ # ------------------------------------------------------------------
435
+ # 10) Country distribution.
436
+ # ------------------------------------------------------------------
437
+ print("[plot] country distribution")
438
+ region_country_series = pd.Series(region_country, name="country")
439
+ cities_per_country = region_country_series.value_counts().sort_values(ascending=False)
440
+
441
+ region_total = per_region["total"].rename("total")
442
+ rc_df = region_total.to_frame().join(region_country_series, how="left")
443
+ checkins_per_country = (rc_df.groupby("country")["total"].sum()
444
+ .reindex(cities_per_country.index)
445
+ .fillna(0))
446
+
447
+ cap = 20 # too many countries — show top-20 in each panel
448
+ cpc = cities_per_country.head(cap)
449
+ chk = checkins_per_country.head(cap)
450
+
451
+ fig, axes = plt.subplots(1, 2, figsize=(13, 5.5))
452
+ axes[0].barh(cpc.index[::-1], cpc.values[::-1], color="#17becf")
453
+ axes[0].set_xlabel("# regions in this dataset")
454
+ axes[0].set_title(f"Top-{cap} countries by # regions (total countries = {len(cities_per_country)})")
455
+ axes[0].tick_params(axis="y", labelsize=8)
456
+
457
+ axes[1].barh(chk.index[::-1], chk.values[::-1], color="#bcbd22")
458
+ axes[1].set_xlabel("# check-ins (home + OOT)")
459
+ axes[1].set_title("Top-20 countries by # check-ins")
460
+ axes[1].tick_params(axis="y", labelsize=8)
461
+ axes[1].set_xscale("log")
462
+ fig.tight_layout()
463
+ fig.savefig(OUT_DIR / "country_distribution.pdf", bbox_inches="tight")
464
+ plt.close(fig)
465
+
466
+ # ------------------------------------------------------------------
467
+ print()
468
+ print(f"figures saved to: {OUT_DIR}")
469
+ for p in sorted(OUT_DIR.glob("*.pdf")):
470
+ print(f" {p.name}")
471
+ print()
472
+ print("== quick stats ==")
473
+ print(f"τ records: {len(tb):,} ({tb.user_id.nunique():,} distinct users)")
474
+ print(f"home check-ins: {len(home_ck):,} oot check-ins: {len(oot_ck):,}")
475
+ print(f"regions home: {len(home_set):,} oot: {len(oot_set):,} both: {len(both):,} "
476
+ f"only-home: {len(only_home):,} only-oot: {len(only_oot):,}")
477
+ print(f"unique (home → oot) pairs: {len(pair_counts):,}")
478
+ print(f"home POI entropy median H_norm = {home_poi_H['H_norm'].median():.3f}")
479
+ print(f"oot POI entropy median H_norm = {oot_poi_H['H_norm'].median():.3f}")
480
+ print(f"home user-act entropy median H_norm = {home_user_H['H_norm'].median():.3f}")
481
+ print(f"oot user-act entropy median H_norm = {oot_user_H['H_norm'].median():.3f}")
482
+
483
+
484
+ if __name__ == "__main__":
485
+ main()
_scripts/viz_traj_length.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Trajectory length distribution for Trip World.
2
+
3
+ A *trajectory* is one trail_id — a single session of consecutive check-ins.
4
+ Each travel-behavior row in travel_behaviors.parquet bundles many trails
5
+ (median ~12 hometown trails + ~2 OOT trails per τ record), so to get
6
+ honest trajectory lengths we explode c_h and c_o by trail_id and count
7
+ check-ins per trail.
8
+
9
+ Output: viz/trajectory_length.pdf
10
+ Run: python _scripts/viz_traj_length.py
11
+ """
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+ import pandas as pd
16
+ import matplotlib
17
+ matplotlib.use("Agg")
18
+ import matplotlib.pyplot as plt
19
+ import os
20
+
21
+ ROOT = Path(os.environ.get("TRIP_WORLD_ROOT", Path(__file__).resolve().parent.parent))
22
+ OUT_DIR = ROOT / "viz"
23
+ OUT_DIR.mkdir(parents=True, exist_ok=True)
24
+
25
+
26
+ def trail_lengths(arrays):
27
+ """Walk a column of c_h / c_o object arrays and emit the per-trail
28
+ check-in counts, **deduplicated globally by trail_id**.
29
+
30
+ The same hometown trail typically appears inside many τ records (one
31
+ per distinct destination the same user travels to). We count each
32
+ trail's length once. Within a single τ record, all check-ins sharing a
33
+ trail_id together form that trail."""
34
+ trail_to_len = {}
35
+ cur = {}
36
+ for lst in arrays:
37
+ cur.clear()
38
+ for ck in lst:
39
+ tid = ck["trail_id"]
40
+ cur[tid] = cur.get(tid, 0) + 1
41
+ for tid, n in cur.items():
42
+ trail_to_len[tid] = n
43
+ return np.fromiter(trail_to_len.values(), dtype=np.int64, count=len(trail_to_len))
44
+
45
+
46
+ def main():
47
+ print("[load] travel_behaviors (c_h, c_o) — exploding by trail_id")
48
+ tb = pd.read_parquet(ROOT / "travel_behaviors.parquet",
49
+ columns=["c_h", "c_o"])
50
+ print(f" τ records: {len(tb):,}")
51
+ h = trail_lengths(tb["c_h"].values)
52
+ o = trail_lengths(tb["c_o"].values)
53
+ print(f" hometown trails: {len(h):,} median={int(np.median(h))} mean={h.mean():.2f} "
54
+ f"p10={int(np.percentile(h,10))} p90={int(np.percentile(h,90))} max={h.max()}")
55
+ print(f" OOT trails: {len(o):,} median={int(np.median(o))} mean={o.mean():.2f} "
56
+ f"p10={int(np.percentile(o,10))} p90={int(np.percentile(o,90))} max={o.max()}")
57
+
58
+ HOME = "#1f77b4"
59
+ TRIP = "#d62728"
60
+ home_label = f"Hometown trajectories (n={len(h):,}, median {int(np.median(h))})"
61
+ trip_label = f"OOT trajectories (n={len(o):,}, median {int(np.median(o))})"
62
+
63
+ fig, ax = plt.subplots(figsize=(7, 4.2))
64
+
65
+ # Integer-length, side-by-side bars. Lengths 1..CAP get their own
66
+ # bar pair; everything past CAP is folded into a single ">CAP" pair.
67
+ CAP = 10
68
+ lengths = np.arange(1, CAP + 1)
69
+ h_counts = np.array([(h == L).sum() for L in lengths] + [(h > CAP).sum()])
70
+ o_counts = np.array([(o == L).sum() for L in lengths] + [(o > CAP).sum()])
71
+
72
+ x = np.arange(len(h_counts))
73
+ width = 0.4
74
+ ax.bar(x - width / 2, h_counts, width, color=HOME, label=home_label)
75
+ ax.bar(x + width / 2, o_counts, width, color=TRIP, label=trip_label)
76
+ ax.set_xticks(x)
77
+ ax.set_xticklabels([str(L) for L in lengths] + [f">{CAP}"])
78
+
79
+ ax.set_xlabel("Number of check-ins")
80
+ ax.set_ylabel("Number of trajectories")
81
+ ax.set_title("Trajectory length distribution")
82
+ ax.legend()
83
+ fig.tight_layout()
84
+
85
+ print(f" > {CAP} check-ins: hometown {(h > CAP).sum():,} / {len(h):,} "
86
+ f"({(h > CAP).mean()*100:.2f}%); "
87
+ f"oot {(o > CAP).sum():,} / {len(o):,} "
88
+ f"({(o > CAP).mean()*100:.2f}%)")
89
+ out = OUT_DIR / "trajectory_length.pdf"
90
+ fig.savefig(out, bbox_inches="tight")
91
+ plt.close(fig)
92
+
93
+ # Drop the older versions if they're around, so only one canonical file remains.
94
+ for old_name in ("trajectory_length_per_tau.pdf",
95
+ "trajectory_length_per_trip.pdf",
96
+ "trajectory_length_per_trajectory.pdf"):
97
+ old = OUT_DIR / old_name
98
+ if old.exists():
99
+ old.unlink()
100
+ print(f"\nsaved: {out}")
101
+
102
+
103
+ if __name__ == "__main__":
104
+ main()
metadata/metadata_all.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:20c8affe6092df1202074e4458672a57e77d96505ede4fb63fa65b0b3d0b22d3
3
+ size 119796103
metadata/place_attributes.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4c31fda0a865c6773ff4067bb20ebd16c2ffde8925ded0da3b26d322d942c3b8
3
+ size 5580621
metro_mapping_clean.json ADDED
The diff for this file is too large to render. See raw diff
 
pois.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:43c3d385700ca050bb1b109ab98481dddce85150b4a8f1cc455fa4994b8f3f0e
3
+ size 69707931
region_labels.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:98134206f3ae04366de219e181380a5c9c302873391ccc9109fa491fe9f11c59
3
+ size 19217
reviews/reviews_all.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:60aa08489743419a26475a842398040dfdc9a508572cb51aa19e864966f10a7c
3
+ size 23400867153
travel_behaviors.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:59d473611daca78404fda149832012562e11469cd0339094c92d2f86d4655034
3
+ size 151509028