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.
Files changed (103) hide show
  1. datafactory_adapters/ARCHITECTURE.md +54 -0
  2. datafactory_adapters/__init__.py +38 -0
  3. datafactory_adapters/_conservation.py +95 -0
  4. datafactory_adapters/_reconciliation.py +92 -0
  5. datafactory_adapters/_validation.py +39 -0
  6. datafactory_adapters/feature_frame.py +25 -0
  7. datafactory_adapters/grid_from_feature_frame.py +89 -0
  8. datafactory_adapters/grid_to_country_month.py +169 -0
  9. datafactory_adapters/grid_to_dataframe.py +176 -0
  10. datafactory_compilation/ARCHITECTURE.md +63 -0
  11. datafactory_compilation/__init__.py +39 -0
  12. datafactory_compilation/aggregation.py +64 -0
  13. datafactory_compilation/compilation_config.py +97 -0
  14. datafactory_compilation/conservation.py +36 -0
  15. datafactory_compilation/grid_compilation.py +352 -0
  16. datafactory_compilation/output.py +85 -0
  17. datafactory_compilation/preflight.py +61 -0
  18. datafactory_compilation/pregridded_compilation.py +291 -0
  19. datafactory_consolidation/ARCHITECTURE.md +58 -0
  20. datafactory_consolidation/__init__.py +28 -0
  21. datafactory_consolidation/consolidation_result.py +27 -0
  22. datafactory_consolidation/consolidators/__init__.py +32 -0
  23. datafactory_consolidation/consolidators/acled.py +462 -0
  24. datafactory_consolidation/consolidators/ucdp.py +524 -0
  25. datafactory_consolidation/event_store.py +67 -0
  26. datafactory_consolidation/tagging.py +46 -0
  27. datafactory_harvester/ARCHITECTURE.md +103 -0
  28. datafactory_harvester/__init__.py +37 -0
  29. datafactory_harvester/event_validation.py +372 -0
  30. datafactory_harvester/harvest_runner.py +72 -0
  31. datafactory_harvester/pipeline_runner.py +125 -0
  32. datafactory_harvester/snapshot_storage.py +117 -0
  33. datafactory_harvester/sources/__init__.py +36 -0
  34. datafactory_harvester/sources/_ucdp_common.py +34 -0
  35. datafactory_harvester/sources/acled.py +743 -0
  36. datafactory_harvester/sources/gaul_admin.py +567 -0
  37. datafactory_harvester/sources/ghsbuilts.py +271 -0
  38. datafactory_harvester/sources/ghspop.py +267 -0
  39. datafactory_harvester/sources/priogrid_static.py +359 -0
  40. datafactory_harvester/sources/shdi.py +625 -0
  41. datafactory_harvester/sources/ucdp_annual.py +616 -0
  42. datafactory_harvester/sources/ucdp_candidate.py +419 -0
  43. datafactory_harvester/sources/ucdp_dot9.py +407 -0
  44. datafactory_harvester/sources/vdem.py +350 -0
  45. datafactory_harvester/validation.py +74 -0
  46. datafactory_http/__init__.py +10 -0
  47. datafactory_http/retry.py +102 -0
  48. datafactory_priogrid/ARCHITECTURE.md +62 -0
  49. datafactory_priogrid/__init__.py +51 -0
  50. datafactory_priogrid/cell_generator.py +137 -0
  51. datafactory_priogrid/grid_config.py +107 -0
  52. datafactory_priogrid/land_mask.py +62 -0
  53. datafactory_priogrid/parity_validation.py +176 -0
  54. datafactory_priogrid/shapefile_harvester.py +174 -0
  55. datafactory_priogrid/shapefile_reader.py +125 -0
  56. datafactory_priogrid/spatiotemporal.py +66 -0
  57. datafactory_priogrid/temporal_config.py +78 -0
  58. datafactory_priogrid/temporal_generator.py +65 -0
  59. datafactory_provenance/ARCHITECTURE.md +61 -0
  60. datafactory_provenance/__init__.py +81 -0
  61. datafactory_provenance/constants.py +3 -0
  62. datafactory_provenance/digests_and_ledgers.py +370 -0
  63. datafactory_provenance/health.py +310 -0
  64. datafactory_provenance/pipeline_lock.py +200 -0
  65. datafactory_provenance/registry.py +92 -0
  66. datafactory_provenance/skip.py +212 -0
  67. datafactory_provenance/source_registry.py +466 -0
  68. datafactory_query/ARCHITECTURE.md +60 -0
  69. datafactory_query/__init__.py +36 -0
  70. datafactory_query/africa_me_gaul_pgids.json +1 -0
  71. datafactory_query/africa_me_legacy_pgids.json +1 -0
  72. datafactory_query/backends_npy.py +90 -0
  73. datafactory_query/backends_zarr.py +259 -0
  74. datafactory_query/coverage.py +64 -0
  75. datafactory_query/dataset.py +263 -0
  76. datafactory_query/defaults.py +101 -0
  77. datafactory_query/land_gaul_pgids.json +1 -0
  78. datafactory_query/land_pgids.json +1 -0
  79. datafactory_query/output_format.py +52 -0
  80. datafactory_query/regions.py +293 -0
  81. datafactory_query/temporal.py +115 -0
  82. datafactory_viewpoint/ARCHITECTURE.md +68 -0
  83. datafactory_viewpoint/__init__.py +33 -0
  84. datafactory_viewpoint/builders/__init__.py +32 -0
  85. datafactory_viewpoint/builders/acled_v1.py +213 -0
  86. datafactory_viewpoint/builders/ghsbuilts_v1.py +351 -0
  87. datafactory_viewpoint/builders/ghspop_v1.py +471 -0
  88. datafactory_viewpoint/builders/shdi_v1.py +389 -0
  89. datafactory_viewpoint/builders/ucdp_v1.py +437 -0
  90. datafactory_viewpoint/builders/vdem_v1.py +419 -0
  91. datafactory_viewpoint/profiles.py +169 -0
  92. datafactory_viewpoint/raster_io.py +49 -0
  93. datafactory_viewpoint/spatial_distribution.py +203 -0
  94. datafactory_viewpoint/spatial_weights.py +207 -0
  95. datafactory_viewpoint/survivorship.py +108 -0
  96. datafactory_viewpoint/temporal.py +111 -0
  97. datafactory_viewpoint/temporal_distribution.py +295 -0
  98. datafactory_viewpoint/viewpoint_config.py +124 -0
  99. datafactory_viewpoint/viewpoint_result.py +33 -0
  100. views_datafactory-1.9.0.dist-info/METADATA +528 -0
  101. views_datafactory-1.9.0.dist-info/RECORD +103 -0
  102. views_datafactory-1.9.0.dist-info/WHEEL +4 -0
  103. views_datafactory-1.9.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,213 @@
