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,389 @@
1
+ """SHDI viewpoint v1 — GDL region-year to grid-monthly broadcast.
2
+
3
+ Reads SHDI harvest output (GDL region-year Parquet), applies GDL→pgid
4
+ crosswalk from the SHDI harvester's spatial join, and expands annual
5
+ values to monthly (step function: constant within each year).
6
+
7
+ No consolidation layer (ADR-036: single periodic release).
8
+ Viewpoint reads directly from data/raw/shdi/.
9
+
10
+ SHDI is an intensive quantity (ADR-040): sums are meaningless.
11
+ Invariants are value range [0, 1] and completeness.
12
+
13
+ Implements ADR-014 (viewpoints as derived views), ADR-036 (SHDI).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path
21
+
22
+ import numpy as np
23
+ import pyarrow as pa
24
+ import pyarrow.parquet as pq
25
+
26
+ from datafactory_provenance import (
27
+ DIGEST_SCHEME,
28
+ LEDGER_VERSION,
29
+ VIEWS_EPOCH_YEAR,
30
+ append_ledger_entry,
31
+ compute_file_digest,
32
+ )
33
+ from datafactory_viewpoint.builders import register_builder
34
+ from datafactory_viewpoint.temporal import (
35
+ VALID_TEMPORAL_INTERPOLATIONS,
36
+ interpolate_temporal,
37
+ )
38
+ from datafactory_viewpoint.viewpoint_result import ViewpointResult
39
+
40
+ logger = logging.getLogger(__name__)
41
+
42
+ DATASET_ID = "shdi_viewpoint"
43
+
44
+ SHDI_VARIABLES: tuple[str, ...] = (
45
+ "shdi",
46
+ "healthindex",
47
+ "edindex",
48
+ "incindex",
49
+ )
50
+
51
+
52
+ # ---- Config ----
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class ShdiViewpointConfig:
57
+ """Configuration for building an SHDI viewpoint.
58
+
59
+ Reads harvest Parquet (GDL region-year), applies GDL→pgid
60
+ crosswalk, expands annual to monthly, writes Parquet with
61
+ (pgid, month_id, shdi, healthindex, edindex, incindex).
62
+ """
63
+
64
+ source_path: Path = field(
65
+ default_factory=lambda: Path(
66
+ "data/raw/shdi/shdi_v10.2.parquet"
67
+ )
68
+ )
69
+ crosswalk_path: Path = field(
70
+ default_factory=lambda: Path(
71
+ "data/raw/shdi/gdl_to_pgid.parquet"
72
+ )
73
+ )
74
+
75
+ output_path: Path = Path("data/viewpoint/shdi_v1.parquet")
76
+ ledger_path: Path = Path(
77
+ "provenance/viewpoint/shdi_v1_ledger.jsonl"
78
+ )
79
+
80
+ variables: tuple[str, ...] = SHDI_VARIABLES
81
+
82
+ start_year: int = 1990
83
+ end_year: int = 2023
84
+
85
+ temporal_interpolation: str = "step"
86
+
87
+ version: str = "shdi_v1"
88
+
89
+ def __post_init__(self) -> None:
90
+ if not self.version:
91
+ msg = "version must be non-empty"
92
+ logger.error(msg)
93
+ raise ValueError(msg)
94
+ if not self.variables:
95
+ msg = "variables must be non-empty"
96
+ logger.error(msg)
97
+ raise ValueError(msg)
98
+ if (
99
+ self.temporal_interpolation
100
+ not in VALID_TEMPORAL_INTERPOLATIONS
101
+ ):
102
+ msg = (
103
+ f"temporal_interpolation "
104
+ f"'{self.temporal_interpolation}' not in "
105
+ f"{VALID_TEMPORAL_INTERPOLATIONS}"
106
+ )
107
+ logger.error(msg)
108
+ raise ValueError(msg)
109
+ if self.start_year < VIEWS_EPOCH_YEAR:
110
+ msg = (
111
+ f"start_year {self.start_year} is before "
112
+ f"VIEWS epoch {VIEWS_EPOCH_YEAR}"
113
+ )
114
+ logger.error(msg)
115
+ raise ValueError(msg)
116
+ if self.end_year < self.start_year:
117
+ msg = (
118
+ f"end_year {self.end_year} < "
119
+ f"start_year {self.start_year}"
120
+ )
121
+ logger.error(msg)
122
+ raise ValueError(msg)
123
+
124
+
125
+ # ---- Crosswalk ----
126
+
127
+
128
+ def _build_gdl_to_pgids(
129
+ crosswalk_path: Path,
130
+ ) -> dict[str, list[int]]:
131
+ """Build GDL code → list[pgid] mapping from gdl_to_pgid.parquet.
132
+
133
+ The SHDI harvester writes gdl_to_pgid.parquet with columns
134
+ (gid, gdl_code) where gid is pgid and gdl_code is GDL region.
135
+ """
136
+ table = pq.read_table(crosswalk_path)
137
+ gids = table.column("gid").to_pylist()
138
+ gdl_codes = table.column("gdl_code").to_pylist()
139
+
140
+ mapping: dict[str, list[int]] = {}
141
+ for gid, gdl_code in zip(gids, gdl_codes, strict=True):
142
+ if gdl_code is None or gdl_code == "":
143
+ continue
144
+ code_str = str(gdl_code)
145
+ if code_str not in mapping:
146
+ mapping[code_str] = []
147
+ mapping[code_str].append(int(gid))
148
+
149
+ logger.info(
150
+ "Crosswalk: %d GDL codes → %d pgids",
151
+ len(mapping),
152
+ sum(len(v) for v in mapping.values()),
153
+ )
154
+ return mapping
155
+
156
+
157
+ # ---- Builder ----
158
+
159
+
160
+ def build_shdi_v1(
161
+ config: ShdiViewpointConfig,
162
+ ) -> ViewpointResult:
163
+ """Build SHDI viewpoint v1 from harvested GDL region-year data.
164
+
165
+ For each (GDLCODE, Year): look up pgids via GDL crosswalk,
166
+ create 12 monthly rows (step function), write Parquet with
167
+ (pgid, month_id, shdi, healthindex, edindex, incindex).
168
+
169
+ Returns:
170
+ ViewpointResult with row counts and output digest.
171
+ """
172
+ if not config.source_path.exists():
173
+ msg = f"Source file not found: {config.source_path}"
174
+ logger.error(msg)
175
+ raise FileNotFoundError(msg)
176
+
177
+ if not config.crosswalk_path.exists():
178
+ msg = (
179
+ f"Crosswalk file not found: {config.crosswalk_path}"
180
+ )
181
+ logger.error(msg)
182
+ raise FileNotFoundError(msg)
183
+
184
+ # Build GDL → pgids mapping
185
+ gdl_to_pgids = _build_gdl_to_pgids(config.crosswalk_path)
186
+
187
+ # Read harvest output
188
+ source_table = pq.read_table(config.source_path)
189
+ n_input = source_table.num_rows
190
+
191
+ gdl_col = source_table.column("GDLCODE").to_pylist()
192
+ year_col = source_table.column("Year").to_pylist()
193
+ var_arrays = {
194
+ var: source_table.column(var).to_numpy(
195
+ zero_copy_only=False
196
+ )
197
+ for var in config.variables
198
+ if var in source_table.column_names
199
+ }
200
+ del source_table
201
+
202
+ missing_vars = (
203
+ set(config.variables) - set(var_arrays.keys())
204
+ )
205
+ if missing_vars:
206
+ msg = (
207
+ f"Source Parquet missing variables: "
208
+ f"{sorted(missing_vars)}"
209
+ )
210
+ logger.error(msg)
211
+ raise ValueError(msg)
212
+
213
+ # Phase 1: group source rows by region, building epoch dicts
214
+ unmapped_regions: set[str] = set()
215
+ n_filtered = 0
216
+
217
+ region_epochs: dict[
218
+ str, dict[str, dict[int, float]]
219
+ ] = {}
220
+
221
+ for i in range(n_input):
222
+ gdl_code = str(gdl_col[i])
223
+ year = int(year_col[i])
224
+
225
+ if year < config.start_year or year > config.end_year:
226
+ n_filtered += 1
227
+ continue
228
+
229
+ if gdl_to_pgids.get(gdl_code) is None:
230
+ unmapped_regions.add(gdl_code)
231
+ continue
232
+
233
+ if gdl_code not in region_epochs:
234
+ region_epochs[gdl_code] = {
235
+ var: {} for var in config.variables
236
+ }
237
+ for var in config.variables:
238
+ region_epochs[gdl_code][var][year] = float(
239
+ var_arrays[var][i]
240
+ )
241
+
242
+ # Phase 2: interpolate via shared temporal module, expand
243
+ pgid_chunks: list[np.ndarray] = []
244
+ month_chunks: list[np.ndarray] = []
245
+ var_chunks: dict[str, list[np.ndarray]] = {
246
+ var: [] for var in config.variables
247
+ }
248
+
249
+ for gdl_code, var_epoch_map in region_epochs.items():
250
+ pgid_arr = np.array(
251
+ gdl_to_pgids[gdl_code], dtype=np.int32
252
+ )
253
+ n_pgids = len(pgid_arr)
254
+
255
+ first_var = next(iter(var_epoch_map))
256
+ years_present = sorted(
257
+ var_epoch_map[first_var].keys()
258
+ )
259
+ min_year = years_present[0]
260
+ max_year = years_present[-1]
261
+
262
+ monthly_vals: dict[str, list[float]] = {}
263
+ for var, epochs in var_epoch_map.items():
264
+ monthly_vals[var] = interpolate_temporal(
265
+ epochs,
266
+ strategy=config.temporal_interpolation,
267
+ start_year=min_year,
268
+ start_month=1,
269
+ end_year=max_year,
270
+ end_month=12,
271
+ )
272
+
273
+ n_months = len(monthly_vals[first_var])
274
+ month_id_arr = np.array(
275
+ [
276
+ (min_year - VIEWS_EPOCH_YEAR) * 12 + m + 1
277
+ for m in range(n_months)
278
+ ],
279
+ dtype=np.int32,
280
+ )
281
+
282
+ pgid_chunks.append(np.tile(pgid_arr, n_months))
283
+ month_chunks.append(
284
+ np.repeat(month_id_arr, n_pgids)
285
+ )
286
+ for var in config.variables:
287
+ vals = np.array(
288
+ monthly_vals[var], dtype=np.float64
289
+ )
290
+ var_chunks[var].append(
291
+ np.repeat(vals, n_pgids)
292
+ )
293
+
294
+ empty_i32 = np.array([], dtype=np.int32)
295
+ empty_f64 = np.array([], dtype=np.float64)
296
+ pgid_rows = (
297
+ np.concatenate(pgid_chunks) if pgid_chunks
298
+ else empty_i32
299
+ )
300
+ month_id_rows = (
301
+ np.concatenate(month_chunks) if month_chunks
302
+ else empty_i32
303
+ )
304
+ var_rows: dict[str, np.ndarray] = {}
305
+ for var in config.variables:
306
+ chunks = var_chunks[var]
307
+ var_rows[var] = (
308
+ np.concatenate(chunks) if chunks else empty_f64
309
+ )
310
+
311
+ if unmapped_regions:
312
+ logger.warning(
313
+ "%d SHDI regions not in GDL crosswalk: %s",
314
+ len(unmapped_regions),
315
+ sorted(unmapped_regions)[:10],
316
+ )
317
+
318
+ if n_filtered > 0:
319
+ logger.info(
320
+ "Filtered %d rows outside year range %d–%d",
321
+ n_filtered, config.start_year, config.end_year,
322
+ )
323
+
324
+ n_output = len(pgid_rows)
325
+ if n_output == 0:
326
+ msg = "Viewpoint produced zero output rows"
327
+ logger.error(msg)
328
+ raise ValueError(msg)
329
+
330
+ # Build Arrow table
331
+ columns: dict[str, pa.Array] = {
332
+ "pgid": pa.array(pgid_rows, type=pa.int32()),
333
+ "month_id": pa.array(month_id_rows, type=pa.int32()),
334
+ }
335
+ for var in config.variables:
336
+ columns[var] = pa.array(
337
+ var_rows[var], type=pa.float64()
338
+ )
339
+ del pgid_rows, month_id_rows, var_rows
340
+
341
+ table = pa.table(columns)
342
+
343
+ # Write Parquet
344
+ config.output_path.parent.mkdir(parents=True, exist_ok=True)
345
+ pq.write_table(table, config.output_path, compression="snappy")
346
+
347
+ output_digest = compute_file_digest(config.output_path)
348
+
349
+ # Provenance
350
+ append_ledger_entry(config.ledger_path, {
351
+ "dataset": DATASET_ID,
352
+ "version": config.version,
353
+ "n_input_rows": n_input,
354
+ "n_output_rows": n_output,
355
+ "n_variables": len(config.variables),
356
+ "unmapped_regions": len(unmapped_regions),
357
+ "n_filtered_years": n_filtered,
358
+ "year_range": [config.start_year, config.end_year],
359
+ "output_path": str(config.output_path),
360
+ "output_digest": output_digest,
361
+ "outcome": "success",
362
+ "ledger_version": LEDGER_VERSION,
363
+ "digest_algorithm": DIGEST_SCHEME,
364
+ })
365
+
366
+ logger.info(
367
+ "SHDI viewpoint %s built: %d input → %d output rows "
368
+ "(%d variables, %d unmapped regions, digest: %s)",
369
+ config.version,
370
+ n_input,
371
+ n_output,
372
+ len(config.variables),
373
+ len(unmapped_regions),
374
+ output_digest,
375
+ )
376
+
377
+ return ViewpointResult(
378
+ output_path=config.output_path,
379
+ n_events_input=n_input,
380
+ n_events_output=n_output,
381
+ n_summary_expanded=0,
382
+ n_spatially_distributed=0,
383
+ n_filtered=n_filtered,
384
+ output_digest=output_digest,
385
+ version=config.version,
386
+ )
387
+
388
+
389
+ register_builder("shdi_v1", build_shdi_v1)