views-datafactory 1.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. datafactory_adapters/ARCHITECTURE.md +54 -0
  2. datafactory_adapters/__init__.py +38 -0
  3. datafactory_adapters/_conservation.py +95 -0
  4. datafactory_adapters/_reconciliation.py +92 -0
  5. datafactory_adapters/_validation.py +39 -0
  6. datafactory_adapters/feature_frame.py +25 -0
  7. datafactory_adapters/grid_from_feature_frame.py +89 -0
  8. datafactory_adapters/grid_to_country_month.py +169 -0
  9. datafactory_adapters/grid_to_dataframe.py +176 -0
  10. datafactory_compilation/ARCHITECTURE.md +63 -0
  11. datafactory_compilation/__init__.py +39 -0
  12. datafactory_compilation/aggregation.py +64 -0
  13. datafactory_compilation/compilation_config.py +97 -0
  14. datafactory_compilation/conservation.py +36 -0
  15. datafactory_compilation/grid_compilation.py +352 -0
  16. datafactory_compilation/output.py +85 -0
  17. datafactory_compilation/preflight.py +61 -0
  18. datafactory_compilation/pregridded_compilation.py +291 -0
  19. datafactory_consolidation/ARCHITECTURE.md +58 -0
  20. datafactory_consolidation/__init__.py +28 -0
  21. datafactory_consolidation/consolidation_result.py +27 -0
  22. datafactory_consolidation/consolidators/__init__.py +32 -0
  23. datafactory_consolidation/consolidators/acled.py +462 -0
  24. datafactory_consolidation/consolidators/ucdp.py +524 -0
  25. datafactory_consolidation/event_store.py +67 -0
  26. datafactory_consolidation/tagging.py +46 -0
  27. datafactory_harvester/ARCHITECTURE.md +103 -0
  28. datafactory_harvester/__init__.py +37 -0
  29. datafactory_harvester/event_validation.py +372 -0
  30. datafactory_harvester/harvest_runner.py +72 -0
  31. datafactory_harvester/pipeline_runner.py +125 -0
  32. datafactory_harvester/snapshot_storage.py +117 -0
  33. datafactory_harvester/sources/__init__.py +36 -0
  34. datafactory_harvester/sources/_ucdp_common.py +34 -0
  35. datafactory_harvester/sources/acled.py +743 -0
  36. datafactory_harvester/sources/gaul_admin.py +567 -0
  37. datafactory_harvester/sources/ghsbuilts.py +271 -0
  38. datafactory_harvester/sources/ghspop.py +267 -0
  39. datafactory_harvester/sources/priogrid_static.py +359 -0
  40. datafactory_harvester/sources/shdi.py +625 -0
  41. datafactory_harvester/sources/ucdp_annual.py +616 -0
  42. datafactory_harvester/sources/ucdp_candidate.py +419 -0
  43. datafactory_harvester/sources/ucdp_dot9.py +407 -0
  44. datafactory_harvester/sources/vdem.py +350 -0
  45. datafactory_harvester/validation.py +74 -0
  46. datafactory_http/__init__.py +10 -0
  47. datafactory_http/retry.py +102 -0
  48. datafactory_priogrid/ARCHITECTURE.md +62 -0
  49. datafactory_priogrid/__init__.py +51 -0
  50. datafactory_priogrid/cell_generator.py +137 -0
  51. datafactory_priogrid/grid_config.py +107 -0
  52. datafactory_priogrid/land_mask.py +62 -0
  53. datafactory_priogrid/parity_validation.py +176 -0
  54. datafactory_priogrid/shapefile_harvester.py +174 -0
  55. datafactory_priogrid/shapefile_reader.py +125 -0
  56. datafactory_priogrid/spatiotemporal.py +66 -0
  57. datafactory_priogrid/temporal_config.py +78 -0
  58. datafactory_priogrid/temporal_generator.py +65 -0
  59. datafactory_provenance/ARCHITECTURE.md +61 -0
  60. datafactory_provenance/__init__.py +81 -0
  61. datafactory_provenance/constants.py +3 -0
  62. datafactory_provenance/digests_and_ledgers.py +370 -0
  63. datafactory_provenance/health.py +310 -0
  64. datafactory_provenance/pipeline_lock.py +200 -0
  65. datafactory_provenance/registry.py +92 -0
  66. datafactory_provenance/skip.py +212 -0
  67. datafactory_provenance/source_registry.py +466 -0
  68. datafactory_query/ARCHITECTURE.md +60 -0
  69. datafactory_query/__init__.py +36 -0
  70. datafactory_query/africa_me_gaul_pgids.json +1 -0
  71. datafactory_query/africa_me_legacy_pgids.json +1 -0
  72. datafactory_query/backends_npy.py +90 -0
  73. datafactory_query/backends_zarr.py +259 -0
  74. datafactory_query/coverage.py +64 -0
  75. datafactory_query/dataset.py +263 -0
  76. datafactory_query/defaults.py +101 -0
  77. datafactory_query/land_gaul_pgids.json +1 -0
  78. datafactory_query/land_pgids.json +1 -0
  79. datafactory_query/output_format.py +52 -0
  80. datafactory_query/regions.py +293 -0
  81. datafactory_query/temporal.py +115 -0
  82. datafactory_viewpoint/ARCHITECTURE.md +68 -0
  83. datafactory_viewpoint/__init__.py +33 -0
  84. datafactory_viewpoint/builders/__init__.py +32 -0
  85. datafactory_viewpoint/builders/acled_v1.py +213 -0
  86. datafactory_viewpoint/builders/ghsbuilts_v1.py +351 -0
  87. datafactory_viewpoint/builders/ghspop_v1.py +471 -0
  88. datafactory_viewpoint/builders/shdi_v1.py +389 -0
  89. datafactory_viewpoint/builders/ucdp_v1.py +437 -0
  90. datafactory_viewpoint/builders/vdem_v1.py +419 -0
  91. datafactory_viewpoint/profiles.py +169 -0
  92. datafactory_viewpoint/raster_io.py +49 -0
  93. datafactory_viewpoint/spatial_distribution.py +203 -0
  94. datafactory_viewpoint/spatial_weights.py +207 -0
  95. datafactory_viewpoint/survivorship.py +108 -0
  96. datafactory_viewpoint/temporal.py +111 -0
  97. datafactory_viewpoint/temporal_distribution.py +295 -0
  98. datafactory_viewpoint/viewpoint_config.py +124 -0
  99. datafactory_viewpoint/viewpoint_result.py +33 -0
  100. views_datafactory-1.9.0.dist-info/METADATA +528 -0
  101. views_datafactory-1.9.0.dist-info/RECORD +103 -0
  102. views_datafactory-1.9.0.dist-info/WHEEL +4 -0
  103. views_datafactory-1.9.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,625 @@
