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.
- datafactory_adapters/ARCHITECTURE.md +54 -0
- datafactory_adapters/__init__.py +38 -0
- datafactory_adapters/_conservation.py +95 -0
- datafactory_adapters/_reconciliation.py +92 -0
- datafactory_adapters/_validation.py +39 -0
- datafactory_adapters/feature_frame.py +25 -0
- datafactory_adapters/grid_from_feature_frame.py +89 -0
- datafactory_adapters/grid_to_country_month.py +169 -0
- datafactory_adapters/grid_to_dataframe.py +176 -0
- datafactory_compilation/ARCHITECTURE.md +63 -0
- datafactory_compilation/__init__.py +39 -0
- datafactory_compilation/aggregation.py +64 -0
- datafactory_compilation/compilation_config.py +97 -0
- datafactory_compilation/conservation.py +36 -0
- datafactory_compilation/grid_compilation.py +352 -0
- datafactory_compilation/output.py +85 -0
- datafactory_compilation/preflight.py +61 -0
- datafactory_compilation/pregridded_compilation.py +291 -0
- datafactory_consolidation/ARCHITECTURE.md +58 -0
- datafactory_consolidation/__init__.py +28 -0
- datafactory_consolidation/consolidation_result.py +27 -0
- datafactory_consolidation/consolidators/__init__.py +32 -0
- datafactory_consolidation/consolidators/acled.py +462 -0
- datafactory_consolidation/consolidators/ucdp.py +524 -0
- datafactory_consolidation/event_store.py +67 -0
- datafactory_consolidation/tagging.py +46 -0
- datafactory_harvester/ARCHITECTURE.md +103 -0
- datafactory_harvester/__init__.py +37 -0
- datafactory_harvester/event_validation.py +372 -0
- datafactory_harvester/harvest_runner.py +72 -0
- datafactory_harvester/pipeline_runner.py +125 -0
- datafactory_harvester/snapshot_storage.py +117 -0
- datafactory_harvester/sources/__init__.py +36 -0
- datafactory_harvester/sources/_ucdp_common.py +34 -0
- datafactory_harvester/sources/acled.py +743 -0
- datafactory_harvester/sources/gaul_admin.py +567 -0
- datafactory_harvester/sources/ghsbuilts.py +271 -0
- datafactory_harvester/sources/ghspop.py +267 -0
- datafactory_harvester/sources/priogrid_static.py +359 -0
- datafactory_harvester/sources/shdi.py +625 -0
- datafactory_harvester/sources/ucdp_annual.py +616 -0
- datafactory_harvester/sources/ucdp_candidate.py +419 -0
- datafactory_harvester/sources/ucdp_dot9.py +407 -0
- datafactory_harvester/sources/vdem.py +350 -0
- datafactory_harvester/validation.py +74 -0
- datafactory_http/__init__.py +10 -0
- datafactory_http/retry.py +102 -0
- datafactory_priogrid/ARCHITECTURE.md +62 -0
- datafactory_priogrid/__init__.py +51 -0
- datafactory_priogrid/cell_generator.py +137 -0
- datafactory_priogrid/grid_config.py +107 -0
- datafactory_priogrid/land_mask.py +62 -0
- datafactory_priogrid/parity_validation.py +176 -0
- datafactory_priogrid/shapefile_harvester.py +174 -0
- datafactory_priogrid/shapefile_reader.py +125 -0
- datafactory_priogrid/spatiotemporal.py +66 -0
- datafactory_priogrid/temporal_config.py +78 -0
- datafactory_priogrid/temporal_generator.py +65 -0
- datafactory_provenance/ARCHITECTURE.md +61 -0
- datafactory_provenance/__init__.py +81 -0
- datafactory_provenance/constants.py +3 -0
- datafactory_provenance/digests_and_ledgers.py +370 -0
- datafactory_provenance/health.py +310 -0
- datafactory_provenance/pipeline_lock.py +200 -0
- datafactory_provenance/registry.py +92 -0
- datafactory_provenance/skip.py +212 -0
- datafactory_provenance/source_registry.py +466 -0
- datafactory_query/ARCHITECTURE.md +60 -0
- datafactory_query/__init__.py +36 -0
- datafactory_query/africa_me_gaul_pgids.json +1 -0
- datafactory_query/africa_me_legacy_pgids.json +1 -0
- datafactory_query/backends_npy.py +90 -0
- datafactory_query/backends_zarr.py +259 -0
- datafactory_query/coverage.py +64 -0
- datafactory_query/dataset.py +263 -0
- datafactory_query/defaults.py +101 -0
- datafactory_query/land_gaul_pgids.json +1 -0
- datafactory_query/land_pgids.json +1 -0
- datafactory_query/output_format.py +52 -0
- datafactory_query/regions.py +293 -0
- datafactory_query/temporal.py +115 -0
- datafactory_viewpoint/ARCHITECTURE.md +68 -0
- datafactory_viewpoint/__init__.py +33 -0
- datafactory_viewpoint/builders/__init__.py +32 -0
- datafactory_viewpoint/builders/acled_v1.py +213 -0
- datafactory_viewpoint/builders/ghsbuilts_v1.py +351 -0
- datafactory_viewpoint/builders/ghspop_v1.py +471 -0
- datafactory_viewpoint/builders/shdi_v1.py +389 -0
- datafactory_viewpoint/builders/ucdp_v1.py +437 -0
- datafactory_viewpoint/builders/vdem_v1.py +419 -0
- datafactory_viewpoint/profiles.py +169 -0
- datafactory_viewpoint/raster_io.py +49 -0
- datafactory_viewpoint/spatial_distribution.py +203 -0
- datafactory_viewpoint/spatial_weights.py +207 -0
- datafactory_viewpoint/survivorship.py +108 -0
- datafactory_viewpoint/temporal.py +111 -0
- datafactory_viewpoint/temporal_distribution.py +295 -0
- datafactory_viewpoint/viewpoint_config.py +124 -0
- datafactory_viewpoint/viewpoint_result.py +33 -0
- views_datafactory-1.9.0.dist-info/METADATA +528 -0
- views_datafactory-1.9.0.dist-info/RECORD +103 -0
- views_datafactory-1.9.0.dist-info/WHEEL +4 -0
- views_datafactory-1.9.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,567 @@
|
|
|
1
|
+
"""GAUL 2024 administrative boundary harvester.
|
|
2
|
+
|
|
3
|
+
Downloads GAUL shapefiles from FAO and performs a spatial join
|
|
4
|
+
against PRIO-GRID cell centroids to produce a lookup table:
|
|
5
|
+
pgid → (gaul0_code, gaul0_name, gaul1_code, gaul1_name,
|
|
6
|
+
gaul2_code, gaul2_name, iso3_code)
|
|
7
|
+
|
|
8
|
+
Uses pyshp (already a dependency) to read shapefiles and shapely
|
|
9
|
+
STRtree for the spatial join. No geopandas.
|
|
10
|
+
|
|
11
|
+
Output: one Parquet file per admin variable (gaul0_code.parquet,
|
|
12
|
+
gaul1_code.parquet, etc.) with columns (gid, value), matching
|
|
13
|
+
the priogrid_static pattern.
|
|
14
|
+
|
|
15
|
+
Source: FAO GAUL 2024 (CC-BY-4.0)
|
|
16
|
+
https://www.fao.org/agroinformatics/training-and-resources/
|
|
17
|
+
data-sets/data-set-detail/global-gaul-new-2024-release/en
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import io
|
|
23
|
+
import json
|
|
24
|
+
import logging
|
|
25
|
+
import time
|
|
26
|
+
import zipfile
|
|
27
|
+
from dataclasses import dataclass, field
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
|
|
30
|
+
import pyarrow as pa
|
|
31
|
+
import pyarrow.parquet as pq
|
|
32
|
+
import shapefile as shp
|
|
33
|
+
from shapely.geometry import Point, shape
|
|
34
|
+
from shapely.strtree import STRtree
|
|
35
|
+
|
|
36
|
+
from datafactory_harvester.sources import register_source
|
|
37
|
+
from datafactory_harvester.validation import validate_positive_int
|
|
38
|
+
from datafactory_http import request_with_retry
|
|
39
|
+
from datafactory_provenance import (
|
|
40
|
+
DIGEST_SCHEME,
|
|
41
|
+
LEDGER_VERSION,
|
|
42
|
+
append_ledger_entry,
|
|
43
|
+
compute_content_digest,
|
|
44
|
+
last_digest_for_version,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
logger = logging.getLogger(__name__)
|
|
48
|
+
|
|
49
|
+
DATASET_ID = "gaul_admin"
|
|
50
|
+
|
|
51
|
+
# ---- FAO download URLs (CC-BY-4.0) ----
|
|
52
|
+
|
|
53
|
+
GAUL_L1_URL = (
|
|
54
|
+
"https://storage.googleapis.com/fao-maps-catalog-data"
|
|
55
|
+
"/boundaries/GAUL_2024_L1.zip"
|
|
56
|
+
)
|
|
57
|
+
GAUL_L2_URL = (
|
|
58
|
+
"https://storage.googleapis.com/fao-maps-catalog-data"
|
|
59
|
+
"/boundaries/GAUL_2024_L2.zip"
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
# L2 contains the full admin hierarchy so we use it as the
|
|
63
|
+
# primary join. L1 is fallback for centroids not matched by L2.
|
|
64
|
+
# GAUL 2024 DBF fields: gaul0_code, gaul0_name, gaul1_code,
|
|
65
|
+
# gaul1_name, gaul2_code, gaul2_name, iso3_code, map_code,
|
|
66
|
+
# continent, disp_en
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# ---- Config ----
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True)
|
|
73
|
+
class GaulAdminConfig:
|
|
74
|
+
"""Configuration for harvesting GAUL admin boundaries.
|
|
75
|
+
|
|
76
|
+
Downloads GAUL 2024 shapefiles from FAO, performs spatial
|
|
77
|
+
join against PRIO-GRID centroids, and stores per-variable
|
|
78
|
+
Parquet files (gid, value) for grid assembly.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
gaul_l1_url: str = GAUL_L1_URL
|
|
82
|
+
gaul_l2_url: str = GAUL_L2_URL
|
|
83
|
+
centroid_shapefile: Path = Path(
|
|
84
|
+
"data/raw/priogrid/shapefile/priogrid_centroid.shp"
|
|
85
|
+
)
|
|
86
|
+
data_dir: Path = Path("data/raw/gaul_admin")
|
|
87
|
+
cache_dir: Path = Path("data/raw/gaul_admin/shapefiles")
|
|
88
|
+
ledger_path: Path = Path(
|
|
89
|
+
"provenance/gaul_admin/ingestion_ledger.jsonl"
|
|
90
|
+
)
|
|
91
|
+
timeout: int = 300 # zipped shapefiles ~50 MB each (ADR-018)
|
|
92
|
+
variables: tuple[str, ...] | None = field(default=None)
|
|
93
|
+
|
|
94
|
+
def __post_init__(self) -> None:
|
|
95
|
+
validate_positive_int(self.timeout, "timeout")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# ---- Shapefile download ----
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _download_shapefile_zip(
|
|
102
|
+
url: str,
|
|
103
|
+
cache_dir: Path,
|
|
104
|
+
*,
|
|
105
|
+
timeout: int = 300,
|
|
106
|
+
) -> Path:
|
|
107
|
+
"""Download and extract a zipped shapefile.
|
|
108
|
+
|
|
109
|
+
Local-first: skips download if .shp already exists.
|
|
110
|
+
Returns path to the extracted .shp file.
|
|
111
|
+
"""
|
|
112
|
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
|
113
|
+
|
|
114
|
+
# Check if already extracted
|
|
115
|
+
existing = list(cache_dir.glob("**/*.shp"))
|
|
116
|
+
shp_candidates = [
|
|
117
|
+
p for p in existing
|
|
118
|
+
if p.stem in url.split("/")[-1].replace(".zip", "")
|
|
119
|
+
]
|
|
120
|
+
if shp_candidates:
|
|
121
|
+
logger.info("Shapefile cached: %s", shp_candidates[0])
|
|
122
|
+
return shp_candidates[0]
|
|
123
|
+
|
|
124
|
+
# Download
|
|
125
|
+
logger.info("Downloading %s ...", url)
|
|
126
|
+
t0 = time.monotonic()
|
|
127
|
+
resp = request_with_retry(url, timeout=timeout)
|
|
128
|
+
|
|
129
|
+
# Read into memory and extract
|
|
130
|
+
content = resp.content
|
|
131
|
+
elapsed = time.monotonic() - t0
|
|
132
|
+
size_mb = len(content) / 1e6
|
|
133
|
+
logger.info(
|
|
134
|
+
"Downloaded %.0f MB in %.1fs", size_mb, elapsed
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
with zipfile.ZipFile(io.BytesIO(content)) as zf:
|
|
138
|
+
zf.extractall(cache_dir)
|
|
139
|
+
logger.info(
|
|
140
|
+
"Extracted %d files to %s",
|
|
141
|
+
len(zf.namelist()), cache_dir,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
# Find the .shp
|
|
145
|
+
extracted = list(cache_dir.glob("**/*.shp"))
|
|
146
|
+
if not extracted:
|
|
147
|
+
msg = f"No .shp found after extracting {url}"
|
|
148
|
+
raise FileNotFoundError(msg)
|
|
149
|
+
|
|
150
|
+
return extracted[0]
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
# ---- Centroid loading ----
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _load_centroids(
|
|
157
|
+
centroid_path: Path,
|
|
158
|
+
) -> list[tuple[int, float, float]]:
|
|
159
|
+
"""Load PRIO-GRID centroids from shapefile.
|
|
160
|
+
|
|
161
|
+
Returns list of (gid, lon, lat) tuples.
|
|
162
|
+
"""
|
|
163
|
+
if not centroid_path.exists():
|
|
164
|
+
msg = f"Centroid shapefile not found: {centroid_path}"
|
|
165
|
+
raise FileNotFoundError(msg)
|
|
166
|
+
|
|
167
|
+
centroids: list[tuple[int, float, float]] = []
|
|
168
|
+
with shp.Reader(str(centroid_path)) as sf:
|
|
169
|
+
fields = [f[0] for f in sf.fields[1:]]
|
|
170
|
+
gid_idx = fields.index("gid")
|
|
171
|
+
for sr in sf.iterShapeRecords():
|
|
172
|
+
gid = int(sr.record[gid_idx])
|
|
173
|
+
lon, lat = sr.shape.points[0]
|
|
174
|
+
centroids.append((gid, lon, lat))
|
|
175
|
+
|
|
176
|
+
logger.info("Loaded %d centroids", len(centroids))
|
|
177
|
+
return centroids
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
# ---- Spatial join ----
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _spatial_join(
|
|
184
|
+
centroids: list[tuple[int, float, float]],
|
|
185
|
+
shp_path: Path,
|
|
186
|
+
field_names: list[str],
|
|
187
|
+
) -> dict[int, dict[str, object]]:
|
|
188
|
+
"""Join centroids against admin polygons.
|
|
189
|
+
|
|
190
|
+
Uses shapely STRtree for O(log n) spatial indexing.
|
|
191
|
+
|
|
192
|
+
Args:
|
|
193
|
+
centroids: List of (gid, lon, lat).
|
|
194
|
+
shp_path: Path to admin shapefile.
|
|
195
|
+
field_names: DBF field names to extract per match.
|
|
196
|
+
|
|
197
|
+
Returns:
|
|
198
|
+
Dict mapping gid → {field_name: value, ...}.
|
|
199
|
+
"""
|
|
200
|
+
# Read admin polygons
|
|
201
|
+
logger.info("Reading %s ...", shp_path.name)
|
|
202
|
+
polygons = []
|
|
203
|
+
records = []
|
|
204
|
+
with shp.Reader(str(shp_path)) as sf:
|
|
205
|
+
dbf_fields = [f[0] for f in sf.fields[1:]]
|
|
206
|
+
field_indices = []
|
|
207
|
+
for fn in field_names:
|
|
208
|
+
if fn not in dbf_fields:
|
|
209
|
+
msg = (
|
|
210
|
+
f"Field {fn!r} not in shapefile. "
|
|
211
|
+
f"Available: {dbf_fields}"
|
|
212
|
+
)
|
|
213
|
+
raise ValueError(msg)
|
|
214
|
+
field_indices.append(dbf_fields.index(fn))
|
|
215
|
+
|
|
216
|
+
for sr in sf.iterShapeRecords():
|
|
217
|
+
geo = sr.shape.__geo_interface__
|
|
218
|
+
if geo["type"] == "Null":
|
|
219
|
+
continue
|
|
220
|
+
polygons.append(shape(geo))
|
|
221
|
+
records.append(
|
|
222
|
+
{fn: sr.record[idx]
|
|
223
|
+
for fn, idx in zip(
|
|
224
|
+
field_names, field_indices, strict=True
|
|
225
|
+
)}
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
logger.info(
|
|
229
|
+
"Loaded %d admin polygons, building index...",
|
|
230
|
+
len(polygons),
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
# Build spatial index
|
|
234
|
+
tree = STRtree(polygons)
|
|
235
|
+
|
|
236
|
+
# Join each centroid
|
|
237
|
+
result: dict[int, dict[str, object]] = {}
|
|
238
|
+
n_matched = 0
|
|
239
|
+
n_unmatched = 0
|
|
240
|
+
|
|
241
|
+
t0 = time.monotonic()
|
|
242
|
+
for gid, lon, lat in centroids:
|
|
243
|
+
pt = Point(lon, lat)
|
|
244
|
+
indices = tree.query(pt, predicate="intersects")
|
|
245
|
+
if len(indices) > 0:
|
|
246
|
+
# Take first match (if multiple, nearest is fine
|
|
247
|
+
# for 0.5° cells — admin boundaries don't overlap
|
|
248
|
+
# within a single level)
|
|
249
|
+
idx = int(indices[0])
|
|
250
|
+
result[gid] = records[idx]
|
|
251
|
+
n_matched += 1
|
|
252
|
+
else:
|
|
253
|
+
n_unmatched += 1
|
|
254
|
+
|
|
255
|
+
elapsed = time.monotonic() - t0
|
|
256
|
+
logger.info(
|
|
257
|
+
"Spatial join: %d matched, %d unmatched (%.1fs)",
|
|
258
|
+
n_matched, n_unmatched, elapsed,
|
|
259
|
+
)
|
|
260
|
+
return result
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
# ---- Variable extraction ----
|
|
264
|
+
|
|
265
|
+
# Each "variable" becomes a Parquet file (gid, value) matching
|
|
266
|
+
# the priogrid_static pattern.
|
|
267
|
+
|
|
268
|
+
ADMIN_VARIABLES: dict[str, dict[str, str]] = {
|
|
269
|
+
"gaul0_code": {
|
|
270
|
+
"level": "l2",
|
|
271
|
+
"field": "gaul0_code",
|
|
272
|
+
"display": "GAUL country code",
|
|
273
|
+
},
|
|
274
|
+
"gaul0_name": {
|
|
275
|
+
"level": "l2",
|
|
276
|
+
"field": "gaul0_name",
|
|
277
|
+
"display": "GAUL country name",
|
|
278
|
+
},
|
|
279
|
+
"gaul1_code": {
|
|
280
|
+
"level": "l2",
|
|
281
|
+
"field": "gaul1_code",
|
|
282
|
+
"display": "GAUL admin-1 code",
|
|
283
|
+
},
|
|
284
|
+
"gaul1_name": {
|
|
285
|
+
"level": "l2",
|
|
286
|
+
"field": "gaul1_name",
|
|
287
|
+
"display": "GAUL admin-1 name",
|
|
288
|
+
},
|
|
289
|
+
"gaul2_code": {
|
|
290
|
+
"level": "l2",
|
|
291
|
+
"field": "gaul2_code",
|
|
292
|
+
"display": "GAUL admin-2 code",
|
|
293
|
+
},
|
|
294
|
+
"gaul2_name": {
|
|
295
|
+
"level": "l2",
|
|
296
|
+
"field": "gaul2_name",
|
|
297
|
+
"display": "GAUL admin-2 name",
|
|
298
|
+
},
|
|
299
|
+
"iso3_code": {
|
|
300
|
+
"level": "l2",
|
|
301
|
+
"field": "iso3_code",
|
|
302
|
+
"display": "ISO 3166-1 alpha-3 country code",
|
|
303
|
+
},
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
# L1 fallback fields — used for centroids not matched by L2
|
|
307
|
+
_L1_FALLBACK_FIELDS: dict[str, str] = {
|
|
308
|
+
"gaul0_code": "gaul0_code",
|
|
309
|
+
"gaul0_name": "gaul0_name",
|
|
310
|
+
"gaul1_code": "gaul1_code",
|
|
311
|
+
"gaul1_name": "gaul1_name",
|
|
312
|
+
"iso3_code": "iso3_code",
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _write_variable(
|
|
317
|
+
var_name: str,
|
|
318
|
+
join_result: dict[int, dict[str, object]],
|
|
319
|
+
field_name: str,
|
|
320
|
+
config: GaulAdminConfig,
|
|
321
|
+
*,
|
|
322
|
+
is_numeric: bool,
|
|
323
|
+
display_name: str,
|
|
324
|
+
fallback: dict[int, dict[str, object]] | None = None,
|
|
325
|
+
fallback_field: str | None = None,
|
|
326
|
+
) -> dict:
|
|
327
|
+
"""Write one admin variable as Parquet (gid, value).
|
|
328
|
+
|
|
329
|
+
Returns a result dict matching the priogrid_static pattern.
|
|
330
|
+
"""
|
|
331
|
+
snap_path = config.data_dir / f"{var_name}.parquet"
|
|
332
|
+
|
|
333
|
+
gids: list[int] = []
|
|
334
|
+
values_int: list[int] = []
|
|
335
|
+
values_str: list[str] = []
|
|
336
|
+
n_from_fallback = 0
|
|
337
|
+
|
|
338
|
+
all_gids = sorted(
|
|
339
|
+
set(join_result.keys())
|
|
340
|
+
| (set(fallback.keys()) if fallback else set())
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
for gid in all_gids:
|
|
344
|
+
rec = join_result.get(gid)
|
|
345
|
+
val = rec[field_name] if rec and field_name in rec else None
|
|
346
|
+
|
|
347
|
+
# Try fallback if primary didn't match
|
|
348
|
+
if val is None and fallback and fallback_field:
|
|
349
|
+
fb_rec = fallback.get(gid)
|
|
350
|
+
if fb_rec and fallback_field in fb_rec:
|
|
351
|
+
val = fb_rec[fallback_field]
|
|
352
|
+
n_from_fallback += 1
|
|
353
|
+
|
|
354
|
+
if val is None:
|
|
355
|
+
continue
|
|
356
|
+
|
|
357
|
+
gids.append(gid)
|
|
358
|
+
if is_numeric:
|
|
359
|
+
values_int.append(int(val)) # type: ignore[call-overload]
|
|
360
|
+
else:
|
|
361
|
+
values_str.append(str(val))
|
|
362
|
+
|
|
363
|
+
# Build table
|
|
364
|
+
if is_numeric:
|
|
365
|
+
table = pa.table({
|
|
366
|
+
"gid": pa.array(gids, type=pa.int32()),
|
|
367
|
+
"value": pa.array(values_int, type=pa.int32()),
|
|
368
|
+
})
|
|
369
|
+
else:
|
|
370
|
+
table = pa.table({
|
|
371
|
+
"gid": pa.array(gids, type=pa.int32()),
|
|
372
|
+
"value": pa.array(values_str, type=pa.string()),
|
|
373
|
+
})
|
|
374
|
+
|
|
375
|
+
# Digest
|
|
376
|
+
content = values_int if is_numeric else values_str
|
|
377
|
+
content_bytes = json.dumps(
|
|
378
|
+
list(zip(gids, content, strict=True)),
|
|
379
|
+
sort_keys=True,
|
|
380
|
+
).encode()
|
|
381
|
+
content_digest = compute_content_digest(content_bytes)
|
|
382
|
+
|
|
383
|
+
# Check if unchanged
|
|
384
|
+
previous = last_digest_for_version(
|
|
385
|
+
config.ledger_path, var_name
|
|
386
|
+
)
|
|
387
|
+
if previous == content_digest and snap_path.exists():
|
|
388
|
+
logger.info(
|
|
389
|
+
"%s unchanged (digest: %s)", var_name, content_digest
|
|
390
|
+
)
|
|
391
|
+
append_ledger_entry(config.ledger_path, {
|
|
392
|
+
"dataset": DATASET_ID,
|
|
393
|
+
"version": var_name,
|
|
394
|
+
"n_cells": len(gids),
|
|
395
|
+
"content_digest": content_digest,
|
|
396
|
+
"outcome": "unchanged",
|
|
397
|
+
"ledger_version": LEDGER_VERSION,
|
|
398
|
+
"digest_algorithm": DIGEST_SCHEME,
|
|
399
|
+
})
|
|
400
|
+
return {
|
|
401
|
+
"variable": var_name,
|
|
402
|
+
"outcome": "unchanged",
|
|
403
|
+
"digest": content_digest,
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
# Write
|
|
407
|
+
snap_path.parent.mkdir(parents=True, exist_ok=True)
|
|
408
|
+
pq.write_table(table, snap_path, compression="snappy")
|
|
409
|
+
|
|
410
|
+
# Provenance
|
|
411
|
+
append_ledger_entry(config.ledger_path, {
|
|
412
|
+
"dataset": DATASET_ID,
|
|
413
|
+
"version": var_name,
|
|
414
|
+
"n_cells": len(gids),
|
|
415
|
+
"n_from_fallback": n_from_fallback,
|
|
416
|
+
"content_digest": content_digest,
|
|
417
|
+
"variable_metadata": {
|
|
418
|
+
"display_name": display_name,
|
|
419
|
+
"category": "Administrative boundaries",
|
|
420
|
+
"source": "FAO GAUL 2024",
|
|
421
|
+
"license": "CC-BY-4.0",
|
|
422
|
+
},
|
|
423
|
+
"outcome": "success",
|
|
424
|
+
"ledger_version": LEDGER_VERSION,
|
|
425
|
+
"digest_algorithm": DIGEST_SCHEME,
|
|
426
|
+
})
|
|
427
|
+
|
|
428
|
+
logger.info(
|
|
429
|
+
"%s: %d cells, %d from L1 fallback, digest %s",
|
|
430
|
+
var_name, len(gids), n_from_fallback, content_digest,
|
|
431
|
+
)
|
|
432
|
+
return {
|
|
433
|
+
"variable": var_name,
|
|
434
|
+
"outcome": "success",
|
|
435
|
+
"n_cells": len(gids),
|
|
436
|
+
"n_from_fallback": n_from_fallback,
|
|
437
|
+
"digest": content_digest,
|
|
438
|
+
"path": str(snap_path),
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
# ---- Orchestrator ----
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def fetch_gaul_admin(
|
|
446
|
+
config: GaulAdminConfig | None = None,
|
|
447
|
+
*,
|
|
448
|
+
force_refresh: bool = False,
|
|
449
|
+
) -> list[dict]:
|
|
450
|
+
"""Fetch GAUL admin boundaries and join to PRIO-GRID.
|
|
451
|
+
|
|
452
|
+
1. Download GAUL L2 and L1 shapefiles (cached locally)
|
|
453
|
+
2. Load PRIO-GRID centroids
|
|
454
|
+
3. Spatial join centroids against L2, then L1 as fallback
|
|
455
|
+
4. Write per-variable Parquet files (gid, value)
|
|
456
|
+
|
|
457
|
+
Returns list of per-variable result dicts.
|
|
458
|
+
"""
|
|
459
|
+
if config is None:
|
|
460
|
+
config = GaulAdminConfig()
|
|
461
|
+
|
|
462
|
+
# Check for cached results (all variables present)
|
|
463
|
+
if not force_refresh and config.variables is None:
|
|
464
|
+
all_cached = all(
|
|
465
|
+
(config.data_dir / f"{v}.parquet").exists()
|
|
466
|
+
and last_digest_for_version(
|
|
467
|
+
config.ledger_path, v
|
|
468
|
+
) is not None
|
|
469
|
+
for v in ADMIN_VARIABLES
|
|
470
|
+
)
|
|
471
|
+
if all_cached:
|
|
472
|
+
logger.info("All GAUL variables cached")
|
|
473
|
+
return [
|
|
474
|
+
{
|
|
475
|
+
"variable": v,
|
|
476
|
+
"outcome": "cached",
|
|
477
|
+
"digest": last_digest_for_version(
|
|
478
|
+
config.ledger_path, v
|
|
479
|
+
),
|
|
480
|
+
}
|
|
481
|
+
for v in ADMIN_VARIABLES
|
|
482
|
+
]
|
|
483
|
+
|
|
484
|
+
# Download shapefiles
|
|
485
|
+
l2_shp = _download_shapefile_zip(
|
|
486
|
+
config.gaul_l2_url,
|
|
487
|
+
config.cache_dir / "GAUL_2024_L2",
|
|
488
|
+
timeout=config.timeout,
|
|
489
|
+
)
|
|
490
|
+
l1_shp = _download_shapefile_zip(
|
|
491
|
+
config.gaul_l1_url,
|
|
492
|
+
config.cache_dir / "GAUL_2024_L1",
|
|
493
|
+
timeout=config.timeout,
|
|
494
|
+
)
|
|
495
|
+
|
|
496
|
+
# Load centroids
|
|
497
|
+
centroids = _load_centroids(config.centroid_shapefile)
|
|
498
|
+
|
|
499
|
+
# Spatial join: L2 (primary)
|
|
500
|
+
l2_fields = sorted({
|
|
501
|
+
v["field"] for v in ADMIN_VARIABLES.values()
|
|
502
|
+
if v["level"] == "l2"
|
|
503
|
+
})
|
|
504
|
+
logger.info("Spatial join against L2 (%s)...", l2_fields)
|
|
505
|
+
l2_join = _spatial_join(centroids, l2_shp, l2_fields)
|
|
506
|
+
|
|
507
|
+
# Spatial join: L1 (fallback for unmatched centroids)
|
|
508
|
+
l1_fields = sorted(set(_L1_FALLBACK_FIELDS.values()))
|
|
509
|
+
logger.info("Spatial join against L1 (%s)...", l1_fields)
|
|
510
|
+
l1_join = _spatial_join(centroids, l1_shp, l1_fields)
|
|
511
|
+
|
|
512
|
+
# Filter to requested variables
|
|
513
|
+
variables = ADMIN_VARIABLES
|
|
514
|
+
if config.variables is not None:
|
|
515
|
+
requested = set(config.variables)
|
|
516
|
+
variables = {
|
|
517
|
+
k: v for k, v in ADMIN_VARIABLES.items()
|
|
518
|
+
if k in requested
|
|
519
|
+
}
|
|
520
|
+
missing = requested - set(variables.keys())
|
|
521
|
+
if missing:
|
|
522
|
+
logger.warning(
|
|
523
|
+
"Unknown variables: %s", sorted(missing)
|
|
524
|
+
)
|
|
525
|
+
|
|
526
|
+
# Write each variable
|
|
527
|
+
results: list[dict] = []
|
|
528
|
+
for var_name, var_meta in variables.items():
|
|
529
|
+
is_numeric = (
|
|
530
|
+
var_name.endswith("_code")
|
|
531
|
+
and not var_name.startswith("iso")
|
|
532
|
+
)
|
|
533
|
+
fb_field = _L1_FALLBACK_FIELDS.get(var_name)
|
|
534
|
+
try:
|
|
535
|
+
result = _write_variable(
|
|
536
|
+
var_name,
|
|
537
|
+
l2_join,
|
|
538
|
+
var_meta["field"],
|
|
539
|
+
config,
|
|
540
|
+
is_numeric=is_numeric,
|
|
541
|
+
display_name=var_meta["display"],
|
|
542
|
+
fallback=l1_join if fb_field else None,
|
|
543
|
+
fallback_field=fb_field,
|
|
544
|
+
)
|
|
545
|
+
results.append(result)
|
|
546
|
+
except Exception as exc:
|
|
547
|
+
logger.error(
|
|
548
|
+
"Failed to write %s: %s", var_name, exc
|
|
549
|
+
)
|
|
550
|
+
append_ledger_entry(config.ledger_path, {
|
|
551
|
+
"dataset": DATASET_ID,
|
|
552
|
+
"version": var_name,
|
|
553
|
+
"outcome": "failed",
|
|
554
|
+
"errors": [str(exc)],
|
|
555
|
+
"ledger_version": LEDGER_VERSION,
|
|
556
|
+
})
|
|
557
|
+
results.append({
|
|
558
|
+
"variable": var_name,
|
|
559
|
+
"outcome": "failed",
|
|
560
|
+
"errors": [str(exc)],
|
|
561
|
+
})
|
|
562
|
+
|
|
563
|
+
return results
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
# Auto-register
|
|
567
|
+
register_source("gaul_admin", fetch_gaul_admin)
|