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,176 @@
|
|
|
1
|
+
"""Grid array to DataFrame conversion.
|
|
2
|
+
|
|
3
|
+
Converts the canonical [T, H, W, C] grid output to a pandas
|
|
4
|
+
DataFrame with (month_id, priogrid_id) MultiIndex. Supports
|
|
5
|
+
land filtering and configurable month_id encoding.
|
|
6
|
+
|
|
7
|
+
Designed to be extractable: depends only on numpy + pandas.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import logging
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
import pandas as pd
|
|
16
|
+
|
|
17
|
+
from datafactory_adapters.feature_frame import (
|
|
18
|
+
FeatureFrame,
|
|
19
|
+
FrameMetadata,
|
|
20
|
+
SpatialLevel,
|
|
21
|
+
SpatioTemporalIndex,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _compute_month_ids(
|
|
28
|
+
time_steps: np.ndarray,
|
|
29
|
+
epoch: int = 0,
|
|
30
|
+
) -> np.ndarray:
|
|
31
|
+
"""Convert datetime64[M] to integer month_ids.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
time_steps: Array of datetime64[M] values.
|
|
35
|
+
epoch: Base year for month_id computation.
|
|
36
|
+
0 = raw (year*12 + month).
|
|
37
|
+
1980 = VIEWS convention ((year-1980)*12 + month).
|
|
38
|
+
|
|
39
|
+
Returns:
|
|
40
|
+
Integer array of month_ids.
|
|
41
|
+
"""
|
|
42
|
+
months_since_epoch_70 = time_steps.astype(
|
|
43
|
+
"datetime64[M]"
|
|
44
|
+
).astype(int)
|
|
45
|
+
years = 1970 + months_since_epoch_70 // 12
|
|
46
|
+
months = months_since_epoch_70 % 12 + 1
|
|
47
|
+
result: np.ndarray = (years - epoch) * 12 + months
|
|
48
|
+
return result
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _flatten_grid(
|
|
52
|
+
grid: np.ndarray,
|
|
53
|
+
pgids: np.ndarray,
|
|
54
|
+
time_steps: np.ndarray,
|
|
55
|
+
month_id_epoch: int = 0,
|
|
56
|
+
land_pgids: set[int] | None = None,
|
|
57
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
58
|
+
"""Flatten [T, H, W, C] grid to (N, C) with index arrays.
|
|
59
|
+
|
|
60
|
+
Shared by grid_to_dataframe and grid_to_feature_frame.
|
|
61
|
+
|
|
62
|
+
Returns:
|
|
63
|
+
(flat_data, all_month_ids, all_pgids) — each of length N.
|
|
64
|
+
|
|
65
|
+
Raises:
|
|
66
|
+
ValueError: If grid is not 4D, pgids is not 2D, or
|
|
67
|
+
spatial dimensions don't match.
|
|
68
|
+
"""
|
|
69
|
+
from datafactory_adapters._validation import validate_grid_pgids
|
|
70
|
+
|
|
71
|
+
validate_grid_pgids(grid, pgids)
|
|
72
|
+
n_t, n_h, n_w, _ = grid.shape
|
|
73
|
+
month_ids = _compute_month_ids(time_steps, month_id_epoch)
|
|
74
|
+
|
|
75
|
+
flat_data: np.ndarray = grid.reshape(n_t * n_h * n_w, -1)
|
|
76
|
+
pgids_flat = pgids.ravel()
|
|
77
|
+
all_pgids = np.tile(pgids_flat, n_t)
|
|
78
|
+
all_month_ids = np.repeat(month_ids, n_h * n_w)
|
|
79
|
+
|
|
80
|
+
if land_pgids is not None:
|
|
81
|
+
mask = np.isin(all_pgids, list(land_pgids))
|
|
82
|
+
flat_data = flat_data[mask]
|
|
83
|
+
all_pgids = all_pgids[mask]
|
|
84
|
+
all_month_ids = all_month_ids[mask]
|
|
85
|
+
|
|
86
|
+
return flat_data, all_month_ids, all_pgids
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def grid_to_dataframe(
|
|
90
|
+
grid: np.ndarray,
|
|
91
|
+
pgids: np.ndarray,
|
|
92
|
+
time_steps: np.ndarray,
|
|
93
|
+
feature_names: list[str],
|
|
94
|
+
*,
|
|
95
|
+
land_pgids: set[int] | None = None,
|
|
96
|
+
month_id_epoch: int = 0,
|
|
97
|
+
sparse: bool = False,
|
|
98
|
+
) -> pd.DataFrame:
|
|
99
|
+
"""Convert a [T, H, W, C] grid to a DataFrame.
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
grid: Grid array of shape [T, H, W, C].
|
|
103
|
+
pgids: Cell ID array of shape [H, W].
|
|
104
|
+
time_steps: Time array of shape [T] (datetime64[M]).
|
|
105
|
+
feature_names: List of C feature column names.
|
|
106
|
+
land_pgids: Optional set of land cell IDs. If provided,
|
|
107
|
+
only land cells are included (dense). If None, all
|
|
108
|
+
cells are included.
|
|
109
|
+
month_id_epoch: Base year for month_id encoding.
|
|
110
|
+
0 = year*12+month. 1980 = VIEWS convention.
|
|
111
|
+
sparse: If True, keep only non-zero rows. If False
|
|
112
|
+
(default), keep all rows (dense time series).
|
|
113
|
+
|
|
114
|
+
Returns:
|
|
115
|
+
DataFrame with (month_id, priogrid_id) MultiIndex
|
|
116
|
+
and one column per feature.
|
|
117
|
+
"""
|
|
118
|
+
flat_data, all_month_ids, all_pgids = _flatten_grid(
|
|
119
|
+
grid, pgids, time_steps, month_id_epoch, land_pgids
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
if sparse:
|
|
123
|
+
nonzero = flat_data.any(axis=1)
|
|
124
|
+
flat_data = flat_data[nonzero]
|
|
125
|
+
all_pgids = all_pgids[nonzero]
|
|
126
|
+
all_month_ids = all_month_ids[nonzero]
|
|
127
|
+
|
|
128
|
+
index = pd.MultiIndex.from_arrays(
|
|
129
|
+
[all_month_ids, all_pgids],
|
|
130
|
+
names=["month_id", "priogrid_id"],
|
|
131
|
+
)
|
|
132
|
+
df = pd.DataFrame(
|
|
133
|
+
flat_data, index=index, columns=feature_names
|
|
134
|
+
)
|
|
135
|
+
return df.sort_index()
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def grid_to_feature_frame(
|
|
139
|
+
grid: np.ndarray,
|
|
140
|
+
pgids: np.ndarray,
|
|
141
|
+
time_steps: np.ndarray,
|
|
142
|
+
feature_names: list[str],
|
|
143
|
+
*,
|
|
144
|
+
land_pgids: set[int] | None = None,
|
|
145
|
+
month_id_epoch: int = 0,
|
|
146
|
+
metadata: FrameMetadata | None = None,
|
|
147
|
+
) -> FeatureFrame:
|
|
148
|
+
"""Convert a [T, H, W, C] grid to a FeatureFrame.
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
grid: Grid array of shape [T, H, W, C].
|
|
152
|
+
pgids: Cell ID array of shape [H, W].
|
|
153
|
+
time_steps: Time array of shape [T] (datetime64[M]).
|
|
154
|
+
feature_names: List of C feature column names.
|
|
155
|
+
land_pgids: Optional set of land cell IDs for filtering.
|
|
156
|
+
month_id_epoch: Base year for month_id encoding.
|
|
157
|
+
metadata: Optional FrameMetadata for provenance.
|
|
158
|
+
|
|
159
|
+
Returns:
|
|
160
|
+
FeatureFrame with dense land-cell time series.
|
|
161
|
+
"""
|
|
162
|
+
flat_data, all_month_ids, all_pgids = _flatten_grid(
|
|
163
|
+
grid, pgids, time_steps, month_id_epoch, land_pgids
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
index = SpatioTemporalIndex(
|
|
167
|
+
time=all_month_ids,
|
|
168
|
+
unit=all_pgids.astype(np.int32),
|
|
169
|
+
level=SpatialLevel.PGM,
|
|
170
|
+
)
|
|
171
|
+
return FeatureFrame.from_2d(
|
|
172
|
+
y_features_2d=flat_data,
|
|
173
|
+
index=index,
|
|
174
|
+
feature_names=list(feature_names),
|
|
175
|
+
metadata=metadata,
|
|
176
|
+
)
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# datafactory_compilation -- Architecture
|
|
2
|
+
|
|
3
|
+
## Purpose
|
|
4
|
+
|
|
5
|
+
Compilation edge -- reads viewpoint output (Parquet) and grid definition, produces compiled npy arrays with shape `[T, H, W, C]` (time, height, width, channels) plus coordinate metadata and provenance. This is a Layer 4 package in the dependency DAG (ADR-012): it imports from provenance and priogrid, and reads viewpoint output as files.
|
|
6
|
+
|
|
7
|
+
## Responsibility Boundary
|
|
8
|
+
|
|
9
|
+
**Owns:**
|
|
10
|
+
- Reading viewpoint output files (Parquet) from disk
|
|
11
|
+
- Placing events onto the spatiotemporal grid (event-to-cell assignment via `latlon_to_pgid`)
|
|
12
|
+
- Aggregating events per cell-month using declared strategy
|
|
13
|
+
- Producing compiled npy output with sidecar coordinate arrays
|
|
14
|
+
- Computing and recording source + output digests for provenance
|
|
15
|
+
|
|
16
|
+
**Does NOT own:**
|
|
17
|
+
- Data fetching or API interaction (datafactory_harvester)
|
|
18
|
+
- Grid definition or coordinate generation (datafactory_priogrid, but imports its configs)
|
|
19
|
+
- Source-specific parsing logic (reads generic Parquet columns declared in config)
|
|
20
|
+
- Consumer-specific post-processing (consumers read compiled output as files)
|
|
21
|
+
|
|
22
|
+
## Dependency Rules
|
|
23
|
+
|
|
24
|
+
**May import:** `datafactory_provenance`, `datafactory_priogrid` (for GridConfig, TemporalConfig, coordinate arrays), numpy, pyarrow
|
|
25
|
+
**Must never import:** `datafactory_harvester`, `datafactory_consolidation`, `datafactory_viewpoint`, or any consumer
|
|
26
|
+
**Data coupling:** Reads viewpoint output as FILES on disk. The filesystem is the decoupling boundary (ADR-012).
|
|
27
|
+
|
|
28
|
+
## Package Structure
|
|
29
|
+
|
|
30
|
+
```
|
|
31
|
+
datafactory_compilation/
|
|
32
|
+
__init__.py -- public API: CompilationConfig, compile_grid, get_strategy
|
|
33
|
+
compilation_config.py -- CompilationConfig (frozen, validated)
|
|
34
|
+
aggregation.py -- built-in aggregation functions (count, sum_field, max_field) + registry
|
|
35
|
+
grid_compilation.py -- compile_grid (main function), event placement, aggregation
|
|
36
|
+
output.py -- compiled grid output writing (npy + sidecars + provenance)
|
|
37
|
+
pregridded_compilation.py -- compilation for pre-gridded sources (GHS-POP, GHS-BUILT-S)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Key Concepts
|
|
41
|
+
|
|
42
|
+
| Concept | Description |
|
|
43
|
+
|---------|-------------|
|
|
44
|
+
| CompilationConfig | Frozen dataclass: source path, grid/temporal configs, feature specs (name + strategy pairs), output dir, column mappings. Validated in `__post_init__`. |
|
|
45
|
+
| Aggregation strategies | Plain functions `(list[dict], str) -> float` registered by name. Built-in: `count`, `sum_field`, `max_field`. The second argument is the event field name to aggregate (configurable via `FeatureSpec.value_field`). `sum_best`/`max_best` are backward-compatible aliases. Adding a strategy means adding a function (OCP). |
|
|
46
|
+
| compile_grid | Main function: reads Parquet -> places events via `latlon_to_pgid` -> aggregates per (cell, month) -> writes npy + sidecars + provenance. Deterministic. |
|
|
47
|
+
| FeatureSpec | Frozen dataclass: `name`, `strategy`, optional `filter` dict, `value_field` (default `"best"`). Filter enables per-feature disaggregation (e.g., `{"type_of_violence": 1}` for state-based only). `value_field` controls which event field is aggregated. Declared in config, never inferred (ADR-003). |
|
|
48
|
+
|
|
49
|
+
## Invariants
|
|
50
|
+
- **Single-writer access assumed.** No concurrent operations supported (see technical_risk_register_resolved.md C-16)
|
|
51
|
+
|
|
52
|
+
- **Dimension order:** Always `[T, H, W, C]` — time, height (rows), width (columns), channels (features). Canonical z-stack layout.
|
|
53
|
+
- **Coordinate sidecars:** `pgids.npy` (int32, shape `[H, W]`), `time_steps.npy` (datetime64[M]), `feature_names.json` always shipped alongside `grid.npy`
|
|
54
|
+
- **Deterministic:** Same inputs + same config = bit-identical output + identical SHA-256 digest (NF-2)
|
|
55
|
+
- **Source digest computed:** SHA-256 of source file bytes computed and recorded in provenance (not cross-checked against an existing ledger -- the compiler records, it does not verify)
|
|
56
|
+
- **Feature list declared:** Features come from CompilationConfig, never inferred from Parquet columns (ADR-003)
|
|
57
|
+
- **Provenance entry:** Written for every compilation, linking source digest + output digest
|
|
58
|
+
- **Column mapping is source-agnostic:** The compiler reads lat/lon/date columns declared in config, not hardcoded field names. The aggregation field is configurable via `FeatureSpec.value_field` (default `"best"`).
|
|
59
|
+
- **All error paths log before raising** (ADR-008)
|
|
60
|
+
|
|
61
|
+
## Intent Contracts
|
|
62
|
+
|
|
63
|
+
- `CompilationConfig` -- governs compilation behavior, feature declarations, column mappings (CIC at `docs/CICs/CompilationConfig.md`)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Compilation node -- places event data onto the spatiotemporal grid.
|
|
2
|
+
|
|
3
|
+
Reads viewpoint output as files. Produces populated npy arrays.
|
|
4
|
+
Tracks provenance: source digests + compilation config -> output digest.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from datafactory_compilation.aggregation import get_strategy
|
|
8
|
+
from datafactory_compilation.compilation_config import (
|
|
9
|
+
CompilationConfig,
|
|
10
|
+
FeatureSpec,
|
|
11
|
+
)
|
|
12
|
+
from datafactory_compilation.conservation import (
|
|
13
|
+
PlacementAccounting,
|
|
14
|
+
assert_placement_conservation,
|
|
15
|
+
)
|
|
16
|
+
from datafactory_compilation.grid_compilation import compile_grid
|
|
17
|
+
from datafactory_compilation.preflight import (
|
|
18
|
+
check_disk_space,
|
|
19
|
+
estimate_grid_bytes,
|
|
20
|
+
)
|
|
21
|
+
from datafactory_compilation.pregridded_compilation import (
|
|
22
|
+
PregriddedCompilationConfig,
|
|
23
|
+
PregriddedFeatureSpec,
|
|
24
|
+
compile_pregridded,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"CompilationConfig",
|
|
29
|
+
"FeatureSpec",
|
|
30
|
+
"PlacementAccounting",
|
|
31
|
+
"PregriddedCompilationConfig",
|
|
32
|
+
"PregriddedFeatureSpec",
|
|
33
|
+
"assert_placement_conservation",
|
|
34
|
+
"check_disk_space",
|
|
35
|
+
"compile_grid",
|
|
36
|
+
"compile_pregridded",
|
|
37
|
+
"estimate_grid_bytes",
|
|
38
|
+
"get_strategy",
|
|
39
|
+
]
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Built-in aggregation strategies for grid compilation.
|
|
2
|
+
|
|
3
|
+
Each strategy is a plain function: (list[dict], str) -> float.
|
|
4
|
+
Strategies aggregate events within a single (cell, month) bin.
|
|
5
|
+
The second argument is the event field name to aggregate.
|
|
6
|
+
Adding a new strategy means adding a function here -- no changes
|
|
7
|
+
to the compiler or config modules (OCP).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
|
|
14
|
+
from datafactory_provenance.registry import Registry
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"count",
|
|
18
|
+
"sum_field",
|
|
19
|
+
"max_field",
|
|
20
|
+
"get_strategy",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
_registry: Registry[Callable[[list[dict], str], float]] = Registry(
|
|
24
|
+
"aggregation strategy"
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@_registry.decorator("count")
|
|
29
|
+
def count(events: list[dict], field: str = "best") -> float:
|
|
30
|
+
"""Count of events in this cell-month."""
|
|
31
|
+
return float(len(events))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@_registry.decorator("sum_field")
|
|
35
|
+
def sum_field(events: list[dict], field: str = "best") -> float:
|
|
36
|
+
"""Sum of field values in this cell-month."""
|
|
37
|
+
return float(sum(e.get(field, 0) or 0 for e in events))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@_registry.decorator("max_field")
|
|
41
|
+
def max_field(events: list[dict], field: str = "best") -> float:
|
|
42
|
+
"""Maximum field value in this cell-month."""
|
|
43
|
+
values = [e.get(field, 0) or 0 for e in events]
|
|
44
|
+
return float(max(values)) if values else 0.0
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
# Backward-compatible aliases — old registry keys still resolve
|
|
48
|
+
_registry.register("sum_best", sum_field)
|
|
49
|
+
_registry.register("max_best", max_field)
|
|
50
|
+
|
|
51
|
+
# Backward-compatible Python names
|
|
52
|
+
sum_best = sum_field
|
|
53
|
+
max_best = max_field
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def get_strategy(
|
|
57
|
+
name: str,
|
|
58
|
+
) -> Callable[[list[dict], str], float]:
|
|
59
|
+
"""Look up a strategy by name.
|
|
60
|
+
|
|
61
|
+
Raises:
|
|
62
|
+
KeyError: If the strategy name is not registered.
|
|
63
|
+
"""
|
|
64
|
+
return _registry.get(name)
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Compilation configuration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, ClassVar
|
|
9
|
+
|
|
10
|
+
from datafactory_priogrid.grid_config import DEFAULT_GRID_CONFIG, GridConfig
|
|
11
|
+
from datafactory_priogrid.temporal_config import TemporalConfig
|
|
12
|
+
from datafactory_priogrid.temporal_generator import DEFAULT_TEMPORAL_CONFIG
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class FeatureSpec:
|
|
19
|
+
"""A single compiled feature: name, strategy, and optional filter.
|
|
20
|
+
|
|
21
|
+
The filter dict maps event field names to required values.
|
|
22
|
+
Only events matching ALL filter conditions are aggregated.
|
|
23
|
+
Example: ``FeatureSpec("ged_sb_count", "count", {"type_of_violence": 1})``
|
|
24
|
+
counts only state-based conflict events (UCDP type 1).
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
name: str
|
|
28
|
+
strategy: str
|
|
29
|
+
filter: dict[str, Any] = field(default_factory=dict)
|
|
30
|
+
value_field: str = "best"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class CompilationConfig:
|
|
35
|
+
"""Configuration for compiling source events onto the spatiotemporal grid.
|
|
36
|
+
|
|
37
|
+
Features are declared as FeatureSpec instances. Each feature
|
|
38
|
+
specifies a name, aggregation strategy, and optional filter
|
|
39
|
+
for per-field disaggregation. The compiler never infers
|
|
40
|
+
features from Parquet columns (ADR-003).
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
# Source
|
|
44
|
+
source_path: Path
|
|
45
|
+
|
|
46
|
+
# Grid
|
|
47
|
+
grid_config: GridConfig = field(
|
|
48
|
+
default_factory=lambda: DEFAULT_GRID_CONFIG
|
|
49
|
+
)
|
|
50
|
+
temporal_config: TemporalConfig = field(
|
|
51
|
+
default_factory=lambda: DEFAULT_TEMPORAL_CONFIG
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
# Features to compute
|
|
55
|
+
features: tuple[FeatureSpec, ...] = (
|
|
56
|
+
FeatureSpec("event_count", "count"),
|
|
57
|
+
FeatureSpec("fatalities", "sum_field"),
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
# Output
|
|
61
|
+
output_dir: Path = Path("data/compiled")
|
|
62
|
+
ledger_path: Path = Path("provenance/compiler/compilation_ledger.jsonl")
|
|
63
|
+
|
|
64
|
+
# Column mapping (source Parquet field names)
|
|
65
|
+
lat_field: str = "latitude"
|
|
66
|
+
lon_field: str = "longitude"
|
|
67
|
+
date_field: str = "date_start"
|
|
68
|
+
|
|
69
|
+
# Output array parameters
|
|
70
|
+
output_dtype: str = "float32"
|
|
71
|
+
fill_value: float = 0.0
|
|
72
|
+
|
|
73
|
+
_ALLOWED_DTYPES: ClassVar[frozenset[str]] = frozenset({
|
|
74
|
+
"float16", "float32", "float64", "int32", "int64",
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
def __post_init__(self) -> None:
|
|
78
|
+
if not self.features:
|
|
79
|
+
err_msg = "features must be non-empty"
|
|
80
|
+
logger.error(err_msg)
|
|
81
|
+
raise ValueError(err_msg)
|
|
82
|
+
names = [f.name for f in self.features]
|
|
83
|
+
if len(names) != len(set(names)):
|
|
84
|
+
dupes = sorted({n for n in names if names.count(n) > 1})
|
|
85
|
+
err_msg = f"duplicate feature names: {dupes}"
|
|
86
|
+
logger.error(err_msg)
|
|
87
|
+
raise ValueError(err_msg)
|
|
88
|
+
if self.output_dtype not in self._ALLOWED_DTYPES:
|
|
89
|
+
err_msg = (
|
|
90
|
+
f"output_dtype must be one of "
|
|
91
|
+
f"{sorted(self._ALLOWED_DTYPES)}, "
|
|
92
|
+
f"got {self.output_dtype!r}"
|
|
93
|
+
)
|
|
94
|
+
logger.error(err_msg)
|
|
95
|
+
raise ValueError(err_msg)
|
|
96
|
+
# source_path is validated at compile time (FileNotFoundError),
|
|
97
|
+
# not at config construction time — the file may not exist yet.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""ADR-040 count conservation for the compilation layer.
|
|
2
|
+
|
|
3
|
+
Invariant 1: placed + skipped_spatial + skipped_temporal = input_rows.
|
|
4
|
+
|
|
5
|
+
Uses if/raise RuntimeError — assert is stripped with -O, which is
|
|
6
|
+
unacceptable for a Tier 2 silent-corruption guard.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import dataclasses
|
|
12
|
+
|
|
13
|
+
__all__ = ["PlacementAccounting", "assert_placement_conservation"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclasses.dataclass(frozen=True)
|
|
17
|
+
class PlacementAccounting:
|
|
18
|
+
"""Immutable record of event placement outcomes."""
|
|
19
|
+
|
|
20
|
+
n_input: int
|
|
21
|
+
n_placed: int
|
|
22
|
+
n_skipped_spatial: int
|
|
23
|
+
n_skipped_temporal: int
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def assert_placement_conservation(acc: PlacementAccounting) -> None:
|
|
27
|
+
"""Verify placed + skipped_spatial + skipped_temporal = input_rows."""
|
|
28
|
+
total = acc.n_placed + acc.n_skipped_spatial + acc.n_skipped_temporal
|
|
29
|
+
if total != acc.n_input:
|
|
30
|
+
raise RuntimeError(
|
|
31
|
+
f"Count conservation violated (ADR-040): "
|
|
32
|
+
f"{acc.n_placed} placed + "
|
|
33
|
+
f"{acc.n_skipped_spatial} spatial + "
|
|
34
|
+
f"{acc.n_skipped_temporal} temporal "
|
|
35
|
+
f"= {total} != {acc.n_input} input rows"
|
|
36
|
+
)
|