1
+ """GDL Subnational HDI (SHDI) harvester — API download.
2
+
3
+ Downloads SHDI data from the GDL Data API, stores as Parquet,
4
+ and builds a spatial join crosswalk mapping GDL regions to
5
+ PRIO-GRID cells. GDL shapefiles are downloaded from the PRIO CDN.
6
+
7
+ Authentication: API token via GDL_API_TOKEN env var (ADR-026).
8
+ Free account at globaldatalab.org → "My GDL" → "API Access".
9
+
10
+ Source: Global Data Lab, Radboud University
11
+ https://globaldatalab.org/shdi/
12
+
13
+ Ref: ADR-036 (SHDI source selection).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ import os
20
+ import time
21
+ import zipfile
22
+ from dataclasses import dataclass
23
+ from pathlib import Path
24
+
25
+ import pyarrow as pa
26
+ import pyarrow.csv as pcsv
27
+ import pyarrow.parquet as pq
28
+ import requests as _requests
29
+ import shapefile as shp
30
+ from shapely import STRtree
31
+ from shapely.geometry import Point, shape
32
+
33
+ from datafactory_harvester.sources import register_source
34
+ from datafactory_harvester.validation import (
35
+ validate_nonempty_string,
36
+ validate_positive_int,
37
+ validate_string_tuple,
38
+ )
39
+ from datafactory_http import request_with_retry
40
+ from datafactory_provenance import (
41
+ DIGEST_SCHEME,
42
+ LEDGER_VERSION,
43
+ append_ledger_entry,
44
+ compute_content_digest,
45
+ last_digest_for_version,
46
+ )
47
+
48
+ logger = logging.getLogger(__name__)
49
+
50
+ DATASET_ID = "shdi"
51
+
52
+ SHDI_VARIABLES: tuple[str, ...] = (
53
+ "shdi",
54
+ "healthindex",
55
+ "edindex",
56
+ "incindex",
57
+ )
58
+
59
+ SHDI_ID_COLUMNS: tuple[str, ...] = (
60
+ "GDLCODE",
61
+ "Level",
62
+ "Country",
63
+ "Region",
64
+ "Year",
65
+ )
66
+
67
+ DEFAULT_CENTROID_PATH = Path(
68
+ "data/raw/priogrid/shapefile/priogrid_centroid.shp"
69
+ )
70
+
71
+ DEFAULT_API_BASE_URL = "https://globaldatalab.org"
72
+
73
+ DEFAULT_SHAPEFILE_URL = (
74
+ "https://cdn.cloud.prio.org/files/"
75
+ "604a306f-80de-49af-8610-948af8e2e474/"
76
+ "GDL%20Shapefiles%20V64.zip"
77
+ )
78
+
79
+
80
+ # ---- Credential resolution (ADR-026) ----
81
+
82
+
83
+ def get_gdl_token(token: str | None = None) -> str:
84
+ """Resolve GDL API token from argument or environment.
85
+
86
+ Resolution order (per ADR-026):
87
+ 1. Function argument (highest priority)
88
+ 2. Environment variable GDL_API_TOKEN
89
+ 3. Fail-loud with actionable error message
90
+
91
+ Returns:
92
+ The API token string.
93
+
94
+ Raises:
95
+ ValueError: If no token can be resolved.
96
+ """
97
+ resolved = token or os.environ.get("GDL_API_TOKEN")
98
+ if not resolved:
99
+ msg = (
100
+ "GDL API token required. Set GDL_API_TOKEN "
101
+ "environment variable or pass token= to "
102
+ "fetch_shdi(). Get a free token at "
103
+ "https://globaldatalab.org → My GDL → API Access."
104
+ )
105
+ logger.error(msg)
106
+ raise ValueError(msg)
107
+ return resolved
108
+
109
+
110
+ # ---- Config ----
111
+
112
+
113
+ @dataclass(frozen=True)
114
+ class ShdiConfig:
115
+ """Configuration for harvesting GDL SHDI data.
116
+
117
+ Downloads SHDI CSV from the GDL Data API, GDL shapefiles
118
+ from PRIO CDN, filters to declared variables, stores as
119
+ Parquet, and builds a GDL→pgid spatial join crosswalk.
120
+ """
121
+
122
+ api_base_url: str = DEFAULT_API_BASE_URL
123
+ shapefile_url: str = DEFAULT_SHAPEFILE_URL
124
+ centroid_path: Path = DEFAULT_CENTROID_PATH
125
+ variables: tuple[str, ...] = SHDI_VARIABLES
126
+ data_dir: Path = Path("data/raw/shdi")
127
+ ledger_path: Path = Path(
128
+ "provenance/shdi/ingestion_ledger.jsonl"
129
+ )
130
+ version: str = "v10.2"
131
+ timeout: int = 300
132
+
133
+ def __post_init__(self) -> None:
134
+ validate_string_tuple(self.variables, "variables")
135
+ validate_nonempty_string(self.version, "version")
136
+ validate_positive_int(self.timeout, "timeout")
137
+
138
+ def indicator_url(self, variable: str) -> str:
139
+ return f"{self.api_base_url}/shdi/download/{variable}/"
140
+
141
+ @property
142
+ def output_path(self) -> Path:
143
+ return self.data_dir / f"shdi_{self.version}.parquet"
144
+
145
+ @property
146
+ def crosswalk_path(self) -> Path:
147
+ return self.data_dir / "gdl_to_pgid.parquet"
148
+
149
+ @property
150
+ def shapefile_cache_path(self) -> Path:
151
+ return self.data_dir / "GDL_Shapefiles.zip"
152
+
153
+
154
+ # ---- Fetch ----
155
+
156
+
157
+ def fetch_shdi(
158
+ config: ShdiConfig | None = None,
159
+ *,
160
+ force_refresh: bool = False,
161
+ ) -> dict:
162
+ """Download SHDI CSV from GDL API and build GDL→pgid crosswalk.
163
+
164
+ 1. Check cache (Parquet + crosswalk exist + ledger has digest) → skip
165
+ 2. Resolve GDL API token (ADR-026)
166
+ 3. Download CSV from GDL Data API
167
+ 4. Parse and filter to ID columns + variables
168
+ 5. Write filtered Parquet
169
+ 6. Download GDL shapefiles from PRIO CDN (if not cached)
170
+ 7. Spatial join: GDL polygons × PRIO-GRID centroids → crosswalk
171
+ 8. Record provenance in ledger
172
+
173
+ Args:
174
+ config: Harvest configuration. Defaults to ShdiConfig().
175
+ force_refresh: Re-download even if cached.
176
+
177
+ Returns:
178
+ Result dict with dataset, version, outcome, content_digest.
179
+
180
+ Raises:
181
+ ValueError: Missing token, CSV missing columns, or zero rows.
182
+ requests.RequestException: Network failure (after retries).
183
+ """
184
+ if config is None:
185
+ config = ShdiConfig()
186
+
187
+ config.data_dir.mkdir(parents=True, exist_ok=True)
188
+
189
+ output_path = config.output_path
190
+ crosswalk_path = config.crosswalk_path
191
+
192
+ # Cache check
193
+ if (
194
+ not force_refresh
195
+ and output_path.exists()
196
+ and crosswalk_path.exists()
197
+ ):
198
+ previous = last_digest_for_version(
199
+ config.ledger_path, config.version
200
+ )
201
+ if previous is not None:
202
+ logger.info(
203
+ "SHDI %s cached (digest: %s)",
204
+ config.version, previous,
205
+ )
206
+ return {
207
+ "dataset": DATASET_ID,
208
+ "version": config.version,
209
+ "outcome": "cached",
210
+ "content_digest": previous,
211
+ }
212
+
213
+ # Resolve token
214
+ token = get_gdl_token()
215
+
216
+ # Download each indicator separately (GDL API returns only latest
217
+ # year when multiple indicators are combined in one request).
218
+ logger.info(
219
+ "Downloading SHDI %s — %d indicators ...",
220
+ config.version, len(config.variables),
221
+ )
222
+ t0 = time.monotonic()
223
+ all_csv_bytes: list[bytes] = []
224
+
225
+ for var in config.variables:
226
+ url = config.indicator_url(var)
227
+ logger.info(" %s → %s", var, url)
228
+ try:
229
+ resp = request_with_retry(
230
+ url,
231
+ params={"format": "csv", "token": token},
232
+ timeout=config.timeout,
233
+ )
234
+ except _requests.RequestException:
235
+ logger.error(
236
+ "Download failed for SHDI %s (%s)",
237
+ config.version, var,
238
+ )
239
+ append_ledger_entry(config.ledger_path, {
240
+ "dataset": DATASET_ID,
241
+ "version": config.version,
242
+ "outcome": "failed",
243
+ "reason": f"download failed for {var}",
244
+ "ledger_version": LEDGER_VERSION,
245
+ "digest_algorithm": DIGEST_SCHEME,
246
+ })
247
+ raise
248
+ all_csv_bytes.append(resp.content)
249
+
250
+ elapsed_dl = time.monotonic() - t0
251
+ total_mb = sum(len(b) for b in all_csv_bytes) / 1e6
252
+ logger.info(
253
+ "Downloaded %d indicators (%.1f MB) in %.1fs",
254
+ len(config.variables), total_mb, elapsed_dl,
255
+ )
256
+
257
+ # Parse each indicator CSV and merge on ID columns
258
+ try:
259
+ table = _parse_and_merge(all_csv_bytes, config)
260
+ except ValueError as exc:
261
+ append_ledger_entry(config.ledger_path, {
262
+ "dataset": DATASET_ID,
263
+ "version": config.version,
264
+ "outcome": "failed",
265
+ "reason": str(exc),
266
+ "ledger_version": LEDGER_VERSION,
267
+ "digest_algorithm": DIGEST_SCHEME,
268
+ })
269
+ raise
270
+
271
+ if table.num_rows == 0:
272
+ msg = "SHDI CSV produced zero rows after filtering"
273
+ logger.error(msg)
274
+ append_ledger_entry(config.ledger_path, {
275
+ "dataset": DATASET_ID,
276
+ "version": config.version,
277
+ "outcome": "failed",
278
+ "reason": msg,
279
+ "ledger_version": LEDGER_VERSION,
280
+ "digest_algorithm": DIGEST_SCHEME,
281
+ })
282
+ raise ValueError(msg)
283
+
284
+ # Filter to subnational rows only (level == "Subnat")
285
+ level_col = table.column("Level").to_pylist()
286
+ subnat_mask = [lv == "Subnat" for lv in level_col]
287
+ table = table.filter(pa.array(subnat_mask))
288
+
289
+ if table.num_rows == 0:
290
+ msg = "SHDI CSV has no subnational rows (level == 'Subnat')"
291
+ logger.error(msg)
292
+ append_ledger_entry(config.ledger_path, {
293
+ "dataset": DATASET_ID,
294
+ "version": config.version,
295
+ "outcome": "failed",
296
+ "reason": msg,
297
+ "ledger_version": LEDGER_VERSION,
298
+ "digest_algorithm": DIGEST_SCHEME,
299
+ })
300
+ raise ValueError(msg)
301
+
302
+ # Write data Parquet
303
+ output_path.parent.mkdir(parents=True, exist_ok=True)
304
+ pq.write_table(table, output_path, compression="snappy")
305
+
306
+ elapsed_csv = time.monotonic() - t0
307
+ logger.info(
308
+ "SHDI CSV: %d rows in %.1fs", table.num_rows, elapsed_csv,
309
+ )
310
+
311
+ # Download shapefiles from PRIO CDN (if not cached)
312
+ shapefile_path = config.shapefile_cache_path
313
+ if force_refresh or not shapefile_path.exists():
314
+ logger.info("Downloading GDL shapefiles from PRIO CDN...")
315
+ t_shp = time.monotonic()
316
+ try:
317
+ shp_resp = request_with_retry(
318
+ config.shapefile_url, timeout=config.timeout,
319
+ )
320
+ except _requests.RequestException:
321
+ logger.error(
322
+ "Shapefile download failed for SHDI %s",
323
+ config.version,
324
+ )
325
+ append_ledger_entry(config.ledger_path, {
326
+ "dataset": DATASET_ID,
327
+ "version": config.version,
328
+ "outcome": "failed",
329
+ "reason": "shapefile download failed",
330
+ "ledger_version": LEDGER_VERSION,
331
+ "digest_algorithm": DIGEST_SCHEME,
332
+ })
333
+ raise
334
+ shapefile_path.write_bytes(shp_resp.content)
335
+ logger.info(
336
+ "Shapefiles: %.1f MB in %.1fs",
337
+ len(shp_resp.content) / 1e6,
338
+ time.monotonic() - t_shp,
339
+ )
340
+
341
+ # Spatial join: GDL shapefiles → PRIO-GRID centroids
342
+ t1 = time.monotonic()
343
+ crosswalk = _build_crosswalk(
344
+ shapefile_path, config.centroid_path,
345
+ )
346
+
347
+ crosswalk_table = pa.table({
348
+ "gid": pa.array(
349
+ [gid for gid, _ in crosswalk], type=pa.int32()
350
+ ),
351
+ "gdl_code": pa.array(
352
+ [code for _, code in crosswalk], type=pa.string()
353
+ ),
354
+ })
355
+ pq.write_table(
356
+ crosswalk_table, crosswalk_path, compression="snappy",
357
+ )
358
+
359
+ elapsed_xwalk = time.monotonic() - t1
360
+ n_pgids = len(crosswalk_table)
361
+ gdl_codes_mapped = len(
362
+ set(crosswalk_table.column("gdl_code").to_pylist())
363
+ )
364
+ logger.info(
365
+ "Crosswalk: %d pgids, %d GDL codes in %.1fs",
366
+ n_pgids, gdl_codes_mapped, elapsed_xwalk,
367
+ )
368
+
369
+ # Provenance — digest covers all indicator CSVs concatenated
370
+ content_digest = compute_content_digest(b"".join(all_csv_bytes))
371
+
372
+ previous = last_digest_for_version(
373
+ config.ledger_path, config.version
374
+ )
375
+ outcome = (
376
+ "unchanged" if previous == content_digest else "success"
377
+ )
378
+
379
+ gdl_col = table.column("GDLCODE").to_pylist()
380
+ n_regions = len(set(gdl_col))
381
+ year_col = table.column("Year").to_pylist()
382
+ min_year = int(min(year_col))
383
+ max_year = int(max(year_col))
384
+
385
+ append_ledger_entry(config.ledger_path, {
386
+ "dataset": DATASET_ID,
387
+ "version": config.version,
388
+ "n_rows": table.num_rows,
389
+ "n_variables": len(config.variables),
390
+ "n_regions": n_regions,
391
+ "year_range": [min_year, max_year],
392
+ "n_pgids_mapped": n_pgids,
393
+ "n_gdl_codes_mapped": gdl_codes_mapped,
394
+ "content_digest": content_digest,
395
+ "outcome": outcome,
396
+ "ledger_version": LEDGER_VERSION,
397
+ "digest_algorithm": DIGEST_SCHEME,
398
+ })
399
+
400
+ elapsed = time.monotonic() - t0
401
+ logger.info(
402
+ "SHDI %s: %d rows, %d regions, years %d–%d, "
403
+ "%d pgids mapped (%.1fs total, digest: %s)",
404
+ config.version,
405
+ table.num_rows, n_regions,
406
+ min_year, max_year,
407
+ n_pgids, elapsed,
408
+ content_digest,
409
+ )
410
+
411
+ return {
412
+ "dataset": DATASET_ID,
413
+ "version": config.version,
414
+ "outcome": outcome,
415
+ "content_digest": content_digest,
416
+ "n_rows": table.num_rows,
417
+ "n_regions": n_regions,
418
+ "n_pgids_mapped": n_pgids,
419
+ "path": str(output_path),
420
+ "crosswalk_path": str(crosswalk_path),
421
+ }
422
+
423
+
424
+ # ---- CSV parsing ----
425
+
426
+
427
+ def _parse_and_merge(
428
+ csv_list: list[bytes],
429
+ config: ShdiConfig,
430
+ ) -> pa.Table:
431
+ """Parse per-indicator CSVs and merge on ID columns.
432
+
433
+ Each CSV has ID columns + one indicator column. We parse each,
434
+ keep only ID + that indicator, then join them together.
435
+ """
436
+ if len(csv_list) != len(config.variables):
437
+ msg = (
438
+ f"Expected {len(config.variables)} CSVs, "
439
+ f"got {len(csv_list)}"
440
+ )
441
+ raise ValueError(msg)
442
+
443
+ id_cols = list(SHDI_ID_COLUMNS)
444
+ tables: list[pa.Table] = []
445
+
446
+ for csv_bytes, var in zip(csv_list, config.variables, strict=True):
447
+ needed = id_cols + [var]
448
+ convert_opts = pcsv.ConvertOptions(include_columns=needed)
449
+ try:
450
+ tbl = pcsv.read_csv(
451
+ pa.py_buffer(csv_bytes),
452
+ convert_options=convert_opts,
453
+ )
454
+ except (pa.ArrowInvalid, pa.ArrowKeyError) as exc:
455
+ msg = f"SHDI CSV missing required columns for {var}: {exc}"
456
+ logger.error(msg)
457
+ raise ValueError(msg) from exc
458
+ tables.append(tbl)
459
+
460
+ if tables[0].num_rows == 0:
461
+ return tables[0]
462
+
463
+ expected_rows = tables[0].num_rows
464
+ result = tables[0]
465
+ for i, tbl in enumerate(tables[1:], start=1):
466
+ result = result.join(tbl, keys=id_cols, join_type="inner")
467
+ if result.num_rows < expected_rows:
468
+ dropped = expected_rows - result.num_rows
469
+ var = config.variables[i]
470
+ msg = (
471
+ f"SHDI inner join lost {dropped} rows "
472
+ f"({dropped / expected_rows:.1%}) merging {var} — "
473
+ f"indicator coverage mismatch"
474
+ )
475
+ logger.error(msg)
476
+ raise ValueError(msg)
477
+
478
+ return result
479
+
480
+
481
+ # ---- Spatial join crosswalk ----
482
+
483
+
484
+ def _load_centroids(
485
+ centroid_path: Path,
486
+ ) -> list[tuple[int, float, float]]:
487
+ """Load PRIO-GRID centroids from shapefile.
488
+
489
+ Returns list of (gid, lon, lat) tuples.
490
+ """
491
+ if not centroid_path.exists():
492
+ msg = f"Centroid shapefile not found: {centroid_path}"
493
+ raise FileNotFoundError(msg)
494
+
495
+ centroids: list[tuple[int, float, float]] = []
496
+ with shp.Reader(str(centroid_path)) as sf:
497
+ fields = [f[0] for f in sf.fields[1:]]
498
+ gid_idx = fields.index("gid")
499
+ for sr in sf.iterShapeRecords():
500
+ gid = int(sr.record[gid_idx])
501
+ lon, lat = sr.shape.points[0]
502
+ centroids.append((gid, lon, lat))
503
+
504
+ logger.info("Loaded %d centroids", len(centroids))
505
+ return centroids
506
+
507
+
508
+ def _extract_shapefile(
509
+ shapefile_path: Path,
510
+ extract_dir: Path,
511
+ ) -> Path:
512
+ """Extract GDL shapefile ZIP and return path to .shp file."""
513
+ with zipfile.ZipFile(shapefile_path) as zf:
514
+ zf.extractall(extract_dir)
515
+
516
+ shp_files = list(extract_dir.rglob("*.shp"))
517
+ if not shp_files:
518
+ msg = (
519
+ f"No .shp found in {shapefile_path}. "
520
+ f"Contents: {list(extract_dir.rglob('*'))}"
521
+ )
522
+ raise FileNotFoundError(msg)
523
+
524
+ return shp_files[0]
525
+
526
+
527
+ def _build_crosswalk(
528
+ shapefile_path: Path,
529
+ centroid_path: Path,
530
+ ) -> list[tuple[int, str]]:
531
+ """Build GDL-code → pgid crosswalk via spatial join.
532
+
533
+ Joins PRIO-GRID centroids against GDL admin polygons using
534
+ STRtree spatial indexing.
535
+
536
+ Args:
537
+ shapefile_path: Path to GDL shapefiles ZIP.
538
+ centroid_path: Path to PRIO-GRID centroid shapefile.
539
+
540
+ Returns:
541
+ List of (gid, gdl_code) tuples.
542
+ """
543
+ centroids = _load_centroids(centroid_path)
544
+
545
+ extract_dir = shapefile_path.parent / "_gdl_shp_extract"
546
+ extract_dir.mkdir(parents=True, exist_ok=True)
547
+
548
+ if shapefile_path.suffix == ".zip":
549
+ shp_path = _extract_shapefile(shapefile_path, extract_dir)
550
+ else:
551
+ shp_path = shapefile_path
552
+
553
+ logger.info("Reading GDL shapefile %s ...", shp_path.name)
554
+ polygons = []
555
+ gdl_codes: list[str] = []
556
+
557
+ with shp.Reader(str(shp_path)) as sf:
558
+ dbf_fields = [f[0] for f in sf.fields[1:]]
559
+
560
+ gdl_field = _find_gdl_code_field(dbf_fields)
561
+ gdl_idx = dbf_fields.index(gdl_field)
562
+
563
+ for sr in sf.iterShapeRecords():
564
+ geo = sr.shape.__geo_interface__
565
+ if geo["type"] == "Null":
566
+ continue
567
+ polygons.append(shape(geo))
568
+ gdl_codes.append(str(sr.record[gdl_idx]))
569
+
570
+ logger.info(
571
+ "Loaded %d GDL polygons, building spatial index...",
572
+ len(polygons),
573
+ )
574
+
575
+ tree = STRtree(polygons)
576
+
577
+ result: list[tuple[int, str]] = []
578
+ n_matched = 0
579
+ n_unmatched = 0
580
+
581
+ t0 = time.monotonic()
582
+ for gid, lon, lat in centroids:
583
+ pt = Point(lon, lat)
584
+ indices = tree.query(pt, predicate="intersects")
585
+ if len(indices) > 0:
586
+ idx = int(indices[0])
587
+ result.append((gid, gdl_codes[idx]))
588
+ n_matched += 1
589
+ else:
590
+ n_unmatched += 1
591
+
592
+ elapsed = time.monotonic() - t0
593
+ logger.info(
594
+ "Spatial join: %d matched, %d unmatched (%.1fs)",
595
+ n_matched, n_unmatched, elapsed,
596
+ )
597
+
598
+ return result
599
+
600
+
601
+ _GDL_CODE_CANDIDATES = (
602
+ "GDLcode", "GDLCODE", "gdlcode", "GDL_Code", "gdl_code",
603
+ )
604
+
605
+
606
+ def _find_gdl_code_field(dbf_fields: list[str]) -> str:
607
+ """Find the GDL code field in shapefile attributes.
608
+
609
+ Tries known candidate names case-insensitively.
610
+ """
611
+ fields_lower = {f.lower(): f for f in dbf_fields}
612
+ for candidate in _GDL_CODE_CANDIDATES:
613
+ if candidate.lower() in fields_lower:
614
+ return fields_lower[candidate.lower()]
615
+
616
+ msg = (
617
+ f"No GDL code field found in shapefile. "
618
+ f"Tried: {_GDL_CODE_CANDIDATES}. "
619
+ f"Available: {dbf_fields}"
620
+ )
621
+ raise ValueError(msg)
622
+
623
+
624
+ # Auto-register
625
+ register_source("shdi", fetch_shdi)