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,137 @@
|
|
|
1
|
+
"""Programmatic PRIO-GRID generator -- pure numpy, zero external data dependency.
|
|
2
|
+
|
|
3
|
+
Generates a full 360x720 global grid with cell IDs matching PRIO-GRID's
|
|
4
|
+
numbering scheme. Returns plain numpy arrays. No geometry libraries.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from datafactory_priogrid.grid_config import DEFAULT_GRID_CONFIG, GridConfig
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def generate_grid(
|
|
17
|
+
config: GridConfig = DEFAULT_GRID_CONFIG,
|
|
18
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
19
|
+
"""Generate cell IDs and centroid coordinates for the full grid.
|
|
20
|
+
|
|
21
|
+
Returns:
|
|
22
|
+
(pgids, lats, lons) -- three 1-D arrays of length config.n_cells.
|
|
23
|
+
pgids are 1-based int32 matching PRIO-GRID's numbering.
|
|
24
|
+
lats/lons are float64 cell centroids in decimal degrees.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
nrow, ncol = config.nrow, config.ncol
|
|
28
|
+
half = config.resolution / 2
|
|
29
|
+
|
|
30
|
+
# Row-major from bottom-left: pgid = row_from_south * ncol + col + 1
|
|
31
|
+
rows = np.repeat(np.arange(nrow), ncol)
|
|
32
|
+
cols = np.tile(np.arange(ncol), nrow)
|
|
33
|
+
|
|
34
|
+
pgids = (rows * ncol + cols + 1).astype(np.int32)
|
|
35
|
+
lats = (config.south + rows * config.resolution + half).astype(np.float64)
|
|
36
|
+
lons = (config.west + cols * config.resolution + half).astype(np.float64)
|
|
37
|
+
|
|
38
|
+
logger.info(
|
|
39
|
+
"Generated %d centroids (%.2f deg grid, %dx%d)",
|
|
40
|
+
len(pgids),
|
|
41
|
+
config.resolution,
|
|
42
|
+
nrow,
|
|
43
|
+
ncol,
|
|
44
|
+
)
|
|
45
|
+
return pgids, lats, lons
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def generate_bounding_boxes(
|
|
49
|
+
config: GridConfig = DEFAULT_GRID_CONFIG,
|
|
50
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
|
51
|
+
"""Generate cell IDs and bounding boxes for the full grid.
|
|
52
|
+
|
|
53
|
+
Returns:
|
|
54
|
+
(pgids, west, south, east, north) -- five 1-D arrays.
|
|
55
|
+
Each cell's bounding box is (west, south, east, north) in degrees.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
pgids, lats, lons = generate_grid(config)
|
|
59
|
+
half = config.resolution / 2
|
|
60
|
+
|
|
61
|
+
return (
|
|
62
|
+
pgids,
|
|
63
|
+
lons - half, # west
|
|
64
|
+
lats - half, # south
|
|
65
|
+
lons + half, # east
|
|
66
|
+
lats + half, # north
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def pgid_to_latlon(
|
|
71
|
+
pgid: int | np.ndarray,
|
|
72
|
+
config: GridConfig = DEFAULT_GRID_CONFIG,
|
|
73
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
74
|
+
"""Convert cell ID(s) to centroid (lat, lon).
|
|
75
|
+
|
|
76
|
+
Works for scalar or array input. Returns float64 arrays.
|
|
77
|
+
|
|
78
|
+
Raises:
|
|
79
|
+
ValueError: If any pgid is outside [1, config.n_cells].
|
|
80
|
+
"""
|
|
81
|
+
pgid = np.asarray(pgid, dtype=np.int32)
|
|
82
|
+
if np.any(pgid < 1) or np.any(pgid > config.n_cells):
|
|
83
|
+
err_msg = (
|
|
84
|
+
f"pgid must be in [1, {config.n_cells}], "
|
|
85
|
+
f"got range [{int(pgid.min())}, {int(pgid.max())}]"
|
|
86
|
+
)
|
|
87
|
+
logger.error(err_msg)
|
|
88
|
+
raise ValueError(err_msg)
|
|
89
|
+
idx = pgid - 1
|
|
90
|
+
rows = idx // config.ncol
|
|
91
|
+
cols = idx % config.ncol
|
|
92
|
+
half = config.resolution / 2
|
|
93
|
+
|
|
94
|
+
lats = (config.south + rows * config.resolution + half).astype(np.float64)
|
|
95
|
+
lons = (config.west + cols * config.resolution + half).astype(np.float64)
|
|
96
|
+
return lats, lons
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def latlon_to_pgid(
|
|
100
|
+
lat: float | np.ndarray,
|
|
101
|
+
lon: float | np.ndarray,
|
|
102
|
+
config: GridConfig = DEFAULT_GRID_CONFIG,
|
|
103
|
+
) -> np.ndarray:
|
|
104
|
+
"""Convert (lat, lon) coordinates to the enclosing cell ID(s).
|
|
105
|
+
|
|
106
|
+
Points exactly on a cell boundary are assigned to the cell
|
|
107
|
+
to the north/east (matching standard raster convention).
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
lat = np.asarray(lat, dtype=np.float64)
|
|
111
|
+
lon = np.asarray(lon, dtype=np.float64)
|
|
112
|
+
|
|
113
|
+
rows = np.floor((lat - config.south) / config.resolution).astype(np.int32)
|
|
114
|
+
cols = np.floor((lon - config.west) / config.resolution).astype(np.int32)
|
|
115
|
+
|
|
116
|
+
if np.any((rows < 0) | (rows >= config.nrow)):
|
|
117
|
+
bad = lat[(rows < 0) | (rows >= config.nrow)]
|
|
118
|
+
err_msg = (
|
|
119
|
+
f"Latitude out of range "
|
|
120
|
+
f"[{config.south}, "
|
|
121
|
+
f"{config.south + config.nrow * config.resolution}]: "
|
|
122
|
+
f"{bad.ravel()[:5]}"
|
|
123
|
+
)
|
|
124
|
+
logger.error(err_msg)
|
|
125
|
+
raise ValueError(err_msg)
|
|
126
|
+
if np.any((cols < 0) | (cols >= config.ncol)):
|
|
127
|
+
bad = lon[(cols < 0) | (cols >= config.ncol)]
|
|
128
|
+
err_msg = (
|
|
129
|
+
f"Longitude out of range "
|
|
130
|
+
f"[{config.west}, "
|
|
131
|
+
f"{config.west + config.ncol * config.resolution}]: "
|
|
132
|
+
f"{bad.ravel()[:5]}"
|
|
133
|
+
)
|
|
134
|
+
logger.error(err_msg)
|
|
135
|
+
raise ValueError(err_msg)
|
|
136
|
+
|
|
137
|
+
return (rows * config.ncol + cols + 1).astype(np.int32)
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""PRIO-GRID spatial backbone configuration.
|
|
2
|
+
|
|
3
|
+
Pure spatial parameters only. No storage paths, no remote URLs —
|
|
4
|
+
those are runtime concerns injected at call sites.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
_GRID_TOLERANCE: float = 1e-9 # Floating-point tolerance for grid dimension validation
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class GridConfig:
|
|
17
|
+
"""Configuration for the PRIO-GRID spatial backbone.
|
|
18
|
+
|
|
19
|
+
Default values reproduce the standard PRIO-GRID exactly:
|
|
20
|
+
360 rows x 720 cols of 0.5 x 0.5 degree cells covering the full globe.
|
|
21
|
+
|
|
22
|
+
The cell ID scheme is row-major from bottom-left:
|
|
23
|
+
pgid = row_from_south * ncol + col_from_west + 1
|
|
24
|
+
|
|
25
|
+
Cell centroids:
|
|
26
|
+
lat = south + row_from_south * resolution + resolution / 2
|
|
27
|
+
lon = west + col_from_west * resolution + resolution / 2
|
|
28
|
+
|
|
29
|
+
Examples:
|
|
30
|
+
Cell 1: lat=-89.75, lon=-179.75 (Antarctic, date line)
|
|
31
|
+
Cell 720: lat=-89.75, lon= 179.75 (end of first row)
|
|
32
|
+
Cell 721: lat=-89.25, lon=-179.75 (second row)
|
|
33
|
+
Cell 259200: lat= 89.75, lon= 179.75 (Arctic, east)
|
|
34
|
+
|
|
35
|
+
Source: create_pg_indices() in
|
|
36
|
+
https://github.com/prio-data/priogrid/blob/master/R/utility.R
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
# Spatial resolution in decimal degrees
|
|
40
|
+
resolution: float = 0.5
|
|
41
|
+
|
|
42
|
+
# Bounding box (WGS84)
|
|
43
|
+
west: float = -180.0
|
|
44
|
+
east: float = 180.0
|
|
45
|
+
south: float = -90.0
|
|
46
|
+
north: float = 90.0
|
|
47
|
+
|
|
48
|
+
# CRS
|
|
49
|
+
crs: str = "EPSG:4326"
|
|
50
|
+
|
|
51
|
+
def __post_init__(self) -> None:
|
|
52
|
+
if self.resolution <= 0:
|
|
53
|
+
err_msg = f"Resolution must be positive, got {self.resolution}"
|
|
54
|
+
logger.error(err_msg)
|
|
55
|
+
raise ValueError(err_msg)
|
|
56
|
+
if self.west >= self.east:
|
|
57
|
+
err_msg = f"West bound ({self.west}) must be less than east ({self.east})"
|
|
58
|
+
logger.error(err_msg)
|
|
59
|
+
raise ValueError(err_msg)
|
|
60
|
+
if self.south >= self.north:
|
|
61
|
+
err_msg = (
|
|
62
|
+
f"South bound ({self.south}) must be less than north ({self.north})"
|
|
63
|
+
)
|
|
64
|
+
logger.error(err_msg)
|
|
65
|
+
raise ValueError(err_msg)
|
|
66
|
+
lat_extent = self.north - self.south
|
|
67
|
+
lon_extent = self.east - self.west
|
|
68
|
+
nrow = lat_extent / self.resolution
|
|
69
|
+
ncol = lon_extent / self.resolution
|
|
70
|
+
nrow_frac = abs(nrow - round(nrow)) > _GRID_TOLERANCE
|
|
71
|
+
ncol_frac = abs(ncol - round(ncol)) > _GRID_TOLERANCE
|
|
72
|
+
if nrow_frac or ncol_frac:
|
|
73
|
+
err_msg = (
|
|
74
|
+
f"Resolution {self.resolution} does not evenly divide "
|
|
75
|
+
f"lat extent ({lat_extent}) or lon extent ({lon_extent})"
|
|
76
|
+
)
|
|
77
|
+
logger.error(err_msg)
|
|
78
|
+
raise ValueError(err_msg)
|
|
79
|
+
|
|
80
|
+
# Derived grid dimensions (at default 0.5 deg: 360 x 720 = 259,200 cells)
|
|
81
|
+
@property
|
|
82
|
+
def nrow(self) -> int:
|
|
83
|
+
return int((self.north - self.south) / self.resolution)
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def ncol(self) -> int:
|
|
87
|
+
return int((self.east - self.west) / self.resolution)
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def n_cells(self) -> int:
|
|
91
|
+
return self.nrow * self.ncol
|
|
92
|
+
|
|
93
|
+
def assert_grid_shape(self, grid: object) -> None:
|
|
94
|
+
"""Validate that a [T, H, W, C] array's spatial dims match this config."""
|
|
95
|
+
shape = getattr(grid, "shape", None)
|
|
96
|
+
if shape is None:
|
|
97
|
+
raise TypeError(
|
|
98
|
+
f"Expected array with .shape attribute, got {type(grid).__name__}"
|
|
99
|
+
)
|
|
100
|
+
if shape[1] != self.nrow or shape[2] != self.ncol:
|
|
101
|
+
raise AssertionError(
|
|
102
|
+
f"Grid spatial dims ({shape[1]}, {shape[2]}) "
|
|
103
|
+
f"!= expected ({self.nrow}, {self.ncol})"
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
DEFAULT_GRID_CONFIG = GridConfig()
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Land mask — identify land cells from the PRIO-GRID API.
|
|
2
|
+
|
|
3
|
+
The PRIO-GRID API (https://grid.prio.org) returns data only for
|
|
4
|
+
land cells. The ``landarea`` variable contains 64,818 cells — each
|
|
5
|
+
with landarea > 0. Ocean cells are not in the API responses.
|
|
6
|
+
|
|
7
|
+
Results are cached to disk to avoid re-fetching.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import logging
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
import requests
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
_PRIOGRID_API_URL = "https://grid.prio.org/api/data/landarea"
|
|
21
|
+
_DEFAULT_CACHE_PATH = Path("data/raw/priogrid/land_pgids.json")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def fetch_land_pgids(
|
|
25
|
+
*,
|
|
26
|
+
cache_path: Path = _DEFAULT_CACHE_PATH,
|
|
27
|
+
force_refresh: bool = False,
|
|
28
|
+
) -> set[int]:
|
|
29
|
+
"""Return the set of PRIO-GRID cell IDs that are land.
|
|
30
|
+
|
|
31
|
+
Fetches the ``landarea`` variable from the PRIO-GRID API,
|
|
32
|
+
which returns only cells with land area > 0 (64,818 cells).
|
|
33
|
+
Results are cached to disk as JSON.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
cache_path: Where to cache the land pgid list.
|
|
37
|
+
force_refresh: If True, re-fetch even if cache exists.
|
|
38
|
+
|
|
39
|
+
Returns:
|
|
40
|
+
Set of integer pgids representing land cells.
|
|
41
|
+
"""
|
|
42
|
+
if not force_refresh and cache_path.exists():
|
|
43
|
+
pgids = json.loads(cache_path.read_text())
|
|
44
|
+
logger.info(
|
|
45
|
+
"Loaded %d land pgids from cache: %s",
|
|
46
|
+
len(pgids), cache_path,
|
|
47
|
+
)
|
|
48
|
+
return set(pgids)
|
|
49
|
+
|
|
50
|
+
logger.info("Fetching land pgids from PRIO-GRID API...")
|
|
51
|
+
resp = requests.get(_PRIOGRID_API_URL, timeout=60)
|
|
52
|
+
resp.raise_for_status()
|
|
53
|
+
data = resp.json()
|
|
54
|
+
pgids = sorted(c["gid"] for c in data["cells"])
|
|
55
|
+
|
|
56
|
+
cache_path.parent.mkdir(parents=True, exist_ok=True)
|
|
57
|
+
cache_path.write_text(json.dumps(pgids))
|
|
58
|
+
logger.info(
|
|
59
|
+
"Fetched %d land pgids, cached to %s",
|
|
60
|
+
len(pgids), cache_path,
|
|
61
|
+
)
|
|
62
|
+
return set(pgids)
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Parity validation: compare our generated grid against a reference source.
|
|
2
|
+
|
|
3
|
+
Defines a Protocol for reading reference geometry data. The actual
|
|
4
|
+
shapefile reader (pyshp, fiona, etc.) is NOT chosen here -- it is
|
|
5
|
+
plugged in at call time. This keeps the grid module free of geo
|
|
6
|
+
dependencies.
|
|
7
|
+
|
|
8
|
+
When no reader is available, parity validation simply cannot run.
|
|
9
|
+
The grid's self-consistency tests still work.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import logging
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Protocol
|
|
16
|
+
|
|
17
|
+
from datafactory_priogrid.grid_config import DEFAULT_GRID_CONFIG, GridConfig
|
|
18
|
+
from datafactory_provenance import LEDGER_VERSION, append_ledger_entry
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
_MAX_REPORTED_ERRORS: int = 10
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ReferenceGeometryReader(Protocol):
|
|
26
|
+
"""Interface for reading reference grid cell centroids.
|
|
27
|
+
|
|
28
|
+
Implementations might use pyshp, fiona, geopandas, or anything
|
|
29
|
+
else that can extract (cell_id, lat, lon) from a shapefile.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def read(self, path: Path) -> list[tuple[int, float, float]]:
|
|
33
|
+
"""Read reference centroids from a file.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
path: Path to the shapefile directory or file.
|
|
37
|
+
|
|
38
|
+
Returns:
|
|
39
|
+
List of (pgid, centroid_lat, centroid_lon) tuples.
|
|
40
|
+
"""
|
|
41
|
+
...
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class ParityResult:
|
|
46
|
+
"""Result of comparing our grid against a reference source."""
|
|
47
|
+
|
|
48
|
+
valid: bool
|
|
49
|
+
n_cells_ours: int
|
|
50
|
+
n_cells_reference: int
|
|
51
|
+
n_matched: int = 0
|
|
52
|
+
max_centroid_error_deg: float = 0.0
|
|
53
|
+
errors: list[str] = field(default_factory=list)
|
|
54
|
+
warnings: list[str] = field(default_factory=list)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def validate_parity(
|
|
58
|
+
reader: ReferenceGeometryReader,
|
|
59
|
+
reference_path: Path,
|
|
60
|
+
config: GridConfig = DEFAULT_GRID_CONFIG,
|
|
61
|
+
*,
|
|
62
|
+
centroid_tolerance_deg: float = 0.01,
|
|
63
|
+
) -> ParityResult:
|
|
64
|
+
"""Compare our generated grid against reference data.
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
reader: An implementation of ReferenceGeometryReader.
|
|
68
|
+
reference_path: Path to the reference shapefile/directory.
|
|
69
|
+
config: Grid config.
|
|
70
|
+
centroid_tolerance_deg: Max allowed centroid deviation in degrees.
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
ParityResult with match details.
|
|
74
|
+
"""
|
|
75
|
+
from datafactory_priogrid.cell_generator import generate_grid
|
|
76
|
+
|
|
77
|
+
# Generate our grid
|
|
78
|
+
pgids, lats, lons = generate_grid(config)
|
|
79
|
+
n_ours = len(pgids)
|
|
80
|
+
|
|
81
|
+
# Read reference
|
|
82
|
+
ref_cells = reader.read(reference_path)
|
|
83
|
+
n_ref = len(ref_cells)
|
|
84
|
+
|
|
85
|
+
errors: list[str] = []
|
|
86
|
+
warnings: list[str] = []
|
|
87
|
+
|
|
88
|
+
if n_ours != n_ref:
|
|
89
|
+
warnings.append(
|
|
90
|
+
f"Cell count mismatch: ours={n_ours}, reference={n_ref}"
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
# Build lookup from our grid
|
|
94
|
+
our_lookup = {
|
|
95
|
+
int(pid): (float(lat), float(lon))
|
|
96
|
+
for pid, lat, lon in zip(pgids, lats, lons, strict=True)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
# Compare
|
|
100
|
+
n_matched = 0
|
|
101
|
+
max_error = 0.0
|
|
102
|
+
|
|
103
|
+
for ref_id, ref_lat, ref_lon in ref_cells:
|
|
104
|
+
ours = our_lookup.get(ref_id)
|
|
105
|
+
if ours is None:
|
|
106
|
+
if len(errors) < _MAX_REPORTED_ERRORS:
|
|
107
|
+
errors.append(f"Reference cell {ref_id} not in our grid")
|
|
108
|
+
continue
|
|
109
|
+
|
|
110
|
+
our_lat, our_lon = ours
|
|
111
|
+
error = max(abs(our_lat - ref_lat), abs(our_lon - ref_lon))
|
|
112
|
+
max_error = max(max_error, error)
|
|
113
|
+
|
|
114
|
+
if error <= centroid_tolerance_deg:
|
|
115
|
+
n_matched += 1
|
|
116
|
+
elif len(errors) < _MAX_REPORTED_ERRORS:
|
|
117
|
+
errors.append(
|
|
118
|
+
f"Cell {ref_id}: centroid mismatch "
|
|
119
|
+
f"ours=({our_lat:.4f},{our_lon:.4f}) "
|
|
120
|
+
f"ref=({ref_lat:.4f},{ref_lon:.4f}) "
|
|
121
|
+
f"error={error:.4f} deg"
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
valid = len(errors) == 0 and n_matched == n_ref
|
|
125
|
+
|
|
126
|
+
result = ParityResult(
|
|
127
|
+
valid=valid,
|
|
128
|
+
n_cells_ours=n_ours,
|
|
129
|
+
n_cells_reference=n_ref,
|
|
130
|
+
n_matched=n_matched,
|
|
131
|
+
max_centroid_error_deg=max_error,
|
|
132
|
+
errors=errors,
|
|
133
|
+
warnings=warnings,
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
if valid:
|
|
137
|
+
logger.info(
|
|
138
|
+
"Parity PASSED: %d/%d cells matched (max error: %.6f deg)",
|
|
139
|
+
n_matched,
|
|
140
|
+
n_ref,
|
|
141
|
+
max_error,
|
|
142
|
+
)
|
|
143
|
+
else:
|
|
144
|
+
logger.error(
|
|
145
|
+
"Parity FAILED: %d matched, %d errors",
|
|
146
|
+
n_matched,
|
|
147
|
+
len(errors),
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
return result
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def record_parity_result(
|
|
154
|
+
result: ParityResult,
|
|
155
|
+
ledger_path: Path,
|
|
156
|
+
) -> None:
|
|
157
|
+
"""Write the parity validation result to provenance.
|
|
158
|
+
|
|
159
|
+
Args:
|
|
160
|
+
result: The parity validation result.
|
|
161
|
+
ledger_path: Path to the parity validation JSONL ledger.
|
|
162
|
+
"""
|
|
163
|
+
append_ledger_entry(
|
|
164
|
+
ledger_path,
|
|
165
|
+
{
|
|
166
|
+
"valid": result.valid,
|
|
167
|
+
"n_cells_ours": result.n_cells_ours,
|
|
168
|
+
"n_cells_reference": result.n_cells_reference,
|
|
169
|
+
"n_matched": result.n_matched,
|
|
170
|
+
"max_centroid_error_deg": round(result.max_centroid_error_deg, 6),
|
|
171
|
+
"errors": result.errors[:_MAX_REPORTED_ERRORS],
|
|
172
|
+
"warnings": result.warnings,
|
|
173
|
+
"ledger_version": LEDGER_VERSION,
|
|
174
|
+
},
|
|
175
|
+
)
|
|
176
|
+
logger.info("Parity result recorded to %s", ledger_path)
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""PRIO-GRID shapefile harvester.
|
|
2
|
+
|
|
3
|
+
Downloads the reference shapefile ZIP from PRIO and stores it locally
|
|
4
|
+
with full provenance. Does NOT parse the shapefile -- reading is deferred
|
|
5
|
+
to a pluggable ReferenceGeometryReader (see validation.py).
|
|
6
|
+
|
|
7
|
+
The shapefile is a one-time critical artifact. If the origin URL goes
|
|
8
|
+
dead, the local copy is the fallback.
|
|
9
|
+
|
|
10
|
+
Provenance uses datafactory_provenance utilities.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import io
|
|
16
|
+
import logging
|
|
17
|
+
import zipfile
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from datafactory_http import request_with_retry
|
|
22
|
+
from datafactory_provenance import (
|
|
23
|
+
DIGEST_SCHEME,
|
|
24
|
+
LEDGER_VERSION,
|
|
25
|
+
append_ledger_entry,
|
|
26
|
+
compute_content_digest,
|
|
27
|
+
last_digest,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
logger = logging.getLogger(__name__)
|
|
31
|
+
|
|
32
|
+
DATASET_ID = "priogrid_shapefile"
|
|
33
|
+
|
|
34
|
+
# Default PRIO-GRID shapefile URL
|
|
35
|
+
DEFAULT_SHAPEFILE_URL = (
|
|
36
|
+
"http://file.prio.no/ReplicationData/PRIO-GRID/"
|
|
37
|
+
"priogrid_shapefiles.zip"
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class ShapefileHarvesterConfig:
|
|
43
|
+
"""Configuration for downloading the PRIO-GRID shapefile.
|
|
44
|
+
|
|
45
|
+
The shapefile is grid reference geometry (not a data source).
|
|
46
|
+
Downloaded once and reused for parity validation.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
url: str = DEFAULT_SHAPEFILE_URL
|
|
50
|
+
data_dir: Path = Path("data/raw/priogrid")
|
|
51
|
+
ledger_path: Path = Path(
|
|
52
|
+
"provenance/priogrid/ingestion_ledger.jsonl"
|
|
53
|
+
)
|
|
54
|
+
timeout: int = 120 # zipped shapefile ~20 MB (ADR-018)
|
|
55
|
+
max_retries: int = 3
|
|
56
|
+
|
|
57
|
+
def __post_init__(self) -> None:
|
|
58
|
+
if self.timeout < 1:
|
|
59
|
+
err_msg = (
|
|
60
|
+
f"timeout must be >= 1, got {self.timeout}"
|
|
61
|
+
)
|
|
62
|
+
logger.error(err_msg)
|
|
63
|
+
raise ValueError(err_msg)
|
|
64
|
+
if self.max_retries < 1:
|
|
65
|
+
err_msg = (
|
|
66
|
+
f"max_retries must be >= 1, "
|
|
67
|
+
f"got {self.max_retries}"
|
|
68
|
+
)
|
|
69
|
+
logger.error(err_msg)
|
|
70
|
+
raise ValueError(err_msg)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _extract_zip(content: bytes, target_dir: Path) -> list[str]:
|
|
74
|
+
"""Extract ZIP content to a directory.
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
content: Raw ZIP bytes.
|
|
78
|
+
target_dir: Directory to extract into.
|
|
79
|
+
|
|
80
|
+
Returns:
|
|
81
|
+
Sorted list of extracted filenames.
|
|
82
|
+
"""
|
|
83
|
+
target_dir.mkdir(parents=True, exist_ok=True)
|
|
84
|
+
with zipfile.ZipFile(io.BytesIO(content)) as zf:
|
|
85
|
+
zf.extractall(target_dir)
|
|
86
|
+
return sorted(p.name for p in target_dir.rglob("*") if p.is_file())
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def fetch_shapefile(
|
|
90
|
+
config: ShapefileHarvesterConfig | None = None,
|
|
91
|
+
*,
|
|
92
|
+
force_refresh: bool = False,
|
|
93
|
+
) -> Path:
|
|
94
|
+
"""Download and store the PRIO-GRID reference shapefile ZIP.
|
|
95
|
+
|
|
96
|
+
Orchestrates: download -> digest -> compare -> extract -> provenance.
|
|
97
|
+
Skips download if files already exist (unless force_refresh).
|
|
98
|
+
Records a heartbeat if content is unchanged.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
config: Harvest configuration. Uses defaults if None.
|
|
102
|
+
force_refresh: If True, re-download even if files exist.
|
|
103
|
+
|
|
104
|
+
Returns:
|
|
105
|
+
Path to the extraction directory containing .shp files.
|
|
106
|
+
"""
|
|
107
|
+
if config is None:
|
|
108
|
+
config = ShapefileHarvesterConfig()
|
|
109
|
+
|
|
110
|
+
shp_dir = config.data_dir / "shapefile"
|
|
111
|
+
|
|
112
|
+
# Early return: files already on disk
|
|
113
|
+
if (
|
|
114
|
+
not force_refresh
|
|
115
|
+
and shp_dir.exists()
|
|
116
|
+
and any(shp_dir.glob("*.shp"))
|
|
117
|
+
):
|
|
118
|
+
logger.info("Using existing shapefile: %s", shp_dir)
|
|
119
|
+
return shp_dir
|
|
120
|
+
|
|
121
|
+
# Download
|
|
122
|
+
logger.info(
|
|
123
|
+
"Downloading PRIO-GRID shapefile from %s",
|
|
124
|
+
config.url,
|
|
125
|
+
)
|
|
126
|
+
config.data_dir.mkdir(parents=True, exist_ok=True)
|
|
127
|
+
content = request_with_retry(
|
|
128
|
+
config.url,
|
|
129
|
+
timeout=config.timeout,
|
|
130
|
+
max_retries=config.max_retries,
|
|
131
|
+
).content
|
|
132
|
+
|
|
133
|
+
digest = compute_content_digest(content)
|
|
134
|
+
logger.info("Downloaded %d bytes (digest: %s)", len(content), digest)
|
|
135
|
+
|
|
136
|
+
# Compare with previous
|
|
137
|
+
previous = last_digest(config.ledger_path)
|
|
138
|
+
changed = previous is None or previous != digest
|
|
139
|
+
|
|
140
|
+
base_entry = {
|
|
141
|
+
"dataset": DATASET_ID,
|
|
142
|
+
"url": config.url,
|
|
143
|
+
"size_bytes": len(content),
|
|
144
|
+
"content_digest": digest,
|
|
145
|
+
"previous_digest": previous,
|
|
146
|
+
"ledger_version": LEDGER_VERSION,
|
|
147
|
+
"digest_algorithm": DIGEST_SCHEME,
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
# Extract and record
|
|
151
|
+
try:
|
|
152
|
+
zip_path = config.data_dir / "priogrid_shapefiles.zip"
|
|
153
|
+
zip_path.write_bytes(content)
|
|
154
|
+
extracted = _extract_zip(content, shp_dir)
|
|
155
|
+
except Exception:
|
|
156
|
+
logger.error("Extraction failed for shapefile from %s", config.url)
|
|
157
|
+
append_ledger_entry(config.ledger_path, {
|
|
158
|
+
**base_entry,
|
|
159
|
+
"outcome": "failed",
|
|
160
|
+
"changed": False,
|
|
161
|
+
})
|
|
162
|
+
raise
|
|
163
|
+
|
|
164
|
+
logger.info("Extracted %d files to %s", len(extracted), shp_dir)
|
|
165
|
+
|
|
166
|
+
outcome = "success" if changed else "unchanged"
|
|
167
|
+
append_ledger_entry(config.ledger_path, {
|
|
168
|
+
**base_entry,
|
|
169
|
+
"outcome": outcome,
|
|
170
|
+
"changed": changed,
|
|
171
|
+
"extracted_files": extracted,
|
|
172
|
+
})
|
|
173
|
+
|
|
174
|
+
return shp_dir
|