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,437 @@
1
+ """UCDP viewpoint v1 — production-parity materialized view.
2
+
3
+ Reads the consolidated event store, applies configurable
4
+ survivorship rules, temporal and spatial distribution, then
5
+ writes a single Parquet with one row per event-month-cell.
6
+
7
+ Processing order:
8
+ 1. Stale-version filtering (configurable via filter_stale_versions)
9
+ 2. Survivorship — one winner per event id (strategy via config)
10
+ 3. Temporal distribution — expand summary events (strategy via
11
+ config, with optional per-source-type overrides)
12
+ 4. Spatial distribution — expand imprecise events across polygon
13
+ cells (ADR-049, strategy via config)
14
+ 5. Filtering — priogrid_gid, type_of_violence, where_prec
15
+ 6. Output — Parquet with date_month column, metadata stripped
16
+
17
+ Non-configurable invariants documented in ADR-023.
18
+ Implements ADR-014 (viewpoints as derived views),
19
+ ADR-015 (UCDP-specific rules), and
20
+ ADR-049 (spatial distribution of imprecise events).
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import logging
26
+ from collections.abc import Callable
27
+
28
+ import pyarrow as pa
29
+ import pyarrow.compute as pc
30
+ import pyarrow.parquet as pq
31
+
32
+ from datafactory_provenance import (
33
+ DIGEST_SCHEME,
34
+ LEDGER_VERSION,
35
+ append_ledger_entry,
36
+ compute_file_digest,
37
+ )
38
+ from datafactory_viewpoint.builders import register_builder
39
+ from datafactory_viewpoint.spatial_distribution import (
40
+ get_spatial_distribution,
41
+ )
42
+ from datafactory_viewpoint.spatial_weights import (
43
+ build_spatial_weight_map,
44
+ )
45
+ from datafactory_viewpoint.survivorship import get_survivorship
46
+ from datafactory_viewpoint.temporal_distribution import (
47
+ get_distribution,
48
+ )
49
+ from datafactory_viewpoint.viewpoint_config import ViewpointConfig
50
+ from datafactory_viewpoint.viewpoint_result import ViewpointResult
51
+
52
+ logger = logging.getLogger(__name__)
53
+
54
+ DATASET_ID = "ucdp_viewpoint"
55
+
56
+ # ---- Boundary declarations (ADR-009) ----
57
+ # What this layer REQUIRES from the consolidated store
58
+ REQUIRED_CONSOLIDATED_FIELDS: set[str] = {
59
+ "id", "_source_type", "_source_version",
60
+ "date_start", "date_end", "date_prec",
61
+ "best", "low", "high",
62
+ "priogrid_gid", "where_prec",
63
+ }
64
+
65
+ # What this layer PRODUCES (columns added to output)
66
+ PRODUCED_FIELDS: tuple[str, ...] = ("date_month",)
67
+
68
+ # What this layer STRIPS (consolidation metadata not in output)
69
+ STRIPPED_FIELDS: set[str] = {
70
+ "_source_type", "_source_version", "_ingested_at",
71
+ "_harvest_digest", "_harvest_timestamp",
72
+ }
73
+
74
+
75
+ def _passes_filters(
76
+ row: dict, config: ViewpointConfig,
77
+ ) -> bool:
78
+ """Check if an event row passes all configured filters."""
79
+ if (
80
+ config.min_priogrid_gid is not None
81
+ and (row.get("priogrid_gid") or 0) < config.min_priogrid_gid
82
+ ):
83
+ return False
84
+ if (
85
+ config.max_type_of_violence is not None
86
+ and (row.get("type_of_violence") or 0)
87
+ > config.max_type_of_violence
88
+ ):
89
+ return False
90
+ return not (
91
+ config.exclude_where_prec
92
+ and not row.get("_spatial_distributed")
93
+ and row.get("where_prec") in config.exclude_where_prec
94
+ )
95
+
96
+
97
+ def build_ucdp_v1(
98
+ config: ViewpointConfig,
99
+ ) -> ViewpointResult:
100
+ """Build UCDP viewpoint v1 from a consolidated event store.
101
+
102
+ Uses sorted-group processing to avoid materializing all events
103
+ as Python dicts simultaneously. Peak memory is ~1 GB instead
104
+ of ~4 GB for 2.3M events.
105
+
106
+ Returns:
107
+ ViewpointResult with record counts and output digest.
108
+
109
+ Raises:
110
+ FileNotFoundError: If the consolidated store doesn't exist.
111
+ ValueError: If the store is empty or has invalid data.
112
+ """
113
+ # Validate source exists
114
+ if not config.consolidated_path.exists():
115
+ err_msg = (
116
+ f"Consolidated store not found: "
117
+ f"{config.consolidated_path}"
118
+ )
119
+ logger.error(err_msg)
120
+ raise FileNotFoundError(err_msg)
121
+
122
+ # Read consolidated store, skipping metadata columns not
123
+ # needed for processing (keep _source_type/_source_version
124
+ # for survivorship, skip _ingested_at/_harvest_* metadata).
125
+ schema = pq.read_schema(config.consolidated_path)
126
+ skip_cols = STRIPPED_FIELDS - REQUIRED_CONSOLIDATED_FIELDS
127
+ read_cols = [
128
+ c for c in schema.names if c not in skip_cols
129
+ ]
130
+ table = pq.read_table(
131
+ config.consolidated_path, columns=read_cols,
132
+ )
133
+ n_read = table.num_rows
134
+ if n_read == 0:
135
+ err_msg = "Consolidated store is empty"
136
+ logger.error(err_msg)
137
+ raise ValueError(err_msg)
138
+
139
+ logger.info(
140
+ "Read consolidated store: %d events from %s",
141
+ n_read, config.consolidated_path,
142
+ )
143
+ n_stale = 0
144
+
145
+ # Filter stale non-annual versions (ADR-023).
146
+ # Controlled by config.filter_stale_versions.
147
+ if config.filter_stale_versions:
148
+ # VIEWSER's GedLoader processes sources in a specific order:
149
+ # 1. Annual is loaded first (authoritative, curated).
150
+ # 2. .9 monthly release overwrites the trailing 12 months.
151
+ # 3. Candidate updates individual months.
152
+ #
153
+ # For months covered by the annual, ONLY annual events
154
+ # exist in VIEWSER — candidate and .9 events for those
155
+ # months are replaced. We replicate this by:
156
+ # a) Determining the annual's temporal coverage
157
+ # b) Dropping candidate/.9 rows whose event id doesn't
158
+ # appear in the annual
159
+ # c) Keeping only the latest .9 version
160
+ source_types = table.column("_source_type")
161
+ source_versions = table.column("_source_version")
162
+ n_before = table.num_rows
163
+
164
+ # (a) Find annual coverage boundary
165
+ annual_mask = pc.equal(source_types, "annual")
166
+ annual_dates = pc.filter(
167
+ table.column("date_end"), annual_mask,
168
+ )
169
+ if len(annual_dates) > 0:
170
+ annual_cutoff = max(annual_dates.to_pylist())
171
+ annual_ids = set(
172
+ pc.filter(
173
+ table.column("id"), annual_mask,
174
+ ).to_pylist()
175
+ )
176
+ logger.info(
177
+ "Annual covers through %s (%d events)",
178
+ annual_cutoff, len(annual_ids),
179
+ )
180
+
181
+ # (b) Drop non-annual rows for events NOT in
182
+ # annual within the annual coverage period
183
+ ids_col = table.column("id")
184
+ dates_col = table.column("date_end")
185
+ is_annual = annual_mask
186
+ in_annual_ids = pc.is_in(
187
+ ids_col, pa.array(sorted(annual_ids)),
188
+ )
189
+ in_annual_period = pc.less_equal(
190
+ dates_col, pa.scalar(annual_cutoff),
191
+ )
192
+ keep = pc.or_(
193
+ is_annual,
194
+ pc.or_(
195
+ in_annual_ids,
196
+ pc.invert(in_annual_period),
197
+ ),
198
+ )
199
+ table = table.filter(keep)
200
+
201
+ # (c) For .9 sources: keep only the latest version
202
+ source_types = table.column("_source_type")
203
+ source_versions = table.column("_source_version")
204
+ dot9_mask = pc.equal(source_types, "dot9")
205
+ dot9_versions = pc.filter(source_versions, dot9_mask)
206
+ if len(dot9_versions) > 0:
207
+ from datafactory_viewpoint.survivorship import (
208
+ _parse_version,
209
+ )
210
+
211
+ latest_dot9 = max(
212
+ dot9_versions.unique().to_pylist(),
213
+ key=_parse_version,
214
+ )
215
+ keep = pc.or_(
216
+ pc.not_equal(source_types, "dot9"),
217
+ pc.equal(source_versions, latest_dot9),
218
+ )
219
+ table = table.filter(keep)
220
+
221
+ n_stale = n_before - table.num_rows
222
+ if n_stale > 0:
223
+ logger.info(
224
+ "Filtered %d stale rows (%d remain)",
225
+ n_stale, table.num_rows,
226
+ )
227
+ else:
228
+ logger.info(
229
+ "Stale-version filtering disabled by config"
230
+ )
231
+
232
+ # Update count after optional stale filtering
233
+ n_input = table.num_rows
234
+
235
+ if n_read != n_input + n_stale:
236
+ raise RuntimeError(
237
+ f"Count conservation violation at stale filtering: "
238
+ f"read ({n_read}) != "
239
+ f"input ({n_input}) + stale ({n_stale})"
240
+ )
241
+
242
+ # Look up strategies
243
+ survivorship_fn = get_survivorship(config.survivorship_strategy)
244
+ distribution_fn = get_distribution(config.distribution_strategy)
245
+ spatial_dist_fn = get_spatial_distribution(
246
+ config.spatial_distribution_strategy,
247
+ )
248
+
249
+ # Pre-resolve source-distribution overrides
250
+ source_dist_fns: (
251
+ dict[str, Callable[[dict], list[dict]]] | None
252
+ ) = None
253
+ if config.source_distribution_map is not None:
254
+ source_dist_fns = {
255
+ src: get_distribution(strat)
256
+ for src, strat in config.source_distribution_map.items()
257
+ }
258
+
259
+ # Build spatial weight map (if distributing)
260
+ weight_map = None
261
+ if config.spatial_distribution_strategy != "passthrough":
262
+ weight_map = build_spatial_weight_map(
263
+ table,
264
+ config.gaul1_crosswalk_path,
265
+ config.gaul0_crosswalk_path,
266
+ )
267
+
268
+ # Sort by event id for grouped processing
269
+ table = table.sort_by("id")
270
+ col_names = table.column_names
271
+
272
+ # Get id column as Python list for group boundary detection
273
+ ids = table.column("id").to_pylist()
274
+
275
+ # Prepare output columns (streaming accumulation)
276
+ output_col_names = [
277
+ c for c in col_names if c not in STRIPPED_FIELDS
278
+ ]
279
+ output_col_names.append("date_month")
280
+ output_columns: dict[str, list] = {
281
+ col: [] for col in output_col_names
282
+ }
283
+
284
+ n_groups = 0
285
+ n_summary = 0
286
+ n_filtered = 0
287
+ n_spatially_distributed = 0
288
+ n_spatial_cells_created = 0
289
+ n_excluded_where_prec = 0
290
+ n_passthrough_where_prec = 0
291
+
292
+ # Process groups: walk sorted id column, slice per group
293
+ i = 0
294
+ while i < n_input:
295
+ # Find end of current group (same event id)
296
+ current_id = ids[i]
297
+ j = i + 1
298
+ while j < n_input and ids[j] == current_id:
299
+ j += 1
300
+
301
+ # Extract group as list of dicts (small: typically 1-5)
302
+ group_slice = table.slice(i, j - i)
303
+ group_dict = group_slice.to_pydict()
304
+ group_events = [
305
+ {col: group_dict[col][k] for col in col_names}
306
+ for k in range(j - i)
307
+ ]
308
+
309
+ # Survivorship: pick winner from group
310
+ winner = survivorship_fn(group_events)
311
+ n_groups += 1
312
+
313
+ # Distribution: expand summary events
314
+ # Use per-source override if configured, else default
315
+ if source_dist_fns is not None:
316
+ src_type = winner.get("_source_type", "")
317
+ fn = source_dist_fns.get(src_type, distribution_fn)
318
+ else:
319
+ fn = distribution_fn
320
+ distributed = fn(winner)
321
+ if len(distributed) > 1:
322
+ n_summary += 1
323
+
324
+ # Spatial distribution: expand imprecise events
325
+ if weight_map is not None:
326
+ spatially_expanded: list[dict] = []
327
+ event_was_distributed = False
328
+ for row in distributed:
329
+ expanded = spatial_dist_fn(row, weight_map)
330
+ if len(expanded) > 1:
331
+ event_was_distributed = True
332
+ n_spatial_cells_created += len(expanded)
333
+ spatially_expanded.extend(expanded)
334
+ if event_was_distributed:
335
+ n_spatially_distributed += 1
336
+ distributed = spatially_expanded
337
+
338
+ # Count passthrough events (where_prec >= 4 but not distributed)
339
+ for row in distributed:
340
+ if (
341
+ row.get("where_prec", 1) >= 4
342
+ and not row.get("_spatial_distributed")
343
+ ):
344
+ n_passthrough_where_prec += 1
345
+
346
+ # Filter + append to output columns
347
+ for row in distributed:
348
+ if not _passes_filters(row, config):
349
+ n_filtered += 1
350
+ if (
351
+ config.exclude_where_prec
352
+ and not row.get("_spatial_distributed")
353
+ and row.get("where_prec")
354
+ in config.exclude_where_prec
355
+ ):
356
+ n_excluded_where_prec += 1
357
+ continue
358
+ for col in output_col_names:
359
+ output_columns[col].append(row.get(col))
360
+
361
+ i = j
362
+
363
+ logger.info(
364
+ "Processed %d groups: %d summary expanded, "
365
+ "%d spatially distributed (%d cells), "
366
+ "%d passthrough where_prec, %d excluded where_prec, "
367
+ "%d filtered, %d output rows",
368
+ n_groups, n_summary,
369
+ n_spatially_distributed, n_spatial_cells_created,
370
+ n_passthrough_where_prec, n_excluded_where_prec,
371
+ n_filtered, len(output_columns["date_month"]),
372
+ )
373
+
374
+ # Build output table from accumulated columns
375
+ pa_columns = {
376
+ col: pa.array(vals, from_pandas=True)
377
+ for col, vals in output_columns.items()
378
+ }
379
+ output_table = pa.table(pa_columns)
380
+
381
+ # Write output
382
+ config.output_path.parent.mkdir(parents=True, exist_ok=True)
383
+ pq.write_table(output_table, config.output_path)
384
+
385
+ output_digest = compute_file_digest(config.output_path)
386
+
387
+ n_output = len(output_columns["date_month"])
388
+ n_survivorship_discarded = n_input - n_groups
389
+
390
+ # Record provenance
391
+ append_ledger_entry(config.ledger_path, {
392
+ "dataset": DATASET_ID,
393
+ "version": config.version,
394
+ "survivorship_strategy": config.survivorship_strategy,
395
+ "distribution_strategy": config.distribution_strategy,
396
+ "spatial_distribution_strategy": (
397
+ config.spatial_distribution_strategy
398
+ ),
399
+ "filter_stale_versions": config.filter_stale_versions,
400
+ "source_distribution_map": config.source_distribution_map,
401
+ "n_events_read": n_read,
402
+ "n_stale_filtered": n_stale,
403
+ "n_events_input": n_input,
404
+ "n_groups": n_groups,
405
+ "n_survivorship_discarded": n_survivorship_discarded,
406
+ "n_events_output": n_output,
407
+ "n_summary_expanded": n_summary,
408
+ "n_spatially_distributed": n_spatially_distributed,
409
+ "n_spatial_cells_created": n_spatial_cells_created,
410
+ "n_excluded_where_prec": n_excluded_where_prec,
411
+ "n_passthrough_where_prec": n_passthrough_where_prec,
412
+ "n_filtered": n_filtered,
413
+ "output_path": str(config.output_path),
414
+ "output_digest": output_digest,
415
+ "ledger_version": LEDGER_VERSION,
416
+ "digest_algorithm": DIGEST_SCHEME,
417
+ })
418
+
419
+ logger.info(
420
+ "Viewpoint %s built: %d → %d rows (digest: %s)",
421
+ config.version, n_input, n_output, output_digest,
422
+ )
423
+
424
+ return ViewpointResult(
425
+ output_path=config.output_path,
426
+ n_events_input=n_input,
427
+ n_events_output=n_output,
428
+ n_summary_expanded=n_summary,
429
+ n_spatially_distributed=n_spatially_distributed,
430
+ n_filtered=n_filtered,
431
+ output_digest=output_digest,
432
+ version=config.version,
433
+ )
434
+
435
+
436
+ # Auto-register
437
+ register_builder("ucdp_v1", build_ucdp_v1)