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,291 @@
|
|
|
1
|
+
"""Pre-gridded compilation: place pre-gridded data onto the spatiotemporal grid.
|
|
2
|
+
|
|
3
|
+
Reads viewpoint output Parquet with (pgid, month_id, value) rows,
|
|
4
|
+
places values directly into [T, H, W, C] npy arrays. No lat/lon
|
|
5
|
+
lookup or event aggregation — the viewpoint has already resolved
|
|
6
|
+
spatial and temporal coordinates.
|
|
7
|
+
|
|
8
|
+
Produces the same output format as compile_grid(): grid.npy,
|
|
9
|
+
pgids.npy, time_steps.npy, feature_names.json, provenance.json,
|
|
10
|
+
and a ledger entry.
|
|
11
|
+
|
|
12
|
+
Ref: ADR-024 (grid invariants), ADR-029 (GHS-POP source).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import logging
|
|
18
|
+
import os
|
|
19
|
+
import tempfile
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import ClassVar
|
|
23
|
+
|
|
24
|
+
import numpy as np
|
|
25
|
+
import pyarrow.parquet as pq
|
|
26
|
+
|
|
27
|
+
from datafactory_compilation.output import write_compilation_output
|
|
28
|
+
from datafactory_compilation.preflight import check_disk_space
|
|
29
|
+
from datafactory_priogrid.cell_generator import generate_grid
|
|
30
|
+
from datafactory_priogrid.grid_config import DEFAULT_GRID_CONFIG, GridConfig
|
|
31
|
+
from datafactory_priogrid.temporal_config import TemporalConfig
|
|
32
|
+
from datafactory_priogrid.temporal_generator import (
|
|
33
|
+
DEFAULT_TEMPORAL_CONFIG,
|
|
34
|
+
generate_time_steps,
|
|
35
|
+
)
|
|
36
|
+
from datafactory_provenance import VIEWS_EPOCH_YEAR, compute_file_digest
|
|
37
|
+
|
|
38
|
+
logger = logging.getLogger(__name__)
|
|
39
|
+
|
|
40
|
+
DATASET_ID = "pregridded_compilation"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class PregriddedFeatureSpec:
|
|
45
|
+
"""A single pre-gridded feature: output name and source column."""
|
|
46
|
+
|
|
47
|
+
name: str
|
|
48
|
+
value_field: str
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class PregriddedCompilationConfig:
|
|
53
|
+
"""Configuration for compiling pre-gridded viewpoint output onto the grid.
|
|
54
|
+
|
|
55
|
+
Unlike CompilationConfig, this expects source data already keyed by
|
|
56
|
+
(pgid, month_id) — no lat/lon lookup or aggregation strategies.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
source_path: Path
|
|
60
|
+
|
|
61
|
+
grid_config: GridConfig = field(
|
|
62
|
+
default_factory=lambda: DEFAULT_GRID_CONFIG
|
|
63
|
+
)
|
|
64
|
+
temporal_config: TemporalConfig = field(
|
|
65
|
+
default_factory=lambda: DEFAULT_TEMPORAL_CONFIG
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
features: tuple[PregriddedFeatureSpec, ...] = ()
|
|
69
|
+
|
|
70
|
+
output_dir: Path = Path("data/compiled")
|
|
71
|
+
ledger_path: Path = Path(
|
|
72
|
+
"provenance/compiler/pregridded_compilation_ledger.jsonl"
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
pgid_field: str = "pgid"
|
|
76
|
+
month_id_field: str = "month_id"
|
|
77
|
+
|
|
78
|
+
output_dtype: str = "float32"
|
|
79
|
+
fill_value: float = 0.0
|
|
80
|
+
|
|
81
|
+
_ALLOWED_DTYPES: ClassVar[frozenset[str]] = frozenset({
|
|
82
|
+
"float16", "float32", "float64", "int32", "int64",
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
def __post_init__(self) -> None:
|
|
86
|
+
if not self.features:
|
|
87
|
+
err_msg = "features must be non-empty"
|
|
88
|
+
logger.error(err_msg)
|
|
89
|
+
raise ValueError(err_msg)
|
|
90
|
+
names = [f.name for f in self.features]
|
|
91
|
+
if len(names) != len(set(names)):
|
|
92
|
+
dupes = sorted({n for n in names if names.count(n) > 1})
|
|
93
|
+
err_msg = f"duplicate feature names: {dupes}"
|
|
94
|
+
logger.error(err_msg)
|
|
95
|
+
raise ValueError(err_msg)
|
|
96
|
+
if self.output_dtype not in self._ALLOWED_DTYPES:
|
|
97
|
+
err_msg = (
|
|
98
|
+
f"output_dtype must be one of "
|
|
99
|
+
f"{sorted(self._ALLOWED_DTYPES)}, "
|
|
100
|
+
f"got {self.output_dtype!r}"
|
|
101
|
+
)
|
|
102
|
+
logger.error(err_msg)
|
|
103
|
+
raise ValueError(err_msg)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _month_id_to_time_index(
|
|
107
|
+
month_id: int,
|
|
108
|
+
start_year: int,
|
|
109
|
+
start_month: int,
|
|
110
|
+
) -> int:
|
|
111
|
+
"""Convert VIEWS month_id to 0-based time index.
|
|
112
|
+
|
|
113
|
+
VIEWS month_id: 1 = January 1980.
|
|
114
|
+
Time index 0 = start_year/start_month from TemporalConfig.
|
|
115
|
+
"""
|
|
116
|
+
year = VIEWS_EPOCH_YEAR + (month_id - 1) // 12
|
|
117
|
+
month = (month_id - 1) % 12 + 1
|
|
118
|
+
return (year - start_year) * 12 + (month - start_month)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def compile_pregridded(config: PregriddedCompilationConfig) -> Path:
|
|
122
|
+
"""Compile pre-gridded viewpoint output onto the spatiotemporal grid.
|
|
123
|
+
|
|
124
|
+
Reads Parquet with (pgid, month_id, value_columns), converts pgid
|
|
125
|
+
to (row, col) and month_id to time_index, and places values into
|
|
126
|
+
[T, H, W, C] npy output.
|
|
127
|
+
|
|
128
|
+
Args:
|
|
129
|
+
config: Pre-gridded compilation configuration.
|
|
130
|
+
|
|
131
|
+
Returns:
|
|
132
|
+
Path to the output directory containing grid.npy and sidecars.
|
|
133
|
+
|
|
134
|
+
Raises:
|
|
135
|
+
FileNotFoundError: If source_path does not exist.
|
|
136
|
+
ValueError: If source Parquet lacks required columns.
|
|
137
|
+
"""
|
|
138
|
+
if not config.source_path.exists():
|
|
139
|
+
err_msg = f"Source file not found: {config.source_path}"
|
|
140
|
+
logger.error(err_msg)
|
|
141
|
+
raise FileNotFoundError(err_msg)
|
|
142
|
+
|
|
143
|
+
source_digest = compute_file_digest(config.source_path)
|
|
144
|
+
|
|
145
|
+
needed_cols = {config.pgid_field, config.month_id_field}
|
|
146
|
+
for feat in config.features:
|
|
147
|
+
needed_cols.add(feat.value_field)
|
|
148
|
+
|
|
149
|
+
available_cols = set(pq.read_schema(config.source_path).names)
|
|
150
|
+
missing_cols = needed_cols - available_cols
|
|
151
|
+
if missing_cols:
|
|
152
|
+
err_msg = (
|
|
153
|
+
f"Source Parquet missing required columns: "
|
|
154
|
+
f"{sorted(missing_cols)}. "
|
|
155
|
+
f"Available: {sorted(available_cols)}"
|
|
156
|
+
)
|
|
157
|
+
logger.error(err_msg)
|
|
158
|
+
raise ValueError(err_msg)
|
|
159
|
+
|
|
160
|
+
table = pq.read_table(
|
|
161
|
+
config.source_path, columns=sorted(needed_cols)
|
|
162
|
+
)
|
|
163
|
+
logger.info(
|
|
164
|
+
"Read %d rows from %s", table.num_rows, config.source_path
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
nrow = config.grid_config.nrow
|
|
168
|
+
ncol = config.grid_config.ncol
|
|
169
|
+
n_cells = config.grid_config.n_cells
|
|
170
|
+
n_steps = config.temporal_config.n_steps
|
|
171
|
+
n_features = len(config.features)
|
|
172
|
+
dtype = np.dtype(config.output_dtype)
|
|
173
|
+
|
|
174
|
+
config.output_dir.mkdir(parents=True, exist_ok=True)
|
|
175
|
+
check_disk_space(
|
|
176
|
+
config.output_dir,
|
|
177
|
+
n_steps * nrow * ncol * n_features * dtype.itemsize,
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
# Allocate grid as memory-mapped file (ADR-037).
|
|
181
|
+
# OS pages data in/out as needed — peak RSS stays bounded
|
|
182
|
+
# regardless of feature count.
|
|
183
|
+
tmp_fd, tmp_mmap_path = tempfile.mkstemp(
|
|
184
|
+
prefix="_memmap_", suffix=".npy",
|
|
185
|
+
dir=str(config.output_dir),
|
|
186
|
+
)
|
|
187
|
+
os.close(tmp_fd)
|
|
188
|
+
|
|
189
|
+
grid_array = None
|
|
190
|
+
try:
|
|
191
|
+
grid_array = np.lib.format.open_memmap(
|
|
192
|
+
tmp_mmap_path,
|
|
193
|
+
mode="w+",
|
|
194
|
+
dtype=dtype,
|
|
195
|
+
shape=(n_steps, nrow, ncol, n_features),
|
|
196
|
+
)
|
|
197
|
+
grid_array[:] = config.fill_value
|
|
198
|
+
|
|
199
|
+
n_rows = table.num_rows
|
|
200
|
+
pgids = table[config.pgid_field].to_numpy(
|
|
201
|
+
zero_copy_only=False,
|
|
202
|
+
)
|
|
203
|
+
month_ids = table[config.month_id_field].to_numpy(
|
|
204
|
+
zero_copy_only=False,
|
|
205
|
+
)
|
|
206
|
+
value_arrays = [
|
|
207
|
+
table[feat.value_field].to_numpy(
|
|
208
|
+
zero_copy_only=False,
|
|
209
|
+
)
|
|
210
|
+
for feat in config.features
|
|
211
|
+
]
|
|
212
|
+
del table
|
|
213
|
+
|
|
214
|
+
n_placed = 0
|
|
215
|
+
n_skipped_spatial = 0
|
|
216
|
+
n_skipped_temporal = 0
|
|
217
|
+
|
|
218
|
+
start_year = config.temporal_config.start_year
|
|
219
|
+
start_month = config.temporal_config.start_month
|
|
220
|
+
|
|
221
|
+
for i in range(n_rows):
|
|
222
|
+
pgid = pgids[i]
|
|
223
|
+
if pgid < 1 or pgid > n_cells:
|
|
224
|
+
n_skipped_spatial += 1
|
|
225
|
+
continue
|
|
226
|
+
|
|
227
|
+
time_idx = _month_id_to_time_index(
|
|
228
|
+
month_ids[i], start_year, start_month
|
|
229
|
+
)
|
|
230
|
+
if time_idx < 0 or time_idx >= n_steps:
|
|
231
|
+
n_skipped_temporal += 1
|
|
232
|
+
continue
|
|
233
|
+
|
|
234
|
+
pgid_idx = pgid - 1
|
|
235
|
+
row = pgid_idx // ncol
|
|
236
|
+
col = pgid_idx % ncol
|
|
237
|
+
|
|
238
|
+
for feat_idx in range(n_features):
|
|
239
|
+
val = value_arrays[feat_idx][i]
|
|
240
|
+
if not np.isnan(val):
|
|
241
|
+
grid_array[time_idx, row, col, feat_idx] = val
|
|
242
|
+
|
|
243
|
+
n_placed += 1
|
|
244
|
+
|
|
245
|
+
if n_skipped_spatial > 0:
|
|
246
|
+
logger.warning(
|
|
247
|
+
"Skipped %d rows: pgid outside grid bounds",
|
|
248
|
+
n_skipped_spatial,
|
|
249
|
+
)
|
|
250
|
+
if n_skipped_temporal > 0:
|
|
251
|
+
logger.warning(
|
|
252
|
+
"Skipped %d rows: month_id outside temporal range",
|
|
253
|
+
n_skipped_temporal,
|
|
254
|
+
)
|
|
255
|
+
logger.info("Placed %d rows into grid", n_placed)
|
|
256
|
+
|
|
257
|
+
feature_names = [feat.name for feat in config.features]
|
|
258
|
+
|
|
259
|
+
pgids_flat, _, _ = generate_grid(config.grid_config)
|
|
260
|
+
pgids_2d = pgids_flat.reshape(nrow, ncol)
|
|
261
|
+
time_steps = generate_time_steps(config.temporal_config)
|
|
262
|
+
|
|
263
|
+
write_compilation_output(
|
|
264
|
+
grid_array=grid_array,
|
|
265
|
+
pgids_2d=pgids_2d,
|
|
266
|
+
time_steps=time_steps,
|
|
267
|
+
feature_names=feature_names,
|
|
268
|
+
output_dir=config.output_dir,
|
|
269
|
+
ledger_path=config.ledger_path,
|
|
270
|
+
dataset_id=DATASET_ID,
|
|
271
|
+
source_path=config.source_path,
|
|
272
|
+
source_digest=source_digest,
|
|
273
|
+
n_placed=n_placed,
|
|
274
|
+
n_skipped_spatial=n_skipped_spatial,
|
|
275
|
+
n_skipped_temporal=n_skipped_temporal,
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
logger.info(
|
|
279
|
+
"Compiled pre-gridded: shape=%s, features=%s, "
|
|
280
|
+
"output=%s",
|
|
281
|
+
grid_array.shape,
|
|
282
|
+
feature_names,
|
|
283
|
+
config.output_dir,
|
|
284
|
+
)
|
|
285
|
+
finally:
|
|
286
|
+
if grid_array is not None:
|
|
287
|
+
del grid_array
|
|
288
|
+
if os.path.exists(tmp_mmap_path):
|
|
289
|
+
os.unlink(tmp_mmap_path)
|
|
290
|
+
|
|
291
|
+
return config.output_dir
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# datafactory_consolidation -- Architecture
|
|
2
|
+
|
|
3
|
+
## Purpose
|
|
4
|
+
|
|
5
|
+
Lossless consolidation of raw source snapshots into version-aware event stores. Combines multiple vintages (annual releases, candidate versions, .9 consolidated versions) from each data source into a single, append-only, queryable store with bitemporal metadata. Vintage-aware per ADR-017. This is a Layer 2 package in the dependency DAG (ADR-012) implementing the consolidation principles defined in ADR-013.
|
|
6
|
+
|
|
7
|
+
## Responsibility Boundary
|
|
8
|
+
|
|
9
|
+
**Owns:**
|
|
10
|
+
- Source-specific consolidation logic (one consolidator per data source)
|
|
11
|
+
- Append-only event store I/O (write new vintages, query by version/time)
|
|
12
|
+
- Bitemporal metadata: `_source_type` ("annual", "candidate", "dot9"), `_source_version`, `_ingested_at`, `_harvest_digest`, `_harvest_timestamp`
|
|
13
|
+
- Lossless field preservation (no columns dropped)
|
|
14
|
+
- Provenance tracking for consolidation operations
|
|
15
|
+
|
|
16
|
+
**Does NOT own:**
|
|
17
|
+
- Data fetching or harvesting (datafactory_harvester — Layer 1)
|
|
18
|
+
- Survivorship decisions between versions (datafactory_viewpoint — Layer 3)
|
|
19
|
+
- Temporal distribution of summary events (datafactory_viewpoint — Layer 3)
|
|
20
|
+
- Grid placement or aggregation (datafactory_compilation — Layer 4)
|
|
21
|
+
- Choosing which version of an event is "right" (that is an opinion; opinions live in Layer 3)
|
|
22
|
+
|
|
23
|
+
## Dependency Rules
|
|
24
|
+
|
|
25
|
+
**May import:** `datafactory_provenance`
|
|
26
|
+
**Reads filesystem output of:** `datafactory_harvester` (Parquet snapshots in `data/`)
|
|
27
|
+
**Must never import:** `datafactory_priogrid`, `datafactory_harvester`, `datafactory_viewpoint`, `datafactory_compilation`, or any consumer
|
|
28
|
+
|
|
29
|
+
## Package Structure
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
datafactory_consolidation/
|
|
33
|
+
__init__.py # Public API: ConsolidationResult, registry re-exports
|
|
34
|
+
ARCHITECTURE.md # This file
|
|
35
|
+
consolidation_result.py # Frozen result dataclass
|
|
36
|
+
event_store.py # Read/write consolidated Parquet store
|
|
37
|
+
tagging.py # Event source type tagging utilities
|
|
38
|
+
consolidators/
|
|
39
|
+
__init__.py # Registry: register_consolidator, consolidate_source
|
|
40
|
+
ucdp.py # UCDP consolidator: annual + candidate + .9
|
|
41
|
+
acled.py # ACLED consolidator: weekly event snapshots
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Key Concepts
|
|
45
|
+
|
|
46
|
+
| Concept | Description |
|
|
47
|
+
|---------|-------------|
|
|
48
|
+
| Consolidator | Source-specific function that reads raw snapshots and appends to a consolidated store |
|
|
49
|
+
| Consolidated store | Append-only Parquet containing all versions of all events with bitemporal metadata |
|
|
50
|
+
| Registry | Dict-based registry (mirrors harvester/sources pattern) — OCP: add consolidator = add file |
|
|
51
|
+
|
|
52
|
+
## Invariants
|
|
53
|
+
|
|
54
|
+
- **Lossless:** No source fields are dropped during consolidation. Metadata columns are added, never replacing source columns.
|
|
55
|
+
- **Append-only:** Existing records in the consolidated store are never modified or deleted.
|
|
56
|
+
- **Bitemporal:** Every record carries valid time (event dates) and transaction time (ingestion metadata).
|
|
57
|
+
- **Provenance:** Every consolidation operation writes a ledger entry with input/output digests.
|
|
58
|
+
- **Fail-loud:** Consolidation failures are logged and raised (ADR-008). No silent fallbacks.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Consolidation of raw source snapshots into lossless event stores.
|
|
2
|
+
|
|
3
|
+
Combines multiple vintages (annual releases, candidate versions) from
|
|
4
|
+
each data source into a single, append-only, version-aware store.
|
|
5
|
+
No opinions applied — survivorship and temporal distribution belong
|
|
6
|
+
to the viewpoint layer (datafactory_viewpoint).
|
|
7
|
+
|
|
8
|
+
Access specific consolidators via:
|
|
9
|
+
from datafactory_consolidation.consolidators.ucdp import consolidate_ucdp
|
|
10
|
+
|
|
11
|
+
Or use the registry:
|
|
12
|
+
from datafactory_consolidation.consolidators import consolidate_source
|
|
13
|
+
consolidate_source("ucdp", config=...)
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from datafactory_consolidation.consolidation_result import ConsolidationResult
|
|
17
|
+
from datafactory_consolidation.consolidators import (
|
|
18
|
+
consolidate_source,
|
|
19
|
+
list_consolidators,
|
|
20
|
+
register_consolidator,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"ConsolidationResult",
|
|
25
|
+
"consolidate_source",
|
|
26
|
+
"list_consolidators",
|
|
27
|
+
"register_consolidator",
|
|
28
|
+
]
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Structured result from a consolidation operation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class ConsolidationResult:
|
|
11
|
+
"""Immutable result of a consolidation run.
|
|
12
|
+
|
|
13
|
+
Attributes:
|
|
14
|
+
output_path: Path to the consolidated Parquet store.
|
|
15
|
+
n_sources: Number of source files consolidated.
|
|
16
|
+
n_records_total: Total records in the store after consolidation.
|
|
17
|
+
n_records_new: Records added in this run (0 if idempotent re-run).
|
|
18
|
+
output_digest: SHA-256 content digest of the output file.
|
|
19
|
+
n_records_before: Records in the store before this run.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
output_path: Path
|
|
23
|
+
n_sources: int
|
|
24
|
+
n_records_total: int
|
|
25
|
+
n_records_new: int
|
|
26
|
+
output_digest: str
|
|
27
|
+
n_records_before: int
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Pluggable consolidator registry.
|
|
2
|
+
|
|
3
|
+
Each consolidator module registers itself via register_consolidator().
|
|
4
|
+
Consumers call consolidate_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
|
+
__all__ = ["consolidate_source", "list_consolidators", "register_consolidator"]
|
|
13
|
+
|
|
14
|
+
from datafactory_provenance.registry import Registry
|
|
15
|
+
|
|
16
|
+
_registry: Registry[Callable[..., Any]] = Registry("consolidator")
|
|
17
|
+
|
|
18
|
+
register_consolidator = _registry.register
|
|
19
|
+
list_consolidators = _registry.list_entries
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def consolidate_source(name: str, **kwargs: Any) -> Any:
|
|
23
|
+
"""Consolidate data from a registered source.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
name: Consolidator identifier.
|
|
27
|
+
**kwargs: Passed to the consolidator function.
|
|
28
|
+
|
|
29
|
+
Raises:
|
|
30
|
+
KeyError: If the consolidator name is not registered.
|
|
31
|
+
"""
|
|
32
|
+
return _registry.get(name)(**kwargs)
|