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,471 @@
|
|
|
1
|
+
"""GHS-POP viewpoint v1 — spatial aggregation + temporal interpolation.
|
|
2
|
+
|
|
3
|
+
Reads GHS-POP R2023A GeoTIFF files from the harvest output directory,
|
|
4
|
+
aggregates 30-arcsecond pixels to 0.5-degree PRIO-GRID cells (sum),
|
|
5
|
+
and interpolates 12 five-year epochs to monthly via step function.
|
|
6
|
+
|
|
7
|
+
No consolidation layer (ADR-029: single release, nothing to merge).
|
|
8
|
+
Viewpoint reads directly from data/raw/ghspop/.
|
|
9
|
+
|
|
10
|
+
Implements ADR-014 (viewpoints as derived views), ADR-029 (GHS-POP),
|
|
11
|
+
ADR-030 (tifffile for GeoTIFF I/O).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import logging
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
import pyarrow as pa
|
|
22
|
+
import pyarrow.parquet as pq
|
|
23
|
+
|
|
24
|
+
from datafactory_provenance import (
|
|
25
|
+
DIGEST_SCHEME,
|
|
26
|
+
LEDGER_VERSION,
|
|
27
|
+
VIEWS_EPOCH_YEAR,
|
|
28
|
+
append_ledger_entry,
|
|
29
|
+
compute_file_digest,
|
|
30
|
+
)
|
|
31
|
+
from datafactory_viewpoint.builders import register_builder
|
|
32
|
+
from datafactory_viewpoint.raster_io import read_geotiff
|
|
33
|
+
from datafactory_viewpoint.temporal import (
|
|
34
|
+
VALID_TEMPORAL_INTERPOLATIONS,
|
|
35
|
+
interpolate_temporal,
|
|
36
|
+
)
|
|
37
|
+
from datafactory_viewpoint.viewpoint_result import ViewpointResult
|
|
38
|
+
|
|
39
|
+
logger = logging.getLogger(__name__)
|
|
40
|
+
|
|
41
|
+
DATASET_ID = "ghspop_viewpoint"
|
|
42
|
+
|
|
43
|
+
KNOWN_EPOCHS = (
|
|
44
|
+
1975, 1980, 1985, 1990, 1995,
|
|
45
|
+
2000, 2005, 2010, 2015, 2020, 2025, 2030,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
PIXELS_PER_CELL = 60
|
|
49
|
+
|
|
50
|
+
DEFAULT_NODATA = -200.0
|
|
51
|
+
|
|
52
|
+
# ---- Config ----
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class GhsPopViewpointConfig:
|
|
57
|
+
"""Configuration for building a GHS-POP viewpoint.
|
|
58
|
+
|
|
59
|
+
Reads GeoTIFF files from source_dir (harvest output), aggregates
|
|
60
|
+
to PRIO-GRID resolution, interpolates to monthly, writes Parquet.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
source_dir: Path
|
|
64
|
+
|
|
65
|
+
output_path: Path = Path("data/viewpoint/ghspop_v1.parquet")
|
|
66
|
+
ledger_path: Path = Path(
|
|
67
|
+
"provenance/viewpoint/ghspop_v1_ledger.jsonl"
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
epochs: tuple[int, ...] = KNOWN_EPOCHS
|
|
71
|
+
release: str = "R2023A"
|
|
72
|
+
resolution: str = "30ss"
|
|
73
|
+
crs: str = "4326"
|
|
74
|
+
|
|
75
|
+
aggregation: str = "sum"
|
|
76
|
+
temporal_interpolation: str = "linear"
|
|
77
|
+
|
|
78
|
+
start_year: int = 1975
|
|
79
|
+
start_month: int = 1
|
|
80
|
+
end_year: int = 2030
|
|
81
|
+
end_month: int = 12
|
|
82
|
+
|
|
83
|
+
nodata: float = DEFAULT_NODATA
|
|
84
|
+
|
|
85
|
+
version: str = "ghspop_v1"
|
|
86
|
+
|
|
87
|
+
def __post_init__(self) -> None:
|
|
88
|
+
if not self.version:
|
|
89
|
+
err_msg = "version must be non-empty"
|
|
90
|
+
logger.error(err_msg)
|
|
91
|
+
raise ValueError(err_msg)
|
|
92
|
+
if not self.epochs:
|
|
93
|
+
err_msg = "At least one epoch is required"
|
|
94
|
+
logger.error(err_msg)
|
|
95
|
+
raise ValueError(err_msg)
|
|
96
|
+
for epoch in self.epochs:
|
|
97
|
+
if epoch not in KNOWN_EPOCHS:
|
|
98
|
+
err_msg = (
|
|
99
|
+
f"Unknown epoch {epoch}. "
|
|
100
|
+
f"Valid epochs: {KNOWN_EPOCHS}"
|
|
101
|
+
)
|
|
102
|
+
logger.error(err_msg)
|
|
103
|
+
raise ValueError(err_msg)
|
|
104
|
+
if self.temporal_interpolation not in VALID_TEMPORAL_INTERPOLATIONS:
|
|
105
|
+
err_msg = (
|
|
106
|
+
f"Unknown temporal_interpolation "
|
|
107
|
+
f"'{self.temporal_interpolation}'. "
|
|
108
|
+
f"Valid: {VALID_TEMPORAL_INTERPOLATIONS}"
|
|
109
|
+
)
|
|
110
|
+
logger.error(err_msg)
|
|
111
|
+
raise ValueError(err_msg)
|
|
112
|
+
|
|
113
|
+
@classmethod
|
|
114
|
+
def from_shortcuts(
|
|
115
|
+
cls, *, source_dir: Path,
|
|
116
|
+
) -> GhsPopViewpointConfig:
|
|
117
|
+
"""Construct config from minimal shortcut arguments."""
|
|
118
|
+
return cls(source_dir=source_dir)
|
|
119
|
+
|
|
120
|
+
def tif_filename(self, epoch: int) -> str:
|
|
121
|
+
stem = (
|
|
122
|
+
f"GHS_POP_E{epoch}_GLOBE"
|
|
123
|
+
f"_{self.release}_{self.crs}_{self.resolution}"
|
|
124
|
+
)
|
|
125
|
+
return f"{stem}_V1_0.tif"
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# ---- Spatial alignment ----
|
|
129
|
+
|
|
130
|
+
PRIO_NROW = 360
|
|
131
|
+
PRIO_NCOL = 720
|
|
132
|
+
GLOBE_PIXEL_ROWS = PRIO_NROW * PIXELS_PER_CELL # 21600
|
|
133
|
+
GLOBE_PIXEL_COLS = PRIO_NCOL * PIXELS_PER_CELL # 43200
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _align_to_globe(
|
|
137
|
+
data: np.ndarray,
|
|
138
|
+
tiepoint_x: float,
|
|
139
|
+
tiepoint_y: float,
|
|
140
|
+
pixel_scale_x: float,
|
|
141
|
+
pixel_scale_y: float,
|
|
142
|
+
) -> np.ndarray:
|
|
143
|
+
"""Embed a raster into the full PRIO-GRID pixel space.
|
|
144
|
+
|
|
145
|
+
JRC GHS-POP WGS84 30ss rasters do not cover the poles and may
|
|
146
|
+
have slight longitude offsets. This function places the raster
|
|
147
|
+
into a 21600x43200 (360x60, 720x60) array at the correct
|
|
148
|
+
geographic position, padding with zeros where the raster has
|
|
149
|
+
no coverage (polar regions).
|
|
150
|
+
|
|
151
|
+
Args:
|
|
152
|
+
data: 2-D raster array.
|
|
153
|
+
tiepoint_x, tiepoint_y: Top-left geographic coordinate.
|
|
154
|
+
pixel_scale_x, pixel_scale_y: Pixel size in degrees.
|
|
155
|
+
|
|
156
|
+
Returns:
|
|
157
|
+
2-D array of shape (21600, 43200), same dtype as input.
|
|
158
|
+
"""
|
|
159
|
+
row_offset = round((90.0 - tiepoint_y) / pixel_scale_y)
|
|
160
|
+
col_offset = round((tiepoint_x - (-180.0)) / pixel_scale_x)
|
|
161
|
+
|
|
162
|
+
globe = np.zeros(
|
|
163
|
+
(GLOBE_PIXEL_ROWS, GLOBE_PIXEL_COLS), dtype=data.dtype,
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
src_row_start = max(0, -row_offset)
|
|
167
|
+
src_col_start = max(0, -col_offset)
|
|
168
|
+
dst_row_start = max(0, row_offset)
|
|
169
|
+
dst_col_start = max(0, col_offset)
|
|
170
|
+
|
|
171
|
+
copy_nrow = min(
|
|
172
|
+
data.shape[0] - src_row_start,
|
|
173
|
+
GLOBE_PIXEL_ROWS - dst_row_start,
|
|
174
|
+
)
|
|
175
|
+
copy_ncol = min(
|
|
176
|
+
data.shape[1] - src_col_start,
|
|
177
|
+
GLOBE_PIXEL_COLS - dst_col_start,
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
globe[
|
|
181
|
+
dst_row_start:dst_row_start + copy_nrow,
|
|
182
|
+
dst_col_start:dst_col_start + copy_ncol,
|
|
183
|
+
] = data[
|
|
184
|
+
src_row_start:src_row_start + copy_nrow,
|
|
185
|
+
src_col_start:src_col_start + copy_ncol,
|
|
186
|
+
]
|
|
187
|
+
|
|
188
|
+
logger.info(
|
|
189
|
+
"Aligned %dx%d raster into %dx%d globe "
|
|
190
|
+
"(row_offset=%d, col_offset=%d)",
|
|
191
|
+
data.shape[0], data.shape[1],
|
|
192
|
+
GLOBE_PIXEL_ROWS, GLOBE_PIXEL_COLS,
|
|
193
|
+
row_offset, col_offset,
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
return globe
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
# ---- Spatial aggregation ----
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _aggregate_to_prio_grid(
|
|
203
|
+
data: np.ndarray,
|
|
204
|
+
*,
|
|
205
|
+
nodata: float = DEFAULT_NODATA,
|
|
206
|
+
) -> np.ndarray:
|
|
207
|
+
"""Aggregate aligned 30-arcsecond raster to PRIO-GRID cells.
|
|
208
|
+
|
|
209
|
+
Input must be 21600x43200 (already aligned to the globe via
|
|
210
|
+
_align_to_globe). Block-sum via reshape — no reprojection.
|
|
211
|
+
|
|
212
|
+
.. warning::
|
|
213
|
+
ADR-031 P3 violation: ``clean = data.copy()`` doubles peak
|
|
214
|
+
memory (~14 GiB for a full globe float32 raster). This
|
|
215
|
+
function is retained for test compatibility but is no longer
|
|
216
|
+
called from ``build_ghspop_v1`` (v1.2.18 switched to
|
|
217
|
+
``_aggregate_with_alignment``). If re-activated, rewrite to
|
|
218
|
+
replace nodata in-place. See C-177.
|
|
219
|
+
|
|
220
|
+
Args:
|
|
221
|
+
data: 2-D float array, shape (21600, 43200).
|
|
222
|
+
nodata: Fill value treated as zero.
|
|
223
|
+
|
|
224
|
+
Returns:
|
|
225
|
+
2-D array of shape (360, 720) with population sums.
|
|
226
|
+
"""
|
|
227
|
+
nrow, ncol = data.shape
|
|
228
|
+
p = PIXELS_PER_CELL
|
|
229
|
+
|
|
230
|
+
if nrow % p != 0 or ncol % p != 0:
|
|
231
|
+
msg = (
|
|
232
|
+
f"Raster dimensions ({nrow}, {ncol}) must be "
|
|
233
|
+
f"divisible by {p}"
|
|
234
|
+
)
|
|
235
|
+
logger.error(msg)
|
|
236
|
+
raise ValueError(msg)
|
|
237
|
+
|
|
238
|
+
clean = data.copy()
|
|
239
|
+
clean[clean == nodata] = 0.0
|
|
240
|
+
clean[clean < 0.0] = 0.0
|
|
241
|
+
|
|
242
|
+
prio_rows = nrow // p
|
|
243
|
+
prio_cols = ncol // p
|
|
244
|
+
|
|
245
|
+
blocks = clean.reshape(prio_rows, p, prio_cols, p)
|
|
246
|
+
result: np.ndarray = blocks.sum(axis=(1, 3), dtype=np.float64)
|
|
247
|
+
return result
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _aggregate_with_alignment(
|
|
251
|
+
data: np.ndarray,
|
|
252
|
+
row_offset: int,
|
|
253
|
+
col_offset: int,
|
|
254
|
+
*,
|
|
255
|
+
nodata: float = DEFAULT_NODATA,
|
|
256
|
+
) -> np.ndarray:
|
|
257
|
+
"""Aggregate raw raster to PRIO-GRID via strip processing.
|
|
258
|
+
|
|
259
|
+
Combines alignment and aggregation without allocating a full
|
|
260
|
+
21600x43200 globe array. Processes one PRIO-GRID row (60 pixel
|
|
261
|
+
rows) at a time — peak memory is raw_array + ~20 MB instead of
|
|
262
|
+
raw_array + globe_array (~7.4 GB combined).
|
|
263
|
+
|
|
264
|
+
Args:
|
|
265
|
+
data: Raw 2-D raster (e.g. 21384x43202).
|
|
266
|
+
row_offset: Globe pixel row where the raster's first row lands.
|
|
267
|
+
col_offset: Globe pixel column where the raster's first column
|
|
268
|
+
lands.
|
|
269
|
+
nodata: Fill value treated as zero.
|
|
270
|
+
|
|
271
|
+
Returns:
|
|
272
|
+
2-D float64 array of shape (360, 720) with population sums.
|
|
273
|
+
"""
|
|
274
|
+
p = PIXELS_PER_CELL
|
|
275
|
+
result = np.zeros((PRIO_NROW, PRIO_NCOL), dtype=np.float64)
|
|
276
|
+
|
|
277
|
+
for prio_row in range(PRIO_NROW):
|
|
278
|
+
globe_r0 = prio_row * p
|
|
279
|
+
raw_r0 = globe_r0 - row_offset
|
|
280
|
+
raw_r1 = raw_r0 + p
|
|
281
|
+
|
|
282
|
+
src_r0 = max(0, raw_r0)
|
|
283
|
+
src_r1 = min(data.shape[0], raw_r1)
|
|
284
|
+
|
|
285
|
+
if src_r0 >= src_r1:
|
|
286
|
+
continue
|
|
287
|
+
|
|
288
|
+
strip = data[src_r0:src_r1, :].astype(np.float32)
|
|
289
|
+
strip[(strip == nodata) | (strip < 0.0)] = 0.0
|
|
290
|
+
|
|
291
|
+
n_rows = strip.shape[0]
|
|
292
|
+
aligned = np.zeros(
|
|
293
|
+
(n_rows, GLOBE_PIXEL_COLS), dtype=np.float32,
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
dst_c0 = max(0, col_offset)
|
|
297
|
+
src_c0 = max(0, -col_offset)
|
|
298
|
+
n_cols = min(
|
|
299
|
+
strip.shape[1] - src_c0,
|
|
300
|
+
GLOBE_PIXEL_COLS - dst_c0,
|
|
301
|
+
)
|
|
302
|
+
if n_cols > 0:
|
|
303
|
+
aligned[:, dst_c0:dst_c0 + n_cols] = (
|
|
304
|
+
strip[:, src_c0:src_c0 + n_cols]
|
|
305
|
+
)
|
|
306
|
+
del strip
|
|
307
|
+
|
|
308
|
+
blocks = aligned.reshape(n_rows, PRIO_NCOL, p)
|
|
309
|
+
result[prio_row, :] = blocks.sum(
|
|
310
|
+
axis=(0, 2), dtype=np.float64,
|
|
311
|
+
)
|
|
312
|
+
del aligned
|
|
313
|
+
|
|
314
|
+
logger.info(
|
|
315
|
+
"Aggregated %dx%d raster to %dx%d PRIO-GRID "
|
|
316
|
+
"(row_offset=%d, col_offset=%d, strip processing)",
|
|
317
|
+
data.shape[0], data.shape[1],
|
|
318
|
+
PRIO_NROW, PRIO_NCOL,
|
|
319
|
+
row_offset, col_offset,
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
return result
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
# ---- Temporal interpolation ----
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
# ---- Builder ----
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def build_ghspop_v1(
|
|
332
|
+
config: GhsPopViewpointConfig,
|
|
333
|
+
) -> ViewpointResult:
|
|
334
|
+
"""Build GHS-POP viewpoint v1 from harvested GeoTIFF files.
|
|
335
|
+
|
|
336
|
+
For each epoch: read GeoTIFF, aggregate to PRIO-GRID, collect
|
|
337
|
+
per-cell values. Then interpolate all cells temporally and write
|
|
338
|
+
Parquet with (pgid, month_id, pop_count).
|
|
339
|
+
|
|
340
|
+
Returns:
|
|
341
|
+
ViewpointResult with cell counts and output digest.
|
|
342
|
+
"""
|
|
343
|
+
if not config.source_dir.exists():
|
|
344
|
+
err_msg = f"Source directory not found: {config.source_dir}"
|
|
345
|
+
logger.error(err_msg)
|
|
346
|
+
raise FileNotFoundError(err_msg)
|
|
347
|
+
|
|
348
|
+
# Read and aggregate each epoch
|
|
349
|
+
epoch_grids: dict[int, np.ndarray] = {}
|
|
350
|
+
for epoch in config.epochs:
|
|
351
|
+
tif_path = config.source_dir / config.tif_filename(epoch)
|
|
352
|
+
if not tif_path.exists():
|
|
353
|
+
err_msg = (
|
|
354
|
+
f"GeoTIFF not found for epoch {epoch}: {tif_path}"
|
|
355
|
+
)
|
|
356
|
+
logger.error(err_msg)
|
|
357
|
+
raise FileNotFoundError(err_msg)
|
|
358
|
+
|
|
359
|
+
logger.info("Reading epoch %d from %s", epoch, tif_path)
|
|
360
|
+
raw, tie_x, tie_y, sc_x, sc_y = read_geotiff(tif_path)
|
|
361
|
+
|
|
362
|
+
row_off = round((90.0 - tie_y) / sc_y)
|
|
363
|
+
col_off = round((tie_x - (-180.0)) / sc_x)
|
|
364
|
+
grid = _aggregate_with_alignment(
|
|
365
|
+
raw, row_off, col_off, nodata=config.nodata,
|
|
366
|
+
)
|
|
367
|
+
del raw
|
|
368
|
+
|
|
369
|
+
epoch_grids[epoch] = grid
|
|
370
|
+
logger.info(
|
|
371
|
+
"Epoch %d: → %d×%d cells, total pop %.0f",
|
|
372
|
+
epoch,
|
|
373
|
+
grid.shape[0], grid.shape[1], grid.sum(),
|
|
374
|
+
)
|
|
375
|
+
|
|
376
|
+
prio_rows, prio_cols = next(iter(epoch_grids.values())).shape
|
|
377
|
+
|
|
378
|
+
# Build (pgid, month_id, pop_count) rows
|
|
379
|
+
pgid_rows: list[int] = []
|
|
380
|
+
month_id_rows: list[int] = []
|
|
381
|
+
pop_count_rows: list[float] = []
|
|
382
|
+
|
|
383
|
+
for row in range(prio_rows):
|
|
384
|
+
for col in range(prio_cols):
|
|
385
|
+
epoch_values = {
|
|
386
|
+
ep: float(grid[row, col])
|
|
387
|
+
for ep, grid in epoch_grids.items()
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
monthly = interpolate_temporal(
|
|
391
|
+
epoch_values,
|
|
392
|
+
strategy=config.temporal_interpolation,
|
|
393
|
+
start_year=config.start_year,
|
|
394
|
+
start_month=config.start_month,
|
|
395
|
+
end_year=config.end_year,
|
|
396
|
+
end_month=config.end_month,
|
|
397
|
+
)
|
|
398
|
+
|
|
399
|
+
# PRIO-GRID ID: row-major from bottom-left
|
|
400
|
+
# Row 0 in raster = north = top of grid = last PRIO row
|
|
401
|
+
prio_row = prio_rows - 1 - row
|
|
402
|
+
pgid = prio_row * prio_cols + col + 1
|
|
403
|
+
|
|
404
|
+
for i, pop in enumerate(monthly):
|
|
405
|
+
if pop == 0.0:
|
|
406
|
+
continue
|
|
407
|
+
|
|
408
|
+
year = config.start_year + (
|
|
409
|
+
config.start_month - 1 + i
|
|
410
|
+
) // 12
|
|
411
|
+
month = (config.start_month - 1 + i) % 12 + 1
|
|
412
|
+
mid = (year - VIEWS_EPOCH_YEAR) * 12 + month
|
|
413
|
+
|
|
414
|
+
pgid_rows.append(pgid)
|
|
415
|
+
month_id_rows.append(mid)
|
|
416
|
+
pop_count_rows.append(pop)
|
|
417
|
+
|
|
418
|
+
# Write Parquet
|
|
419
|
+
table = pa.table({
|
|
420
|
+
"pgid": pa.array(pgid_rows, type=pa.int32()),
|
|
421
|
+
"month_id": pa.array(month_id_rows, type=pa.int32()),
|
|
422
|
+
"pop_count": pa.array(pop_count_rows, type=pa.float64()),
|
|
423
|
+
})
|
|
424
|
+
del pgid_rows, month_id_rows, pop_count_rows
|
|
425
|
+
|
|
426
|
+
n_output = table.num_rows
|
|
427
|
+
|
|
428
|
+
config.output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
429
|
+
pq.write_table(table, config.output_path)
|
|
430
|
+
|
|
431
|
+
output_digest = compute_file_digest(config.output_path)
|
|
432
|
+
|
|
433
|
+
append_ledger_entry(config.ledger_path, {
|
|
434
|
+
"dataset": DATASET_ID,
|
|
435
|
+
"version": config.version,
|
|
436
|
+
"epochs": list(config.epochs),
|
|
437
|
+
"aggregation": config.aggregation,
|
|
438
|
+
"temporal_interpolation": config.temporal_interpolation,
|
|
439
|
+
"n_epochs": len(config.epochs),
|
|
440
|
+
"n_cells_output": n_output,
|
|
441
|
+
"output_path": str(config.output_path),
|
|
442
|
+
"output_digest": output_digest,
|
|
443
|
+
"outcome": "success",
|
|
444
|
+
"ledger_version": LEDGER_VERSION,
|
|
445
|
+
"digest_algorithm": DIGEST_SCHEME,
|
|
446
|
+
})
|
|
447
|
+
|
|
448
|
+
logger.info(
|
|
449
|
+
"GHS-POP viewpoint %s built: %d epochs → %d rows "
|
|
450
|
+
"(digest: %s)",
|
|
451
|
+
config.version,
|
|
452
|
+
len(config.epochs),
|
|
453
|
+
n_output,
|
|
454
|
+
output_digest,
|
|
455
|
+
)
|
|
456
|
+
|
|
457
|
+
return ViewpointResult(
|
|
458
|
+
output_path=config.output_path,
|
|
459
|
+
n_events_input=sum(
|
|
460
|
+
int(g.size) for g in epoch_grids.values()
|
|
461
|
+
),
|
|
462
|
+
n_events_output=n_output,
|
|
463
|
+
n_summary_expanded=0,
|
|
464
|
+
n_spatially_distributed=0,
|
|
465
|
+
n_filtered=0,
|
|
466
|
+
output_digest=output_digest,
|
|
467
|
+
version=config.version,
|
|
468
|
+
)
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
register_builder("ghspop_v1", build_ghspop_v1)
|