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,125 @@
1
+ """Shared pipeline execution runner (C-164 Pattern #7).
2
+
3
+ Provides run_pipeline() — the common skeleton for all pipeline
4
+ scripts: line buffering, banner, per-step timing, skip-to logic,
5
+ precondition checks, and error handling.
6
+ Source-specific logic stays in the calling script via step closures.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import sys
12
+ import time
13
+ from collections.abc import Callable
14
+ from dataclasses import dataclass
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class PipelineStep:
19
+ """A single step in a pipeline.
20
+
21
+ run: called when this step executes. Should raise on failure.
22
+ skip_check: called when this step is skipped (--skip-to past it).
23
+ Returns a detail string for the skip message (e.g. "3 files").
24
+ Should raise if precondition data is missing.
25
+ """
26
+
27
+ name: str
28
+ run: Callable[[], None]
29
+ skip_check: Callable[[], str] | None = None
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class PipelineResult:
34
+ """Result of running a pipeline."""
35
+
36
+ source_name: str
37
+ steps_run: tuple[str, ...]
38
+ steps_skipped: tuple[str, ...]
39
+ elapsed: float
40
+ step_timings: dict[str, float]
41
+ success: bool
42
+
43
+
44
+ def run_pipeline(
45
+ *,
46
+ source_name: str,
47
+ steps: tuple[PipelineStep, ...],
48
+ config_summary: dict[str, str] | None = None,
49
+ skip_to: str | None = None,
50
+ ) -> PipelineResult:
51
+ """Execute a multi-step pipeline with skip-to support.
52
+
53
+ For each step:
54
+ 1. If skipped: call skip_check (verify preconditions), print skip label
55
+ 2. If running: print step label, call run() with timing, catch errors
56
+ """
57
+ sys.stdout.reconfigure(line_buffering=True) # type: ignore[union-attr]
58
+
59
+ n = len(steps)
60
+ step_names = [s.name for s in steps]
61
+ skip_idx = step_names.index(skip_to) if skip_to else 0
62
+
63
+ print("=" * 60)
64
+ print(f"{source_name} PIPELINE")
65
+ if config_summary:
66
+ for key, value in config_summary.items():
67
+ print(f"{key}: {value}")
68
+ if skip_to:
69
+ print(f"Skipping to: {skip_to}")
70
+ print("=" * 60)
71
+ print()
72
+
73
+ t_start = time.monotonic()
74
+ steps_run: list[str] = []
75
+ steps_skipped: list[str] = []
76
+ step_timings: dict[str, float] = {}
77
+
78
+ def _fail_result() -> PipelineResult:
79
+ return PipelineResult(
80
+ source_name=source_name,
81
+ steps_run=tuple(steps_run),
82
+ steps_skipped=tuple(steps_skipped),
83
+ elapsed=time.monotonic() - t_start,
84
+ step_timings=step_timings,
85
+ success=False,
86
+ )
87
+
88
+ for i, step in enumerate(steps):
89
+ label = f"[{i + 1}/{n}] {step.name.upper()}"
90
+
91
+ if i < skip_idx:
92
+ if step.skip_check is not None:
93
+ try:
94
+ detail = step.skip_check()
95
+ except Exception as e:
96
+ print(f"FAIL: {e}")
97
+ return _fail_result()
98
+ print(f"{label} — skipped ({detail})")
99
+ else:
100
+ print(f"{label} — skipped")
101
+ steps_skipped.append(step.name)
102
+ print()
103
+ else:
104
+ print(label)
105
+ t0 = time.monotonic()
106
+ try:
107
+ step.run()
108
+ except Exception as e:
109
+ print(f" FAIL: {e}")
110
+ return _fail_result()
111
+ dt = time.monotonic() - t0
112
+ step_timings[step.name] = dt
113
+ steps_run.append(step.name)
114
+ print(f" ({dt:.1f}s)")
115
+ print()
116
+
117
+ elapsed = time.monotonic() - t_start
118
+ return PipelineResult(
119
+ source_name=source_name,
120
+ steps_run=tuple(steps_run),
121
+ steps_skipped=tuple(steps_skipped),
122
+ elapsed=elapsed,
123
+ step_timings=step_timings,
124
+ success=True,
125
+ )
@@ -0,0 +1,117 @@
1
+ """Source-agnostic event snapshot storage.
2
+
3
+ Handles Parquet persistence and archiving of raw event snapshots.
4
+ No knowledge of specific data sources.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import os
11
+ import tempfile
12
+ from datetime import UTC, datetime
13
+ from pathlib import Path
14
+
15
+ import pyarrow as pa
16
+ import pyarrow.parquet as pq
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ _PARQUET_COMPRESSION: str = "snappy"
21
+
22
+ _ARCHIVE_DIRNAME: str = "archive"
23
+
24
+
25
+ def save_event_snapshot(
26
+ events: list[dict],
27
+ path: Path,
28
+ ) -> None:
29
+ """Persist all raw event fields as a Parquet file.
30
+
31
+ Preserves every field from the source — enables event-level
32
+ revision detection and arbitrary re-analysis.
33
+
34
+ Atomic (C-233): writes to a temp file in the same directory,
35
+ then renames. A crash mid-write can never leave a truncated
36
+ Parquet at the canonical path — the raw layer is the recovery
37
+ layer, so its snapshots must be uncorruptible.
38
+
39
+ Args:
40
+ events: List of raw event dicts.
41
+ path: Output Parquet file path.
42
+
43
+ Raises:
44
+ ValueError: If events list is empty.
45
+ """
46
+ if not events:
47
+ err_msg = "No events to save as snapshot"
48
+ logger.error(err_msg)
49
+ raise ValueError(err_msg)
50
+
51
+ path.parent.mkdir(parents=True, exist_ok=True)
52
+
53
+ # Build column arrays from event dicts
54
+ all_fields = sorted({k for ev in events for k in ev})
55
+
56
+ columns: dict[str, list] = {f: [] for f in all_fields}
57
+ for ev in events:
58
+ for f in all_fields:
59
+ columns[f].append(ev.get(f))
60
+
61
+ pa_columns: dict[str, pa.Array] = {}
62
+ for name, values in columns.items():
63
+ pa_columns[name] = pa.array(values, from_pandas=True)
64
+
65
+ table = pa.table(pa_columns)
66
+
67
+ fd, tmp = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
68
+ try:
69
+ os.close(fd)
70
+ tmp_path = Path(tmp)
71
+ pq.write_table(
72
+ table, tmp_path, compression=_PARQUET_COMPRESSION,
73
+ )
74
+ tmp_path.rename(path)
75
+ except BaseException:
76
+ Path(tmp).unlink(missing_ok=True)
77
+ raise
78
+
79
+ logger.info(
80
+ "Saved event snapshot to %s (%d events, %d fields)",
81
+ path,
82
+ len(events),
83
+ len(all_fields),
84
+ )
85
+
86
+
87
+ def archive_snapshot(path: Path) -> Path | None:
88
+ """Move an existing snapshot to a dated archive.
89
+
90
+ Archives land in an ``archive/`` subdirectory (C-234) so
91
+ consolidation source-file globs structurally cannot pick them
92
+ up — same-directory archives were excluded only by filename
93
+ convention, and tripped spurious year-overlap warnings.
94
+
95
+ Uses the current UTC timestamp for the archive suffix.
96
+ Returns the archive path, or None if the source doesn't exist.
97
+
98
+ Args:
99
+ path: Path to the existing snapshot.
100
+
101
+ Returns:
102
+ Path to the archive, or None if source doesn't exist.
103
+ """
104
+ if not path.exists():
105
+ return None
106
+
107
+ stamp = datetime.now(tz=UTC).strftime("%Y%m%d_%H%M%S")
108
+ archive_dir = path.parent / _ARCHIVE_DIRNAME
109
+ archive_dir.mkdir(parents=True, exist_ok=True)
110
+ archive_path = archive_dir / f"{path.stem}_{stamp}{path.suffix}"
111
+ path.rename(archive_path)
112
+
113
+ logger.info(
114
+ "Archived snapshot: %s -> %s/%s",
115
+ path.name, _ARCHIVE_DIRNAME, archive_path.name,
116
+ )
117
+ return archive_path
@@ -0,0 +1,36 @@
1
+ """Pluggable data source registry.
2
+
3
+ Each source module registers itself via register_source().
4
+ Consumers call fetch_source(name, ...) without knowing the implementation.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Callable
10
+ from typing import Any
11
+
12
+ from datafactory_provenance.registry import Registry
13
+
14
+ _registry: Registry[Callable[..., Any]] = Registry("source")
15
+
16
+ # Backward-compatible public API
17
+ _SOURCES = _registry.entries # conftest.py accesses this directly
18
+ register_source = _registry.register
19
+ list_sources = _registry.list_entries
20
+
21
+
22
+ def fetch_source(name: str, **kwargs: Any) -> Any:
23
+ """Fetch data from a registered source.
24
+
25
+ Args:
26
+ name: Source identifier.
27
+ **kwargs: Passed to the source's fetch function.
28
+
29
+ Returns:
30
+ Source-specific result (Path for single-source,
31
+ list[dict] for multi-version).
32
+
33
+ Raises:
34
+ KeyError: If the source name is not registered.
35
+ """
36
+ return _registry.get(name)(**kwargs)
@@ -0,0 +1,34 @@
1
+ """Shared constants and validation for UCDP GED API sources.
2
+
3
+ Extracted from ucdp_annual.py so that candidate and .9 harvesters
4
+ can validate API envelopes without importing a sibling source module.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ ENVELOPE_KEYS: set[str] = {"TotalCount", "TotalPages", "Result"}
14
+
15
+ UCDP_GED_API_BASE: str = "https://ucdpapi.pcr.uu.se/api/gedevents"
16
+
17
+
18
+ def validate_envelope(data: dict) -> None:
19
+ """Validate the API response envelope structure."""
20
+ missing = ENVELOPE_KEYS - set(data.keys())
21
+ if missing:
22
+ err_msg = (
23
+ f"UCDP API response envelope missing keys: {missing}. "
24
+ f"Available keys: {sorted(data.keys())}."
25
+ )
26
+ logger.error(err_msg)
27
+ raise ValueError(err_msg)
28
+ if not isinstance(data["Result"], list):
29
+ err_msg = (
30
+ f"UCDP API 'Result' is {type(data['Result']).__name__}, "
31
+ f"expected list."
32
+ )
33
+ logger.error(err_msg)
34
+ raise ValueError(err_msg)