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,359 @@
1
+ """PRIO-GRID static features harvester.
2
+
3
+ Fetches static variables (terrain, resources, land cover) from the
4
+ PRIO-GRID 2.0 API (https://grid.prio.org/api). These are frozen
5
+ datasets (2009-2015 vintages) covering 64,818 land cells.
6
+
7
+ Each variable is stored as a separate Parquet file with columns
8
+ (gid, value). Provenance is tracked per variable.
9
+
10
+ This is the second data source in the datafactory (after UCDP).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import logging
17
+ import time
18
+ from dataclasses import dataclass, field
19
+ from pathlib import Path
20
+
21
+ import pyarrow as pa
22
+ import pyarrow.parquet as pq
23
+ import requests
24
+
25
+ from datafactory_harvester.snapshot_storage import archive_snapshot
26
+ from datafactory_harvester.sources import register_source
27
+ from datafactory_harvester.validation import validate_positive_int
28
+ from datafactory_provenance import (
29
+ DIGEST_SCHEME,
30
+ LEDGER_VERSION,
31
+ append_ledger_entry,
32
+ compute_content_digest,
33
+ last_digest_for_version,
34
+ )
35
+
36
+ logger = logging.getLogger(__name__)
37
+
38
+ DATASET_ID = "priogrid_static"
39
+ PRIOGRID_API_URL = "https://grid.prio.org/api"
40
+
41
+ # ---- Boundary declarations (ADR-009) ----
42
+ REQUIRED_CELL_FIELDS: set[str] = {"gid", "value"}
43
+
44
+
45
+ # ---- Config ----
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class PriogridStaticConfig:
50
+ """Configuration for fetching PRIO-GRID static features.
51
+
52
+ Static variables are frozen snapshots (terrain, resources,
53
+ land cover). They change only when PRIO releases a new
54
+ version of the grid, which is rare.
55
+ """
56
+
57
+ api_url: str = PRIOGRID_API_URL
58
+ data_dir: Path = Path("data/raw/priogrid_static")
59
+ ledger_path: Path = Path(
60
+ "provenance/priogrid_static/ingestion_ledger.jsonl"
61
+ )
62
+ timeout: int = 60 # per-variable JSON ~1 MB (ADR-018)
63
+ variables: tuple[str, ...] | None = field(default=None)
64
+
65
+ def __post_init__(self) -> None:
66
+ validate_positive_int(self.timeout, "timeout")
67
+
68
+
69
+ # ---- Helpers ----
70
+
71
+
72
+ def _discover_static_variables(
73
+ api_url: str, timeout: int
74
+ ) -> list[dict]:
75
+ """Fetch the variable catalog and return static variables."""
76
+ resp = requests.get(
77
+ f"{api_url}/variables", timeout=timeout
78
+ )
79
+ resp.raise_for_status()
80
+ all_vars = resp.json()
81
+ return [v for v in all_vars if v.get("type") == "static"]
82
+
83
+
84
+ def _snapshot_path(
85
+ config: PriogridStaticConfig, variable_name: str
86
+ ) -> Path:
87
+ """Build the Parquet snapshot path for a variable."""
88
+ return config.data_dir / f"{variable_name}.parquet"
89
+
90
+
91
+ def _fetch_variable(
92
+ config: PriogridStaticConfig,
93
+ variable: dict,
94
+ *,
95
+ force_refresh: bool = False,
96
+ ) -> dict:
97
+ """Fetch a single static variable.
98
+
99
+ Local-first: if Parquet exists and ledger has digest, skip.
100
+
101
+ Returns a result dict with variable name, outcome, and
102
+ cell count.
103
+ """
104
+ name = variable["name"]
105
+ snap_path = _snapshot_path(config, name)
106
+
107
+ # Local-first skip
108
+ if not force_refresh and snap_path.exists():
109
+ previous = last_digest_for_version(
110
+ config.ledger_path, name
111
+ )
112
+ if previous is not None:
113
+ logger.info(
114
+ "Variable %s already on disk (digest: %s)",
115
+ name, previous,
116
+ )
117
+ return {
118
+ "variable": name,
119
+ "outcome": "cached",
120
+ "digest": previous,
121
+ }
122
+
123
+ # Fetch from API
124
+ t0 = time.monotonic()
125
+ resp = requests.get(
126
+ f"{config.api_url}/data/{name}",
127
+ timeout=config.timeout,
128
+ )
129
+ resp.raise_for_status()
130
+ data = resp.json()
131
+ fetch_duration = time.monotonic() - t0
132
+
133
+ cells = data.get("cells", [])
134
+ if not cells:
135
+ err_msg = f"Variable {name} returned 0 cells"
136
+ logger.error(err_msg)
137
+ append_ledger_entry(config.ledger_path, {
138
+ "dataset": DATASET_ID,
139
+ "version": name,
140
+ "n_cells": 0,
141
+ "outcome": "failed",
142
+ "errors": [err_msg],
143
+ "ledger_version": LEDGER_VERSION,
144
+ "digest_algorithm": DIGEST_SCHEME,
145
+ })
146
+ return {
147
+ "variable": name,
148
+ "outcome": "failed",
149
+ "errors": [err_msg],
150
+ }
151
+
152
+ # Validate required fields on first cell
153
+ first = cells[0]
154
+ missing = REQUIRED_CELL_FIELDS - set(first.keys())
155
+ if missing:
156
+ err_msg = (
157
+ f"Variable {name}: cells missing fields "
158
+ f"{sorted(missing)}"
159
+ )
160
+ logger.error(err_msg)
161
+ return {
162
+ "variable": name,
163
+ "outcome": "failed",
164
+ "errors": [err_msg],
165
+ }
166
+
167
+ # Type validation (warnings, not errors)
168
+ warnings: list[str] = []
169
+ n_type_errors = 0
170
+ for c in cells:
171
+ if not isinstance(c.get("gid"), (int, float)):
172
+ n_type_errors += 1
173
+ if not isinstance(c.get("value"), (int, float)):
174
+ n_type_errors += 1
175
+ if n_type_errors > 0:
176
+ warnings.append(
177
+ f"{n_type_errors} type violations in "
178
+ f"{len(cells)} cells"
179
+ )
180
+
181
+ # Check gid uniqueness
182
+ gid_list = [c["gid"] for c in cells]
183
+ unique_gids = set(gid_list)
184
+ if len(unique_gids) != len(gid_list):
185
+ n_dupes = len(gid_list) - len(unique_gids)
186
+ warnings.append(
187
+ f"Duplicate gids: {n_dupes} duplicates "
188
+ f"in {len(gid_list)} cells"
189
+ )
190
+
191
+ # Build Parquet table
192
+ gids = gid_list
193
+ values = [c["value"] for c in cells]
194
+ table = pa.table({
195
+ "gid": pa.array(gids, type=pa.int32()),
196
+ "value": pa.array(values, type=pa.float64()),
197
+ })
198
+
199
+ # Compute digest
200
+ content_bytes = json.dumps(
201
+ sorted((c["gid"], c["value"]) for c in cells),
202
+ sort_keys=True,
203
+ ).encode()
204
+ content_digest = compute_content_digest(content_bytes)
205
+
206
+ # Check if unchanged
207
+ previous = last_digest_for_version(
208
+ config.ledger_path, name
209
+ )
210
+ if previous == content_digest and not force_refresh and snap_path.exists():
211
+ logger.info(
212
+ "Variable %s unchanged (digest: %s)",
213
+ name, content_digest,
214
+ )
215
+ append_ledger_entry(config.ledger_path, {
216
+ "dataset": DATASET_ID,
217
+ "version": name,
218
+ "n_cells": len(cells),
219
+ "content_digest": content_digest,
220
+ "warnings": warnings,
221
+ "outcome": "unchanged",
222
+ "ledger_version": LEDGER_VERSION,
223
+ "digest_algorithm": DIGEST_SCHEME,
224
+ })
225
+ return {
226
+ "variable": name,
227
+ "outcome": "unchanged",
228
+ "digest": content_digest,
229
+ }
230
+
231
+ # Archive old snapshot before overwriting (P4)
232
+ if snap_path.exists():
233
+ archive_snapshot(snap_path)
234
+ logger.info(
235
+ "Archived previous %s snapshot", name,
236
+ )
237
+
238
+ # Store
239
+ snap_path.parent.mkdir(parents=True, exist_ok=True)
240
+ pq.write_table(table, snap_path, compression="snappy")
241
+
242
+ # Variable metadata for provenance
243
+ var_meta = {
244
+ "display_name": variable.get("displayName", ""),
245
+ "category": variable.get("category", ""),
246
+ "unit": variable.get("unit", ""),
247
+ "source_name": variable.get("sourceName", ""),
248
+ }
249
+
250
+ # Provenance
251
+ append_ledger_entry(config.ledger_path, {
252
+ "dataset": DATASET_ID,
253
+ "version": name,
254
+ "n_cells": len(cells),
255
+ "min_value": data.get("minValue"),
256
+ "max_value": data.get("maxValue"),
257
+ "fetch_duration_s": round(fetch_duration, 2),
258
+ "content_digest": content_digest,
259
+ "variable_metadata": var_meta,
260
+ "warnings": warnings,
261
+ "outcome": "success",
262
+ "ledger_version": LEDGER_VERSION,
263
+ "digest_algorithm": DIGEST_SCHEME,
264
+ })
265
+
266
+ logger.info(
267
+ "Fetched %s: %d cells, digest %s (%.1fs)",
268
+ name, len(cells), content_digest, fetch_duration,
269
+ )
270
+
271
+ return {
272
+ "variable": name,
273
+ "outcome": "success",
274
+ "n_cells": len(cells),
275
+ "digest": content_digest,
276
+ "path": str(snap_path),
277
+ }
278
+
279
+
280
+ # ---- Orchestrator ----
281
+
282
+
283
+ def fetch_priogrid_static(
284
+ config: PriogridStaticConfig | None = None,
285
+ *,
286
+ force_refresh: bool = False,
287
+ ) -> list[dict]:
288
+ """Fetch PRIO-GRID static variables.
289
+
290
+ Discovers available static variables from the API catalog,
291
+ fetches each one, validates, and stores as Parquet with
292
+ provenance tracking.
293
+
294
+ Args:
295
+ config: Harvest configuration. Uses defaults if None.
296
+ force_refresh: If True, re-fetch even if cached.
297
+
298
+ Returns:
299
+ List of per-variable result dicts with outcome.
300
+ """
301
+ if config is None:
302
+ config = PriogridStaticConfig()
303
+
304
+ # Discover static variables
305
+ all_static = _discover_static_variables(
306
+ config.api_url, config.timeout
307
+ )
308
+ logger.info(
309
+ "Discovered %d static variables", len(all_static)
310
+ )
311
+
312
+ # Filter to requested subset if specified
313
+ if config.variables is not None:
314
+ requested = set(config.variables)
315
+ filtered = [
316
+ v for v in all_static
317
+ if v["name"] in requested
318
+ ]
319
+ missing = requested - {v["name"] for v in filtered}
320
+ if missing:
321
+ logger.warning(
322
+ "Requested variables not found: %s",
323
+ sorted(missing),
324
+ )
325
+ all_static = filtered
326
+
327
+ # Fetch each variable
328
+ results = []
329
+ for i, variable in enumerate(all_static, 1):
330
+ name = variable["name"]
331
+ logger.info(
332
+ "Fetching %s (%d/%d)...",
333
+ name, i, len(all_static),
334
+ )
335
+ try:
336
+ result = _fetch_variable(
337
+ config, variable,
338
+ force_refresh=force_refresh,
339
+ )
340
+ results.append(result)
341
+ except (
342
+ requests.RequestException,
343
+ ValueError,
344
+ json.JSONDecodeError,
345
+ ) as exc:
346
+ logger.error(
347
+ "Failed to fetch %s: %s", name, exc
348
+ )
349
+ results.append({
350
+ "variable": name,
351
+ "outcome": "failed",
352
+ "errors": [str(exc)],
353
+ })
354
+
355
+ return results
356
+
357
+
358
+ # Auto-register
359
+ register_source("priogrid_static", fetch_priogrid_static)