1
+ """ACLED viewpoint v1 — daily events aggregated to monthly.
2
+
3
+ Reads the ACLED consolidated event store, assigns each daily event
4
+ to its calendar month (date_month), optionally filters by event type,
5
+ and writes a Parquet with one row per event.
6
+
7
+ No survivorship needed (single source type, no overlapping vintages).
8
+ No temporal distribution needed (daily events map 1:1 to months).
9
+
10
+ Implements ADR-014 (viewpoints as derived views).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import logging
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+
19
+ import pyarrow as pa
20
+ import pyarrow.compute as pc
21
+ import pyarrow.parquet as pq
22
+
23
+ from datafactory_provenance import (
24
+ DIGEST_SCHEME,
25
+ LEDGER_VERSION,
26
+ append_ledger_entry,
27
+ compute_file_digest,
28
+ )
29
+ from datafactory_viewpoint.builders import register_builder
30
+ from datafactory_viewpoint.viewpoint_result import ViewpointResult
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+ DATASET_ID = "acled_viewpoint"
35
+
36
+ REQUIRED_CONSOLIDATED_FIELDS: set[str] = {
37
+ "event_id_cnty",
38
+ "event_date",
39
+ "event_type",
40
+ "latitude",
41
+ "longitude",
42
+ "fatalities",
43
+ }
44
+
45
+ PRODUCED_FIELDS: tuple[str, ...] = ("date_month",)
46
+
47
+ STRIPPED_FIELDS: set[str] = {
48
+ "_source_type",
49
+ "_source_version",
50
+ "_ingested_at",
51
+ "_harvest_digest",
52
+ "_harvest_timestamp",
53
+ }
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class AcledViewpointConfig:
58
+ """Configuration for building an ACLED viewpoint.
59
+
60
+ Simpler than the UCDP ViewpointConfig — no survivorship or
61
+ distribution strategies needed.
62
+ """
63
+
64
+ consolidated_path: Path
65
+
66
+ output_path: Path = Path(
67
+ "data/viewpoint/acled_v1.parquet"
68
+ )
69
+ ledger_path: Path = Path(
70
+ "provenance/viewpoint/acled_v1_ledger.jsonl"
71
+ )
72
+
73
+ event_type_filter: tuple[str, ...] | None = None
74
+
75
+ version: str = "acled_v1"
76
+
77
+ def __post_init__(self) -> None:
78
+ if not self.version:
79
+ err_msg = "version must be non-empty"
80
+ logger.error(err_msg)
81
+ raise ValueError(err_msg)
82
+
83
+ @classmethod
84
+ def from_shortcuts(
85
+ cls, *, consolidated_path: Path,
86
+ ) -> AcledViewpointConfig:
87
+ """Construct config from minimal shortcut arguments."""
88
+ return cls(consolidated_path=consolidated_path)
89
+
90
+
91
+ def _assign_date_month(event_date: str) -> str:
92
+ """Extract YYYY-MM from a daily event_date string."""
93
+ return event_date[:7]
94
+
95
+
96
+ def build_acled_v1(
97
+ config: AcledViewpointConfig,
98
+ ) -> ViewpointResult:
99
+ """Build ACLED viewpoint v1 from a consolidated event store.
100
+
101
+ Returns:
102
+ ViewpointResult with record counts and output digest.
103
+ """
104
+ if not config.consolidated_path.exists():
105
+ err_msg = (
106
+ f"Consolidated store not found: "
107
+ f"{config.consolidated_path}"
108
+ )
109
+ logger.error(err_msg)
110
+ raise FileNotFoundError(err_msg)
111
+
112
+ schema = pq.read_schema(config.consolidated_path)
113
+ missing = REQUIRED_CONSOLIDATED_FIELDS - set(schema.names)
114
+ if missing:
115
+ err_msg = (
116
+ f"Consolidated store missing required fields: "
117
+ f"{sorted(missing)}"
118
+ )
119
+ logger.error(err_msg)
120
+ raise ValueError(err_msg)
121
+
122
+ skip_cols = STRIPPED_FIELDS - REQUIRED_CONSOLIDATED_FIELDS
123
+ keep_cols = [
124
+ c for c in schema.names
125
+ if c not in skip_cols
126
+ ]
127
+ table = pq.read_table(
128
+ config.consolidated_path, columns=keep_cols,
129
+ )
130
+ n_input = table.num_rows
131
+ if n_input == 0:
132
+ err_msg = "Consolidated store is empty"
133
+ logger.error(err_msg)
134
+ raise ValueError(err_msg)
135
+
136
+ logger.info(
137
+ "Read ACLED consolidated store: %d events from %s",
138
+ n_input,
139
+ config.consolidated_path,
140
+ )
141
+
142
+ n_filtered = 0
143
+
144
+ if config.event_type_filter is not None:
145
+ filter_set = pa.array(config.event_type_filter)
146
+ mask = pc.is_in(
147
+ table.column("event_type"), filter_set
148
+ )
149
+ n_before = table.num_rows
150
+ table = table.filter(mask)
151
+ n_filtered = n_before - table.num_rows
152
+ logger.info(
153
+ "Event type filter: %d → %d events (%d filtered)",
154
+ n_before,
155
+ table.num_rows,
156
+ n_filtered,
157
+ )
158
+
159
+ event_dates = table.column("event_date").to_pylist()
160
+ date_months = [_assign_date_month(d) for d in event_dates]
161
+ table = table.append_column(
162
+ "date_month",
163
+ pa.array(date_months, type=pa.string()),
164
+ )
165
+
166
+ n_output = table.num_rows
167
+
168
+ if n_input != n_output + n_filtered:
169
+ raise RuntimeError(
170
+ f"Count conservation violation: "
171
+ f"input ({n_input}) != "
172
+ f"output ({n_output}) + filtered ({n_filtered})"
173
+ )
174
+
175
+ config.output_path.parent.mkdir(parents=True, exist_ok=True)
176
+ pq.write_table(table, config.output_path)
177
+
178
+ output_digest = compute_file_digest(config.output_path)
179
+
180
+ append_ledger_entry(config.ledger_path, {
181
+ "dataset": DATASET_ID,
182
+ "version": config.version,
183
+ "event_type_filter": config.event_type_filter,
184
+ "n_events_input": n_input,
185
+ "n_events_output": n_output,
186
+ "n_filtered": n_filtered,
187
+ "output_path": str(config.output_path),
188
+ "output_digest": output_digest,
189
+ "ledger_version": LEDGER_VERSION,
190
+ "digest_algorithm": DIGEST_SCHEME,
191
+ })
192
+
193
+ logger.info(
194
+ "ACLED viewpoint %s built: %d → %d rows (digest: %s)",
195
+ config.version,
196
+ n_input,
197
+ n_output,
198
+ output_digest,
199
+ )
200
+
201
+ return ViewpointResult(
202
+ output_path=config.output_path,
203
+ n_events_input=n_input,
204
+ n_events_output=n_output,
205
+ n_summary_expanded=0,
206
+ n_spatially_distributed=0,
207
+ n_filtered=n_filtered,
208
+ output_digest=output_digest,
209
+ version=config.version,
210
+ )
211
+
212
+
213
+ register_builder("acled_v1", build_acled_v1)
@@ -0,0 +1,351 @@
1
+ """GHS-BUILT-S viewpoint v1 — spatial aggregation + temporal interpolation.
2
+
3
+ Reads GHS-BUILT-S 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 linear interpolation.
6
+
7
+ No consolidation layer (ADR-034: single release, nothing to merge).
8
+ Viewpoint reads directly from data/raw/ghsbuilts/.
9
+
10
+ Implements ADR-014 (viewpoints as derived views), ADR-034 (GHS-BUILT-S),
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 = "ghsbuilts_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
+ # ---- Config ----
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class GhsBuiltSViewpointConfig:
55
+ """Configuration for building a GHS-BUILT-S viewpoint.
56
+
57
+ Reads GeoTIFF files from source_dir (harvest output), aggregates
58
+ to PRIO-GRID resolution, interpolates to monthly, writes Parquet.
59
+ """
60
+
61
+ source_dir: Path
62
+
63
+ output_path: Path = Path("data/viewpoint/ghsbuilts_v1.parquet")
64
+ ledger_path: Path = Path(
65
+ "provenance/viewpoint/ghsbuilts_v1_ledger.jsonl"
66
+ )
67
+
68
+ epochs: tuple[int, ...] = KNOWN_EPOCHS
69
+ release: str = "R2023A"
70
+ resolution: str = "30ss"
71
+ crs: str = "4326"
72
+
73
+ aggregation: str = "sum"
74
+ temporal_interpolation: str = "linear"
75
+
76
+ start_year: int = 1975
77
+ start_month: int = 1
78
+ end_year: int = 2030
79
+ end_month: int = 12
80
+
81
+ version: str = "ghsbuilts_v1"
82
+
83
+ def __post_init__(self) -> None:
84
+ if not self.version:
85
+ err_msg = "version must be non-empty"
86
+ logger.error(err_msg)
87
+ raise ValueError(err_msg)
88
+ if not self.epochs:
89
+ err_msg = "At least one epoch is required"
90
+ logger.error(err_msg)
91
+ raise ValueError(err_msg)
92
+ for epoch in self.epochs:
93
+ if epoch not in KNOWN_EPOCHS:
94
+ err_msg = (
95
+ f"Unknown epoch {epoch}. "
96
+ f"Valid epochs: {KNOWN_EPOCHS}"
97
+ )
98
+ logger.error(err_msg)
99
+ raise ValueError(err_msg)
100
+ if self.temporal_interpolation not in VALID_TEMPORAL_INTERPOLATIONS:
101
+ err_msg = (
102
+ f"Unknown temporal_interpolation "
103
+ f"'{self.temporal_interpolation}'. "
104
+ f"Valid: {VALID_TEMPORAL_INTERPOLATIONS}"
105
+ )
106
+ logger.error(err_msg)
107
+ raise ValueError(err_msg)
108
+
109
+ @classmethod
110
+ def from_shortcuts(
111
+ cls, *, source_dir: Path,
112
+ ) -> GhsBuiltSViewpointConfig:
113
+ """Construct config from minimal shortcut arguments."""
114
+ return cls(source_dir=source_dir)
115
+
116
+ def tif_filename(self, epoch: int) -> str:
117
+ stem = (
118
+ f"GHS_BUILT_S_E{epoch}_GLOBE"
119
+ f"_{self.release}_{self.crs}_{self.resolution}"
120
+ )
121
+ return f"{stem}_V1_0.tif"
122
+
123
+
124
+ # ---- Spatial alignment ----
125
+
126
+ PRIO_NROW = 360
127
+ PRIO_NCOL = 720
128
+ GLOBE_PIXEL_ROWS = PRIO_NROW * PIXELS_PER_CELL # 21600
129
+ GLOBE_PIXEL_COLS = PRIO_NCOL * PIXELS_PER_CELL # 43200
130
+
131
+
132
+ # ---- Spatial aggregation ----
133
+
134
+
135
+ def _aggregate_with_alignment(
136
+ data: np.ndarray,
137
+ row_offset: int,
138
+ col_offset: int,
139
+ ) -> np.ndarray:
140
+ """Aggregate raw raster to PRIO-GRID via strip processing.
141
+
142
+ Combines alignment and aggregation without allocating a full
143
+ 21600x43200 globe array. Processes one PRIO-GRID row (60 pixel
144
+ rows) at a time — peak memory is raw_array + ~20 MB instead of
145
+ raw_array + globe_array.
146
+
147
+ GHS-BUILT-S is uint32 with no nodata sentinel — zero means
148
+ no built-up surface, which is a legitimate value that sums
149
+ correctly without masking.
150
+
151
+ Args:
152
+ data: Raw 2-D raster (e.g. 21384x43201).
153
+ row_offset: Globe pixel row where the raster's first row lands.
154
+ col_offset: Globe pixel column where the raster's first column
155
+ lands.
156
+
157
+ Returns:
158
+ 2-D float64 array of shape (360, 720) with built-up area sums.
159
+ """
160
+ p = PIXELS_PER_CELL
161
+ result = np.zeros((PRIO_NROW, PRIO_NCOL), dtype=np.float64)
162
+
163
+ for prio_row in range(PRIO_NROW):
164
+ globe_r0 = prio_row * p
165
+ raw_r0 = globe_r0 - row_offset
166
+ raw_r1 = raw_r0 + p
167
+
168
+ src_r0 = max(0, raw_r0)
169
+ src_r1 = min(data.shape[0], raw_r1)
170
+
171
+ if src_r0 >= src_r1:
172
+ continue
173
+
174
+ strip = data[src_r0:src_r1, :].astype(np.float64)
175
+
176
+ n_rows = strip.shape[0]
177
+ aligned = np.zeros(
178
+ (n_rows, GLOBE_PIXEL_COLS), dtype=np.float64,
179
+ )
180
+
181
+ dst_c0 = max(0, col_offset)
182
+ src_c0 = max(0, -col_offset)
183
+ n_cols = min(
184
+ strip.shape[1] - src_c0,
185
+ GLOBE_PIXEL_COLS - dst_c0,
186
+ )
187
+ if n_cols > 0:
188
+ aligned[:, dst_c0:dst_c0 + n_cols] = (
189
+ strip[:, src_c0:src_c0 + n_cols]
190
+ )
191
+ del strip
192
+
193
+ blocks = aligned.reshape(n_rows, PRIO_NCOL, p)
194
+ result[prio_row, :] = blocks.sum(
195
+ axis=(0, 2), dtype=np.float64,
196
+ )
197
+ del aligned
198
+
199
+ logger.info(
200
+ "Aggregated %dx%d raster to %dx%d PRIO-GRID "
201
+ "(row_offset=%d, col_offset=%d, strip processing)",
202
+ data.shape[0], data.shape[1],
203
+ PRIO_NROW, PRIO_NCOL,
204
+ row_offset, col_offset,
205
+ )
206
+
207
+ return result
208
+
209
+
210
+ # ---- Builder ----
211
+
212
+
213
+ def build_ghsbuilts_v1(
214
+ config: GhsBuiltSViewpointConfig,
215
+ ) -> ViewpointResult:
216
+ """Build GHS-BUILT-S viewpoint v1 from harvested GeoTIFF files.
217
+
218
+ For each epoch: read GeoTIFF, aggregate to PRIO-GRID, collect
219
+ per-cell values. Then interpolate all cells temporally and write
220
+ Parquet with (pgid, month_id, built_area).
221
+
222
+ Returns:
223
+ ViewpointResult with cell counts and output digest.
224
+ """
225
+ if not config.source_dir.exists():
226
+ err_msg = f"Source directory not found: {config.source_dir}"
227
+ logger.error(err_msg)
228
+ raise FileNotFoundError(err_msg)
229
+
230
+ # Read and aggregate each epoch
231
+ epoch_grids: dict[int, np.ndarray] = {}
232
+ for epoch in config.epochs:
233
+ tif_path = config.source_dir / config.tif_filename(epoch)
234
+ if not tif_path.exists():
235
+ err_msg = (
236
+ f"GeoTIFF not found for epoch {epoch}: {tif_path}"
237
+ )
238
+ logger.error(err_msg)
239
+ raise FileNotFoundError(err_msg)
240
+
241
+ logger.info("Reading epoch %d from %s", epoch, tif_path)
242
+ raw, tie_x, tie_y, sc_x, sc_y = read_geotiff(tif_path)
243
+
244
+ row_off = round((90.0 - tie_y) / sc_y)
245
+ col_off = round((tie_x - (-180.0)) / sc_x)
246
+ grid = _aggregate_with_alignment(raw, row_off, col_off)
247
+ del raw
248
+
249
+ epoch_grids[epoch] = grid
250
+ logger.info(
251
+ "Epoch %d: -> %dx%d cells, total built area %.0f m^2",
252
+ epoch,
253
+ grid.shape[0], grid.shape[1], grid.sum(),
254
+ )
255
+
256
+ prio_rows, prio_cols = next(iter(epoch_grids.values())).shape
257
+
258
+ # Build (pgid, month_id, built_area) rows
259
+ pgid_rows: list[int] = []
260
+ month_id_rows: list[int] = []
261
+ built_area_rows: list[float] = []
262
+
263
+ for row in range(prio_rows):
264
+ for col in range(prio_cols):
265
+ epoch_values = {
266
+ ep: float(grid[row, col])
267
+ for ep, grid in epoch_grids.items()
268
+ }
269
+
270
+ monthly = interpolate_temporal(
271
+ epoch_values,
272
+ strategy=config.temporal_interpolation,
273
+ start_year=config.start_year,
274
+ start_month=config.start_month,
275
+ end_year=config.end_year,
276
+ end_month=config.end_month,
277
+ )
278
+
279
+ # PRIO-GRID ID: row-major from bottom-left
280
+ # Row 0 in raster = north = top of grid = last PRIO row
281
+ prio_row = prio_rows - 1 - row
282
+ pgid = prio_row * prio_cols + col + 1
283
+
284
+ for i, area in enumerate(monthly):
285
+ if area == 0.0:
286
+ continue
287
+
288
+ year = config.start_year + (
289
+ config.start_month - 1 + i
290
+ ) // 12
291
+ month = (config.start_month - 1 + i) % 12 + 1
292
+ mid = (year - VIEWS_EPOCH_YEAR) * 12 + month
293
+
294
+ pgid_rows.append(pgid)
295
+ month_id_rows.append(mid)
296
+ built_area_rows.append(area)
297
+
298
+ # Write Parquet
299
+ table = pa.table({
300
+ "pgid": pa.array(pgid_rows, type=pa.int32()),
301
+ "month_id": pa.array(month_id_rows, type=pa.int32()),
302
+ "built_area": pa.array(built_area_rows, type=pa.float64()),
303
+ })
304
+ del pgid_rows, month_id_rows, built_area_rows
305
+
306
+ n_output = table.num_rows
307
+
308
+ config.output_path.parent.mkdir(parents=True, exist_ok=True)
309
+ pq.write_table(table, config.output_path)
310
+
311
+ output_digest = compute_file_digest(config.output_path)
312
+
313
+ append_ledger_entry(config.ledger_path, {
314
+ "dataset": DATASET_ID,
315
+ "version": config.version,
316
+ "epochs": list(config.epochs),
317
+ "aggregation": config.aggregation,
318
+ "temporal_interpolation": config.temporal_interpolation,
319
+ "n_epochs": len(config.epochs),
320
+ "n_cells_output": n_output,
321
+ "output_path": str(config.output_path),
322
+ "output_digest": output_digest,
323
+ "outcome": "success",
324
+ "ledger_version": LEDGER_VERSION,
325
+ "digest_algorithm": DIGEST_SCHEME,
326
+ })
327
+
328
+ logger.info(
329
+ "GHS-BUILT-S viewpoint %s built: %d epochs -> %d rows "
330
+ "(digest: %s)",
331
+ config.version,
332
+ len(config.epochs),
333
+ n_output,
334
+ output_digest,
335
+ )
336
+
337
+ return ViewpointResult(
338
+ output_path=config.output_path,
339
+ n_events_input=sum(
340
+ int(g.size) for g in epoch_grids.values()
341
+ ),
342
+ n_events_output=n_output,
343
+ n_summary_expanded=0,
344
+ n_spatially_distributed=0,
345
+ n_filtered=0,
346
+ output_digest=output_digest,
347
+ version=config.version,
348
+ )
349
+
350
+
351
+ register_builder("ghsbuilts_v1", build_ghsbuilts_v1)