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,203 @@
|
|
|
1
|
+
"""Spatial distribution strategy registry for viewpoint building.
|
|
2
|
+
|
|
3
|
+
Each strategy is a function: (dict, SpatialWeightMap) -> list[dict].
|
|
4
|
+
Given a single event and a precomputed weight map, the strategy
|
|
5
|
+
returns one or more rows depending on whether the event has low
|
|
6
|
+
spatial precision (where_prec >= 4).
|
|
7
|
+
|
|
8
|
+
Adding a new strategy means adding a function here with the
|
|
9
|
+
@_registry.decorator — no changes to the builder (OCP).
|
|
10
|
+
|
|
11
|
+
Mirrors temporal_distribution.py for the spatial dimension.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import logging
|
|
17
|
+
import math
|
|
18
|
+
from collections.abc import Callable
|
|
19
|
+
|
|
20
|
+
from datafactory_provenance.registry import Registry
|
|
21
|
+
from datafactory_viewpoint.spatial_weights import SpatialWeightMap
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
_registry: Registry[
|
|
26
|
+
Callable[[dict, SpatialWeightMap], list[dict]]
|
|
27
|
+
] = Registry("spatial distribution strategy")
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"get_spatial_distribution",
|
|
31
|
+
"proportional",
|
|
32
|
+
"passthrough",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
_SPATIAL_THRESHOLD: int = 4
|
|
36
|
+
_COUNTRY_LEVEL: int = 6
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def get_spatial_distribution(
|
|
40
|
+
name: str,
|
|
41
|
+
) -> Callable[[dict, SpatialWeightMap], list[dict]]:
|
|
42
|
+
"""Look up a spatial distribution strategy by name.
|
|
43
|
+
|
|
44
|
+
Raises:
|
|
45
|
+
KeyError: If the strategy name is not registered.
|
|
46
|
+
"""
|
|
47
|
+
return _registry.get(name)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _distribute_value(
|
|
51
|
+
value: int,
|
|
52
|
+
weights: dict[int, float],
|
|
53
|
+
) -> dict[int, int]:
|
|
54
|
+
"""Distribute an integer value across cells by weight.
|
|
55
|
+
|
|
56
|
+
Uses floor for all cells, then adds the integer remainder
|
|
57
|
+
to the cell with the highest weight (tie-break: lowest pgid).
|
|
58
|
+
Guarantees sum(output) == value.
|
|
59
|
+
"""
|
|
60
|
+
if not weights:
|
|
61
|
+
return {}
|
|
62
|
+
|
|
63
|
+
if value == 0:
|
|
64
|
+
return dict.fromkeys(weights, 0)
|
|
65
|
+
|
|
66
|
+
allocated: dict[int, int] = {}
|
|
67
|
+
for pgid, share in weights.items():
|
|
68
|
+
allocated[pgid] = int(math.floor(value * share))
|
|
69
|
+
|
|
70
|
+
remainder = value - sum(allocated.values())
|
|
71
|
+
|
|
72
|
+
if remainder > 0:
|
|
73
|
+
ranked = sorted(
|
|
74
|
+
weights.items(),
|
|
75
|
+
key=lambda item: (-item[1], item[0]),
|
|
76
|
+
)
|
|
77
|
+
for i in range(remainder):
|
|
78
|
+
pgid = ranked[i % len(ranked)][0]
|
|
79
|
+
allocated[pgid] += 1
|
|
80
|
+
|
|
81
|
+
return allocated
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _get_polygon_weights(
|
|
85
|
+
event: dict,
|
|
86
|
+
weight_map: SpatialWeightMap,
|
|
87
|
+
) -> tuple[dict[int, float] | None, list[int] | None, int | None]:
|
|
88
|
+
"""Determine the target polygon and its weights for an event.
|
|
89
|
+
|
|
90
|
+
Returns (weights, all_cells, gaul_code) or (None, None, None)
|
|
91
|
+
if the polygon cannot be determined.
|
|
92
|
+
"""
|
|
93
|
+
pgid = event.get("priogrid_gid")
|
|
94
|
+
if pgid is None or pgid == 0:
|
|
95
|
+
logger.warning(
|
|
96
|
+
"Event %s has no priogrid_gid, passing through",
|
|
97
|
+
event.get("id"),
|
|
98
|
+
)
|
|
99
|
+
return None, None, None
|
|
100
|
+
|
|
101
|
+
pgid_int = int(pgid)
|
|
102
|
+
where_prec = event.get("where_prec", 1)
|
|
103
|
+
|
|
104
|
+
if where_prec >= _COUNTRY_LEVEL:
|
|
105
|
+
gaul_code = weight_map.pgid_to_gaul0.get(pgid_int)
|
|
106
|
+
if gaul_code is None:
|
|
107
|
+
logger.warning(
|
|
108
|
+
"Event %s centroid pgid %d has no gaul0 code "
|
|
109
|
+
"(water/unassigned), passing through",
|
|
110
|
+
event.get("id"),
|
|
111
|
+
pgid_int,
|
|
112
|
+
)
|
|
113
|
+
return None, None, None
|
|
114
|
+
weights = weight_map.country_weights.get(gaul_code)
|
|
115
|
+
all_cells = weight_map.country_all_cells.get(gaul_code)
|
|
116
|
+
return weights, all_cells, gaul_code
|
|
117
|
+
|
|
118
|
+
gaul_code = weight_map.pgid_to_gaul1.get(pgid_int)
|
|
119
|
+
if gaul_code is None:
|
|
120
|
+
logger.warning(
|
|
121
|
+
"Event %s centroid pgid %d has no gaul1 code "
|
|
122
|
+
"(water/unassigned), passing through",
|
|
123
|
+
event.get("id"),
|
|
124
|
+
pgid_int,
|
|
125
|
+
)
|
|
126
|
+
return None, None, None
|
|
127
|
+
weights = weight_map.admin1_weights.get(gaul_code)
|
|
128
|
+
all_cells = weight_map.admin1_all_cells.get(gaul_code)
|
|
129
|
+
return weights, all_cells, gaul_code
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@_registry.decorator("proportional")
|
|
133
|
+
def proportional(
|
|
134
|
+
event: dict,
|
|
135
|
+
weight_map: SpatialWeightMap,
|
|
136
|
+
) -> list[dict]:
|
|
137
|
+
"""Distribute imprecise events proportionally to well-located fatalities.
|
|
138
|
+
|
|
139
|
+
For events with where_prec >= 4: determines the target polygon
|
|
140
|
+
(admin-1 for 4/5, country for 6+), distributes best/low/high
|
|
141
|
+
proportionally across the polygon's cells using the precomputed
|
|
142
|
+
weight map. Conserves totals exactly via floor+remainder.
|
|
143
|
+
|
|
144
|
+
For where_prec <= 3 or when the polygon cannot be determined:
|
|
145
|
+
returns the event unchanged.
|
|
146
|
+
"""
|
|
147
|
+
where_prec = event.get("where_prec", 1)
|
|
148
|
+
if where_prec < _SPATIAL_THRESHOLD:
|
|
149
|
+
return [event]
|
|
150
|
+
|
|
151
|
+
weights, all_cells, gaul_code = _get_polygon_weights(
|
|
152
|
+
event, weight_map,
|
|
153
|
+
)
|
|
154
|
+
if weights is None and all_cells is None:
|
|
155
|
+
return [event]
|
|
156
|
+
|
|
157
|
+
if weights is None or len(weights) == 0:
|
|
158
|
+
if all_cells and len(all_cells) > 0:
|
|
159
|
+
weights = {
|
|
160
|
+
pgid: 1.0 / len(all_cells) for pgid in all_cells
|
|
161
|
+
}
|
|
162
|
+
else:
|
|
163
|
+
return [event]
|
|
164
|
+
|
|
165
|
+
best = int(event.get("best") or 0)
|
|
166
|
+
low = int(event.get("low") or 0)
|
|
167
|
+
high = int(event.get("high") or 0)
|
|
168
|
+
|
|
169
|
+
best_alloc = _distribute_value(best, weights)
|
|
170
|
+
low_alloc = _distribute_value(low, weights)
|
|
171
|
+
high_alloc = _distribute_value(high, weights)
|
|
172
|
+
|
|
173
|
+
original_pgid = event.get("priogrid_gid")
|
|
174
|
+
n_cells = len(weights)
|
|
175
|
+
|
|
176
|
+
rows: list[dict] = []
|
|
177
|
+
for pgid in sorted(weights.keys()):
|
|
178
|
+
row = {
|
|
179
|
+
**event,
|
|
180
|
+
"priogrid_gid": pgid,
|
|
181
|
+
"best": best_alloc[pgid],
|
|
182
|
+
"low": low_alloc[pgid],
|
|
183
|
+
"high": high_alloc[pgid],
|
|
184
|
+
"_spatial_distributed": True,
|
|
185
|
+
"_spatial_source_pgid": original_pgid,
|
|
186
|
+
"_spatial_polygon_code": gaul_code,
|
|
187
|
+
"_spatial_n_cells": n_cells,
|
|
188
|
+
}
|
|
189
|
+
rows.append(row)
|
|
190
|
+
|
|
191
|
+
return rows
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@_registry.decorator("passthrough")
|
|
195
|
+
def passthrough(
|
|
196
|
+
event: dict,
|
|
197
|
+
weight_map: SpatialWeightMap, # noqa: ARG001
|
|
198
|
+
) -> list[dict]:
|
|
199
|
+
"""Return event unchanged regardless of where_prec.
|
|
200
|
+
|
|
201
|
+
Legacy / production-parity behavior: no spatial distribution.
|
|
202
|
+
"""
|
|
203
|
+
return [event]
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""Spatial weight map for proportional distribution of imprecise events.
|
|
2
|
+
|
|
3
|
+
Computes per-cell fatality weights within admin-1 and country polygons
|
|
4
|
+
using GAUL crosswalk parquets and well-located events from the
|
|
5
|
+
consolidated UCDP store. Used by spatial_distribution.py strategies.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
import pyarrow as pa
|
|
15
|
+
import pyarrow.compute as pc
|
|
16
|
+
import pyarrow.parquet as pq
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
__all__ = ["SpatialWeightMap", "build_spatial_weight_map"]
|
|
21
|
+
|
|
22
|
+
_WELL_LOCATED_MAX: int = 3
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class SpatialWeightMap:
|
|
27
|
+
"""Precomputed cell-level fatality weights within GAUL polygons.
|
|
28
|
+
|
|
29
|
+
For each admin-1 and country polygon, stores the proportional
|
|
30
|
+
share of well-located fatalities in each cell. Shares sum to
|
|
31
|
+
1.0 per polygon. Used by spatial distribution strategies to
|
|
32
|
+
allocate imprecise-event deaths.
|
|
33
|
+
|
|
34
|
+
Attributes:
|
|
35
|
+
admin1_weights: gaul1_code -> {pgid: share}. Only polygons
|
|
36
|
+
with nonzero well-located fatalities.
|
|
37
|
+
country_weights: gaul0_code -> {pgid: share}. Same rule.
|
|
38
|
+
pgid_to_gaul1: pgid -> gaul1_code for all valid cells.
|
|
39
|
+
pgid_to_gaul0: pgid -> gaul0_code for all valid cells.
|
|
40
|
+
admin1_all_cells: gaul1_code -> [pgids] for uniform fallback.
|
|
41
|
+
country_all_cells: gaul0_code -> [pgids] for uniform fallback.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
admin1_weights: dict[int, dict[int, float]] = field(
|
|
45
|
+
default_factory=dict,
|
|
46
|
+
)
|
|
47
|
+
country_weights: dict[int, dict[int, float]] = field(
|
|
48
|
+
default_factory=dict,
|
|
49
|
+
)
|
|
50
|
+
pgid_to_gaul1: dict[int, int] = field(default_factory=dict)
|
|
51
|
+
pgid_to_gaul0: dict[int, int] = field(default_factory=dict)
|
|
52
|
+
admin1_all_cells: dict[int, list[int]] = field(
|
|
53
|
+
default_factory=dict,
|
|
54
|
+
)
|
|
55
|
+
country_all_cells: dict[int, list[int]] = field(
|
|
56
|
+
default_factory=dict,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _load_gaul_crosswalk(path: Path) -> dict[int, int]:
|
|
61
|
+
"""Load a GAUL crosswalk parquet (gid, value) -> {pgid: gaul_code}.
|
|
62
|
+
|
|
63
|
+
Filters out cells with value == -1 (unassigned / water).
|
|
64
|
+
"""
|
|
65
|
+
if not path.exists():
|
|
66
|
+
err_msg = f"GAUL crosswalk not found: {path}"
|
|
67
|
+
logger.error(err_msg)
|
|
68
|
+
raise FileNotFoundError(err_msg)
|
|
69
|
+
|
|
70
|
+
table = pq.read_table(path)
|
|
71
|
+
gids = table.column("gid").to_pylist()
|
|
72
|
+
values = table.column("value").to_pylist()
|
|
73
|
+
|
|
74
|
+
mapping: dict[int, int] = {}
|
|
75
|
+
for gid, val in zip(gids, values, strict=True):
|
|
76
|
+
if val is None or val == -1:
|
|
77
|
+
continue
|
|
78
|
+
mapping[int(gid)] = int(val)
|
|
79
|
+
|
|
80
|
+
return mapping
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _build_all_cells(
|
|
84
|
+
pgid_to_gaul: dict[int, int],
|
|
85
|
+
) -> dict[int, list[int]]:
|
|
86
|
+
"""Invert pgid->gaul_code to gaul_code->[pgids]."""
|
|
87
|
+
result: dict[int, list[int]] = {}
|
|
88
|
+
for pgid, gaul_code in pgid_to_gaul.items():
|
|
89
|
+
if gaul_code not in result:
|
|
90
|
+
result[gaul_code] = []
|
|
91
|
+
result[gaul_code].append(pgid)
|
|
92
|
+
for cells in result.values():
|
|
93
|
+
cells.sort()
|
|
94
|
+
return result
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _compute_weights(
|
|
98
|
+
cell_fatalities: dict[int, float],
|
|
99
|
+
pgid_to_gaul: dict[int, int],
|
|
100
|
+
) -> dict[int, dict[int, float]]:
|
|
101
|
+
"""Compute proportional weights per polygon from cell fatalities.
|
|
102
|
+
|
|
103
|
+
For each polygon, the share of each cell is:
|
|
104
|
+
cell_share = cell_fatalities / polygon_total_fatalities
|
|
105
|
+
|
|
106
|
+
Only polygons with nonzero total fatalities are included.
|
|
107
|
+
"""
|
|
108
|
+
polygon_totals: dict[int, float] = {}
|
|
109
|
+
polygon_cells: dict[int, dict[int, float]] = {}
|
|
110
|
+
|
|
111
|
+
for pgid, deaths in cell_fatalities.items():
|
|
112
|
+
gaul_code = pgid_to_gaul.get(pgid)
|
|
113
|
+
if gaul_code is None:
|
|
114
|
+
continue
|
|
115
|
+
if gaul_code not in polygon_totals:
|
|
116
|
+
polygon_totals[gaul_code] = 0.0
|
|
117
|
+
polygon_cells[gaul_code] = {}
|
|
118
|
+
polygon_totals[gaul_code] += deaths
|
|
119
|
+
polygon_cells[gaul_code][pgid] = (
|
|
120
|
+
polygon_cells[gaul_code].get(pgid, 0.0) + deaths
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
weights: dict[int, dict[int, float]] = {}
|
|
124
|
+
for gaul_code, total in polygon_totals.items():
|
|
125
|
+
if total <= 0:
|
|
126
|
+
continue
|
|
127
|
+
weights[gaul_code] = {
|
|
128
|
+
pgid: deaths / total
|
|
129
|
+
for pgid, deaths in polygon_cells[gaul_code].items()
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
return weights
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def build_spatial_weight_map(
|
|
136
|
+
table: pa.Table,
|
|
137
|
+
gaul1_path: Path,
|
|
138
|
+
gaul0_path: Path,
|
|
139
|
+
) -> SpatialWeightMap:
|
|
140
|
+
"""Build a spatial weight map from the consolidated event table.
|
|
141
|
+
|
|
142
|
+
Scans well-located events (where_prec <= 3), aggregates deaths
|
|
143
|
+
by priogrid_gid, then cross-references with GAUL crosswalks to
|
|
144
|
+
produce per-cell proportional weights within each polygon.
|
|
145
|
+
|
|
146
|
+
Args:
|
|
147
|
+
table: Consolidated event table (after stale version filtering).
|
|
148
|
+
gaul1_path: Path to gaul1_code.parquet (pgid -> admin-1 code).
|
|
149
|
+
gaul0_path: Path to gaul0_code.parquet (pgid -> country code).
|
|
150
|
+
|
|
151
|
+
Returns:
|
|
152
|
+
SpatialWeightMap with precomputed weights.
|
|
153
|
+
|
|
154
|
+
Raises:
|
|
155
|
+
FileNotFoundError: If a GAUL crosswalk parquet is missing.
|
|
156
|
+
"""
|
|
157
|
+
pgid_to_gaul1 = _load_gaul_crosswalk(gaul1_path)
|
|
158
|
+
pgid_to_gaul0 = _load_gaul_crosswalk(gaul0_path)
|
|
159
|
+
|
|
160
|
+
admin1_all_cells = _build_all_cells(pgid_to_gaul1)
|
|
161
|
+
country_all_cells = _build_all_cells(pgid_to_gaul0)
|
|
162
|
+
|
|
163
|
+
logger.info(
|
|
164
|
+
"GAUL crosswalks: %d admin-1 cells, %d country cells",
|
|
165
|
+
len(pgid_to_gaul1),
|
|
166
|
+
len(pgid_to_gaul0),
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
well_located_mask = pc.less_equal(
|
|
170
|
+
table.column("where_prec"),
|
|
171
|
+
pa.scalar(_WELL_LOCATED_MAX, type=pa.int64()),
|
|
172
|
+
)
|
|
173
|
+
well_located = table.filter(well_located_mask)
|
|
174
|
+
|
|
175
|
+
pgids = well_located.column("priogrid_gid").to_pylist()
|
|
176
|
+
bests = well_located.column("best").to_pylist()
|
|
177
|
+
|
|
178
|
+
cell_fatalities: dict[int, float] = {}
|
|
179
|
+
for pgid, best in zip(pgids, bests, strict=True):
|
|
180
|
+
if pgid is None:
|
|
181
|
+
continue
|
|
182
|
+
pgid_int = int(pgid)
|
|
183
|
+
cell_fatalities[pgid_int] = (
|
|
184
|
+
cell_fatalities.get(pgid_int, 0.0) + (best or 0)
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
admin1_weights = _compute_weights(cell_fatalities, pgid_to_gaul1)
|
|
188
|
+
country_weights = _compute_weights(cell_fatalities, pgid_to_gaul0)
|
|
189
|
+
|
|
190
|
+
logger.info(
|
|
191
|
+
"Spatial weight map: %d admin-1 polygons with weights, "
|
|
192
|
+
"%d country polygons with weights, from %d well-located "
|
|
193
|
+
"events across %d cells",
|
|
194
|
+
len(admin1_weights),
|
|
195
|
+
len(country_weights),
|
|
196
|
+
len(well_located),
|
|
197
|
+
len(cell_fatalities),
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
return SpatialWeightMap(
|
|
201
|
+
admin1_weights=admin1_weights,
|
|
202
|
+
country_weights=country_weights,
|
|
203
|
+
pgid_to_gaul1=pgid_to_gaul1,
|
|
204
|
+
pgid_to_gaul0=pgid_to_gaul0,
|
|
205
|
+
admin1_all_cells=admin1_all_cells,
|
|
206
|
+
country_all_cells=country_all_cells,
|
|
207
|
+
)
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Survivorship strategy registry for viewpoint building.
|
|
2
|
+
|
|
3
|
+
Each strategy is a function: list[dict] -> dict.
|
|
4
|
+
Given all versions of the same event (same id, different source
|
|
5
|
+
versions), the strategy picks the winning record.
|
|
6
|
+
|
|
7
|
+
Adding a new strategy means adding a function here with the
|
|
8
|
+
@_registry.decorator — no changes to the builder (OCP).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import logging
|
|
14
|
+
from collections.abc import Callable
|
|
15
|
+
|
|
16
|
+
from datafactory_provenance.registry import Registry
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
_registry: Registry[Callable[[list[dict]], dict]] = Registry(
|
|
21
|
+
"survivorship strategy"
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
__all__ = ["get_survivorship", "annual_wins", "dot9_wins"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def get_survivorship(name: str) -> Callable[[list[dict]], dict]:
|
|
28
|
+
"""Look up a survivorship strategy by name.
|
|
29
|
+
|
|
30
|
+
Raises:
|
|
31
|
+
KeyError: If the strategy name is not registered.
|
|
32
|
+
"""
|
|
33
|
+
return _registry.get(name)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _parse_version(version_str: str) -> tuple[int, ...]:
|
|
37
|
+
"""Parse a version string into a tuple of ints for comparison.
|
|
38
|
+
|
|
39
|
+
Examples: "25.1" → (25, 1), "25.0.12" → (25, 0, 12)
|
|
40
|
+
|
|
41
|
+
Non-numeric versions return (0,) with a warning — they sort
|
|
42
|
+
below all numeric versions, ensuring unknown formats are never
|
|
43
|
+
preferred in survivorship strategies.
|
|
44
|
+
"""
|
|
45
|
+
parts = version_str.split(".")
|
|
46
|
+
try:
|
|
47
|
+
return tuple(int(p) for p in parts)
|
|
48
|
+
except ValueError:
|
|
49
|
+
logger.warning(
|
|
50
|
+
"Non-numeric version string %r, "
|
|
51
|
+
"treating as lowest priority",
|
|
52
|
+
version_str,
|
|
53
|
+
)
|
|
54
|
+
return (0,)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@_registry.decorator("annual_wins")
|
|
58
|
+
def annual_wins(versions: list[dict]) -> dict:
|
|
59
|
+
"""Pick annual if available, else latest candidate by version.
|
|
60
|
+
|
|
61
|
+
Survivorship rule per ADR-015: annual is authoritative for
|
|
62
|
+
months it covers. For the trailing window, the latest
|
|
63
|
+
candidate version wins.
|
|
64
|
+
"""
|
|
65
|
+
annuals = [
|
|
66
|
+
v for v in versions if v.get("_source_type") == "annual"
|
|
67
|
+
]
|
|
68
|
+
if annuals:
|
|
69
|
+
# If multiple annual versions, pick the latest
|
|
70
|
+
return max(annuals, key=lambda v: _parse_version(
|
|
71
|
+
v.get("_source_version", "0")
|
|
72
|
+
))
|
|
73
|
+
|
|
74
|
+
# No annual — pick latest candidate by version number
|
|
75
|
+
return max(versions, key=lambda v: _parse_version(
|
|
76
|
+
v.get("_source_version", "0")
|
|
77
|
+
))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@_registry.decorator("dot9_wins")
|
|
81
|
+
def dot9_wins(versions: list[dict]) -> dict:
|
|
82
|
+
"""Annual > .9 > candidate. Production-parity survivorship.
|
|
83
|
+
|
|
84
|
+
Prefers annual (authoritative, curated) when available.
|
|
85
|
+
Falls back to .9 (UCDP's own consolidation with exclusive
|
|
86
|
+
content). Last resort: latest individual candidate version.
|
|
87
|
+
"""
|
|
88
|
+
annuals = [
|
|
89
|
+
v for v in versions
|
|
90
|
+
if v.get("_source_type") == "annual"
|
|
91
|
+
]
|
|
92
|
+
if annuals:
|
|
93
|
+
return max(annuals, key=lambda v: _parse_version(
|
|
94
|
+
v.get("_source_version", "0")
|
|
95
|
+
))
|
|
96
|
+
|
|
97
|
+
dot9s = [
|
|
98
|
+
v for v in versions
|
|
99
|
+
if v.get("_source_type") == "dot9"
|
|
100
|
+
]
|
|
101
|
+
if dot9s:
|
|
102
|
+
return max(dot9s, key=lambda v: _parse_version(
|
|
103
|
+
v.get("_source_version", "0")
|
|
104
|
+
))
|
|
105
|
+
|
|
106
|
+
return max(versions, key=lambda v: _parse_version(
|
|
107
|
+
v.get("_source_version", "0")
|
|
108
|
+
))
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Temporal interpolation for epoch-based viewpoint builders."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
VALID_TEMPORAL_INTERPOLATIONS = ("step", "linear")
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def interpolate_temporal(
|
|
9
|
+
epoch_values: dict[int, float],
|
|
10
|
+
*,
|
|
11
|
+
strategy: str,
|
|
12
|
+
start_year: int,
|
|
13
|
+
start_month: int,
|
|
14
|
+
end_year: int,
|
|
15
|
+
end_month: int,
|
|
16
|
+
) -> list[float]:
|
|
17
|
+
"""Interpolate epoch values to monthly time steps.
|
|
18
|
+
|
|
19
|
+
Strategies:
|
|
20
|
+
step — hold last known epoch value until the next epoch.
|
|
21
|
+
linear — linearly interpolate between adjacent epochs;
|
|
22
|
+
hold flat before the first and after the last.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
epoch_values: Mapping of epoch year -> aggregated value.
|
|
26
|
+
strategy: One of VALID_TEMPORAL_INTERPOLATIONS.
|
|
27
|
+
start_year, start_month: First output month.
|
|
28
|
+
end_year, end_month: Last output month (inclusive).
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
List of float values, one per month.
|
|
32
|
+
"""
|
|
33
|
+
n_months = (
|
|
34
|
+
(end_year - start_year) * 12
|
|
35
|
+
+ (end_month - start_month)
|
|
36
|
+
+ 1
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
sorted_epochs = sorted(epoch_values.keys())
|
|
40
|
+
|
|
41
|
+
if strategy == "step":
|
|
42
|
+
return interp_step(
|
|
43
|
+
n_months, sorted_epochs, epoch_values,
|
|
44
|
+
start_year, start_month,
|
|
45
|
+
)
|
|
46
|
+
if strategy == "linear":
|
|
47
|
+
return interp_linear(
|
|
48
|
+
n_months, sorted_epochs, epoch_values,
|
|
49
|
+
start_year, start_month,
|
|
50
|
+
)
|
|
51
|
+
msg = (
|
|
52
|
+
f"Unknown interpolation strategy '{strategy}'. "
|
|
53
|
+
f"Valid: {VALID_TEMPORAL_INTERPOLATIONS}"
|
|
54
|
+
)
|
|
55
|
+
raise ValueError(msg)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def interp_step(
|
|
59
|
+
n_months: int,
|
|
60
|
+
sorted_epochs: list[int],
|
|
61
|
+
epoch_values: dict[int, float],
|
|
62
|
+
start_year: int,
|
|
63
|
+
start_month: int,
|
|
64
|
+
) -> list[float]:
|
|
65
|
+
result: list[float] = []
|
|
66
|
+
for i in range(n_months):
|
|
67
|
+
year = start_year + (start_month - 1 + i) // 12
|
|
68
|
+
value = 0.0
|
|
69
|
+
for ep in sorted_epochs:
|
|
70
|
+
if ep <= year:
|
|
71
|
+
value = epoch_values[ep]
|
|
72
|
+
else:
|
|
73
|
+
break
|
|
74
|
+
result.append(value)
|
|
75
|
+
return result
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def interp_linear(
|
|
79
|
+
n_months: int,
|
|
80
|
+
sorted_epochs: list[int],
|
|
81
|
+
epoch_values: dict[int, float],
|
|
82
|
+
start_year: int,
|
|
83
|
+
start_month: int,
|
|
84
|
+
) -> list[float]:
|
|
85
|
+
result: list[float] = []
|
|
86
|
+
for i in range(n_months):
|
|
87
|
+
year = start_year + (start_month - 1 + i) // 12
|
|
88
|
+
month = (start_month - 1 + i) % 12 + 1
|
|
89
|
+
t = year + (month - 1) / 12.0
|
|
90
|
+
|
|
91
|
+
if not sorted_epochs or t < sorted_epochs[0]:
|
|
92
|
+
result.append(0.0)
|
|
93
|
+
continue
|
|
94
|
+
|
|
95
|
+
if t >= sorted_epochs[-1]:
|
|
96
|
+
result.append(epoch_values[sorted_epochs[-1]])
|
|
97
|
+
continue
|
|
98
|
+
|
|
99
|
+
for j in range(len(sorted_epochs) - 1):
|
|
100
|
+
ep_lo = sorted_epochs[j]
|
|
101
|
+
ep_hi = sorted_epochs[j + 1]
|
|
102
|
+
if ep_lo <= t < ep_hi:
|
|
103
|
+
frac = (t - ep_lo) / (ep_hi - ep_lo)
|
|
104
|
+
val = (
|
|
105
|
+
epoch_values[ep_lo] * (1 - frac)
|
|
106
|
+
+ epoch_values[ep_hi] * frac
|
|
107
|
+
)
|
|
108
|
+
result.append(val)
|
|
109
|
+
break
|
|
110
|
+
|
|
111
|
+
return result
|