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,352 @@
|
|
|
1
|
+
"""Grid compilation: place event data onto the spatiotemporal grid.
|
|
2
|
+
|
|
3
|
+
Reads viewpoint output Parquet, assigns each event to a (cell, month) bin,
|
|
4
|
+
aggregates using declared strategies, and outputs npy arrays with
|
|
5
|
+
sidecar coordinate files and provenance.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import tempfile
|
|
14
|
+
from collections import defaultdict
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
import pyarrow as pa
|
|
19
|
+
import pyarrow.parquet as pq
|
|
20
|
+
|
|
21
|
+
from datafactory_compilation.aggregation import get_strategy
|
|
22
|
+
from datafactory_compilation.compilation_config import CompilationConfig
|
|
23
|
+
from datafactory_compilation.conservation import (
|
|
24
|
+
PlacementAccounting,
|
|
25
|
+
assert_placement_conservation,
|
|
26
|
+
)
|
|
27
|
+
from datafactory_compilation.output import write_compilation_output
|
|
28
|
+
from datafactory_compilation.preflight import check_disk_space
|
|
29
|
+
from datafactory_priogrid.cell_generator import generate_grid
|
|
30
|
+
from datafactory_priogrid.temporal_generator import generate_time_steps
|
|
31
|
+
from datafactory_provenance import compute_file_digest
|
|
32
|
+
|
|
33
|
+
logger = logging.getLogger(__name__)
|
|
34
|
+
|
|
35
|
+
DATASET_ID = "compilation"
|
|
36
|
+
|
|
37
|
+
_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _required_columns(config: CompilationConfig) -> set[str]:
|
|
41
|
+
"""Derive the minimal set of Parquet columns needed for compilation."""
|
|
42
|
+
cols = {config.lat_field, config.lon_field, config.date_field}
|
|
43
|
+
for feat in config.features:
|
|
44
|
+
if feat.filter:
|
|
45
|
+
cols.update(feat.filter.keys())
|
|
46
|
+
if feat.strategy != "count" and feat.value_field:
|
|
47
|
+
cols.add(feat.value_field)
|
|
48
|
+
return cols
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _parse_month_index(
|
|
52
|
+
date_str: str,
|
|
53
|
+
start_year: int,
|
|
54
|
+
start_month: int,
|
|
55
|
+
) -> int | None:
|
|
56
|
+
"""Parse a date string (YYYY-MM-DD) to a 0-based monthly index.
|
|
57
|
+
|
|
58
|
+
Returns None if the date is outside the temporal range or malformed.
|
|
59
|
+
"""
|
|
60
|
+
if not _DATE_RE.match(date_str):
|
|
61
|
+
logger.warning("Malformed date string: %r", date_str)
|
|
62
|
+
return None
|
|
63
|
+
try:
|
|
64
|
+
parts = date_str.split("-")
|
|
65
|
+
year = int(parts[0])
|
|
66
|
+
month = int(parts[1])
|
|
67
|
+
except (ValueError, IndexError):
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
if not (1 <= month <= 12):
|
|
71
|
+
return None
|
|
72
|
+
|
|
73
|
+
idx = (year - start_year) * 12 + (month - start_month)
|
|
74
|
+
return idx if idx >= 0 else None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _place_events(
|
|
78
|
+
table: pa.Table,
|
|
79
|
+
config: CompilationConfig,
|
|
80
|
+
) -> tuple[
|
|
81
|
+
dict[tuple[int, int], np.ndarray], dict[str, np.ndarray]
|
|
82
|
+
]:
|
|
83
|
+
"""Assign events to (pgid_index, time_index) bins.
|
|
84
|
+
|
|
85
|
+
Extracts placement columns (lat, lon, date) as lists, computes
|
|
86
|
+
bin assignments, then extracts remaining columns as numpy arrays.
|
|
87
|
+
Returns row-index bins and column arrays for aggregation.
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
table: A PyArrow Table with event data.
|
|
91
|
+
config: Compilation configuration.
|
|
92
|
+
|
|
93
|
+
Returns:
|
|
94
|
+
Tuple of (bins, col_arrays) where bins maps
|
|
95
|
+
(pgid_idx, time_idx) to numpy arrays of row indices,
|
|
96
|
+
and col_arrays maps column names to numpy arrays.
|
|
97
|
+
"""
|
|
98
|
+
from datafactory_priogrid.cell_generator import latlon_to_pgid
|
|
99
|
+
|
|
100
|
+
n_cells = config.grid_config.n_cells
|
|
101
|
+
n_steps = config.temporal_config.n_steps
|
|
102
|
+
n_rows = table.num_rows
|
|
103
|
+
|
|
104
|
+
# Extract only placement columns as Python lists
|
|
105
|
+
lats = table[config.lat_field].to_pylist()
|
|
106
|
+
lons = table[config.lon_field].to_pylist()
|
|
107
|
+
dates = table[config.date_field].to_pylist()
|
|
108
|
+
|
|
109
|
+
# Phase 1: compute bin assignments (row_index → bin key)
|
|
110
|
+
row_bins: dict[int, tuple[int, int]] = {}
|
|
111
|
+
n_skipped_spatial = 0
|
|
112
|
+
n_skipped_temporal = 0
|
|
113
|
+
|
|
114
|
+
for i in range(n_rows):
|
|
115
|
+
lat, lon, date_str = lats[i], lons[i], dates[i]
|
|
116
|
+
|
|
117
|
+
if lat is None or lon is None:
|
|
118
|
+
n_skipped_spatial += 1
|
|
119
|
+
continue
|
|
120
|
+
|
|
121
|
+
try:
|
|
122
|
+
pgid = int(
|
|
123
|
+
latlon_to_pgid(
|
|
124
|
+
float(lat), float(lon), config.grid_config
|
|
125
|
+
)
|
|
126
|
+
)
|
|
127
|
+
except (ValueError, TypeError):
|
|
128
|
+
n_skipped_spatial += 1
|
|
129
|
+
continue
|
|
130
|
+
|
|
131
|
+
if pgid < 1 or pgid > n_cells:
|
|
132
|
+
n_skipped_spatial += 1
|
|
133
|
+
continue
|
|
134
|
+
|
|
135
|
+
if not isinstance(date_str, str):
|
|
136
|
+
n_skipped_temporal += 1
|
|
137
|
+
continue
|
|
138
|
+
|
|
139
|
+
time_idx = _parse_month_index(
|
|
140
|
+
date_str,
|
|
141
|
+
config.temporal_config.start_year,
|
|
142
|
+
config.temporal_config.start_month,
|
|
143
|
+
)
|
|
144
|
+
if time_idx is None or time_idx >= n_steps:
|
|
145
|
+
n_skipped_temporal += 1
|
|
146
|
+
continue
|
|
147
|
+
|
|
148
|
+
pgid_idx = pgid - 1
|
|
149
|
+
row_bins[i] = (pgid_idx, time_idx)
|
|
150
|
+
|
|
151
|
+
# ADR-040 Invariant 1: placed + excluded = input
|
|
152
|
+
assert_placement_conservation(PlacementAccounting(
|
|
153
|
+
n_input=n_rows,
|
|
154
|
+
n_placed=len(row_bins),
|
|
155
|
+
n_skipped_spatial=n_skipped_spatial,
|
|
156
|
+
n_skipped_temporal=n_skipped_temporal,
|
|
157
|
+
))
|
|
158
|
+
|
|
159
|
+
if n_skipped_spatial > 0:
|
|
160
|
+
logger.warning(
|
|
161
|
+
"Skipped %d events: invalid spatial coordinates",
|
|
162
|
+
n_skipped_spatial,
|
|
163
|
+
)
|
|
164
|
+
if n_skipped_temporal > 0:
|
|
165
|
+
logger.warning(
|
|
166
|
+
"Skipped %d events: outside temporal range",
|
|
167
|
+
n_skipped_temporal,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
# Phase 2: extract columns as numpy arrays, build row-index bins
|
|
171
|
+
if not row_bins:
|
|
172
|
+
logger.info("Placed 0 events into 0 non-empty bins")
|
|
173
|
+
return {}, {}
|
|
174
|
+
|
|
175
|
+
placement_cols = {
|
|
176
|
+
config.lat_field, config.lon_field, config.date_field,
|
|
177
|
+
}
|
|
178
|
+
col_arrays: dict[str, np.ndarray] = {
|
|
179
|
+
col: table[col].to_numpy(zero_copy_only=False)
|
|
180
|
+
for col in table.column_names
|
|
181
|
+
if col not in placement_cols
|
|
182
|
+
}
|
|
183
|
+
del table
|
|
184
|
+
|
|
185
|
+
idx_lists: dict[tuple[int, int], list[int]] = defaultdict(list)
|
|
186
|
+
for row_idx, bin_key in row_bins.items():
|
|
187
|
+
idx_lists[bin_key].append(row_idx)
|
|
188
|
+
bins = {
|
|
189
|
+
k: np.array(v, dtype=np.intp)
|
|
190
|
+
for k, v in idx_lists.items()
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
logger.info(
|
|
194
|
+
"Placed %d events into %d non-empty bins",
|
|
195
|
+
len(row_bins),
|
|
196
|
+
len(bins),
|
|
197
|
+
)
|
|
198
|
+
return bins, col_arrays
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def compile_grid(config: CompilationConfig) -> Path:
|
|
202
|
+
"""Compile source events onto the spatiotemporal grid.
|
|
203
|
+
|
|
204
|
+
Reads the source Parquet, places events onto the grid, aggregates
|
|
205
|
+
using declared strategies, and writes npy output with coordinate
|
|
206
|
+
sidecar files and provenance.
|
|
207
|
+
|
|
208
|
+
Args:
|
|
209
|
+
config: Compilation configuration.
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
Path to the output directory containing grid.npy and sidecars.
|
|
213
|
+
|
|
214
|
+
Raises:
|
|
215
|
+
FileNotFoundError: If source_path does not exist.
|
|
216
|
+
ValueError: If source Parquet lacks required columns.
|
|
217
|
+
"""
|
|
218
|
+
# Validate source exists
|
|
219
|
+
if not config.source_path.exists():
|
|
220
|
+
err_msg = f"Source file not found: {config.source_path}"
|
|
221
|
+
logger.error(err_msg)
|
|
222
|
+
raise FileNotFoundError(err_msg)
|
|
223
|
+
|
|
224
|
+
# Compute source digest (chunked to avoid doubling memory)
|
|
225
|
+
source_digest = compute_file_digest(config.source_path)
|
|
226
|
+
|
|
227
|
+
# Read only the columns needed for placement + aggregation
|
|
228
|
+
needed_cols = _required_columns(config)
|
|
229
|
+
available_cols = set(pq.read_schema(config.source_path).names)
|
|
230
|
+
missing_cols = needed_cols - available_cols
|
|
231
|
+
if missing_cols:
|
|
232
|
+
err_msg = (
|
|
233
|
+
f"Source Parquet missing required columns: {sorted(missing_cols)}. "
|
|
234
|
+
f"Available: {sorted(available_cols)}"
|
|
235
|
+
)
|
|
236
|
+
logger.error(err_msg)
|
|
237
|
+
raise ValueError(err_msg)
|
|
238
|
+
table = pq.read_table(config.source_path, columns=sorted(needed_cols))
|
|
239
|
+
|
|
240
|
+
# Place events into (cell, month) bins using columnar extraction.
|
|
241
|
+
# Placement columns (lat, lon, date) are read as lists;
|
|
242
|
+
# remaining columns are extracted as numpy arrays for aggregation.
|
|
243
|
+
logger.info("Read %d events from %s", table.num_rows, config.source_path)
|
|
244
|
+
bins, col_arrays = _place_events(table, config)
|
|
245
|
+
del table
|
|
246
|
+
|
|
247
|
+
# Build output array: [T, H, W, C] — canonical z-stack layout
|
|
248
|
+
nrow = config.grid_config.nrow
|
|
249
|
+
ncol = config.grid_config.ncol
|
|
250
|
+
n_steps = config.temporal_config.n_steps
|
|
251
|
+
n_features = len(config.features)
|
|
252
|
+
dtype = np.dtype(config.output_dtype)
|
|
253
|
+
|
|
254
|
+
config.output_dir.mkdir(parents=True, exist_ok=True)
|
|
255
|
+
check_disk_space(
|
|
256
|
+
config.output_dir,
|
|
257
|
+
n_steps * nrow * ncol * n_features * dtype.itemsize,
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
# Allocate grid as memory-mapped file (ADR-037).
|
|
261
|
+
# OS pages data in/out as needed — peak RSS stays bounded
|
|
262
|
+
# regardless of feature count.
|
|
263
|
+
tmp_fd, tmp_mmap_path = tempfile.mkstemp(
|
|
264
|
+
prefix="_memmap_", suffix=".npy",
|
|
265
|
+
dir=str(config.output_dir),
|
|
266
|
+
)
|
|
267
|
+
os.close(tmp_fd)
|
|
268
|
+
|
|
269
|
+
grid_array = None
|
|
270
|
+
try:
|
|
271
|
+
grid_array = np.lib.format.open_memmap(
|
|
272
|
+
tmp_mmap_path,
|
|
273
|
+
mode="w+",
|
|
274
|
+
dtype=dtype,
|
|
275
|
+
shape=(n_steps, nrow, ncol, n_features),
|
|
276
|
+
)
|
|
277
|
+
grid_array[:] = config.fill_value
|
|
278
|
+
|
|
279
|
+
# Resolve strategies
|
|
280
|
+
strategies = [
|
|
281
|
+
get_strategy(feat.strategy)
|
|
282
|
+
for feat in config.features
|
|
283
|
+
]
|
|
284
|
+
feature_names = [feat.name for feat in config.features]
|
|
285
|
+
|
|
286
|
+
# Aggregate using columnar lookups with ephemeral dicts.
|
|
287
|
+
# Memory bounded by max bin size (~100), not total events.
|
|
288
|
+
for (pgid_idx, time_idx), row_indices in sorted(
|
|
289
|
+
bins.items()
|
|
290
|
+
):
|
|
291
|
+
row = pgid_idx // ncol
|
|
292
|
+
col = pgid_idx % ncol
|
|
293
|
+
for feat_idx, (spec, strategy_fn) in enumerate(
|
|
294
|
+
zip(
|
|
295
|
+
config.features, strategies, strict=True,
|
|
296
|
+
)
|
|
297
|
+
):
|
|
298
|
+
if spec.filter:
|
|
299
|
+
mask = np.ones(
|
|
300
|
+
len(row_indices), dtype=bool,
|
|
301
|
+
)
|
|
302
|
+
for k, v in spec.filter.items():
|
|
303
|
+
mask &= (
|
|
304
|
+
col_arrays[k][row_indices] == v
|
|
305
|
+
)
|
|
306
|
+
filtered = row_indices[mask]
|
|
307
|
+
else:
|
|
308
|
+
filtered = row_indices
|
|
309
|
+
|
|
310
|
+
vf = spec.value_field
|
|
311
|
+
if vf and vf in col_arrays:
|
|
312
|
+
events = [
|
|
313
|
+
{vf: col_arrays[vf][i]}
|
|
314
|
+
for i in filtered
|
|
315
|
+
]
|
|
316
|
+
else:
|
|
317
|
+
events = [{} for _ in range(len(filtered))]
|
|
318
|
+
grid_array[time_idx, row, col, feat_idx] = (
|
|
319
|
+
strategy_fn(events, vf)
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
# Generate coordinate arrays
|
|
323
|
+
pgids_flat, _, _ = generate_grid(config.grid_config)
|
|
324
|
+
pgids_2d = pgids_flat.reshape(nrow, ncol)
|
|
325
|
+
time_steps = generate_time_steps(config.temporal_config)
|
|
326
|
+
|
|
327
|
+
# Write output
|
|
328
|
+
write_compilation_output(
|
|
329
|
+
grid_array=grid_array,
|
|
330
|
+
pgids_2d=pgids_2d,
|
|
331
|
+
time_steps=time_steps,
|
|
332
|
+
feature_names=feature_names,
|
|
333
|
+
output_dir=config.output_dir,
|
|
334
|
+
ledger_path=config.ledger_path,
|
|
335
|
+
dataset_id=DATASET_ID,
|
|
336
|
+
source_path=config.source_path,
|
|
337
|
+
source_digest=source_digest,
|
|
338
|
+
)
|
|
339
|
+
|
|
340
|
+
logger.info(
|
|
341
|
+
"Compiled grid: shape=%s, features=%s, output=%s",
|
|
342
|
+
grid_array.shape,
|
|
343
|
+
feature_names,
|
|
344
|
+
config.output_dir,
|
|
345
|
+
)
|
|
346
|
+
finally:
|
|
347
|
+
if grid_array is not None:
|
|
348
|
+
del grid_array
|
|
349
|
+
if os.path.exists(tmp_mmap_path):
|
|
350
|
+
os.unlink(tmp_mmap_path)
|
|
351
|
+
|
|
352
|
+
return config.output_dir
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Shared output writing for compilation modules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
from datafactory_provenance import (
|
|
13
|
+
DIGEST_SCHEME,
|
|
14
|
+
LEDGER_VERSION,
|
|
15
|
+
append_ledger_entry,
|
|
16
|
+
compute_file_digest,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def write_compilation_output(
|
|
23
|
+
*,
|
|
24
|
+
grid_array: np.ndarray,
|
|
25
|
+
pgids_2d: np.ndarray,
|
|
26
|
+
time_steps: np.ndarray,
|
|
27
|
+
feature_names: list[str],
|
|
28
|
+
output_dir: Path,
|
|
29
|
+
ledger_path: Path,
|
|
30
|
+
dataset_id: str,
|
|
31
|
+
source_path: Path,
|
|
32
|
+
source_digest: str,
|
|
33
|
+
n_placed: int | None = None,
|
|
34
|
+
n_skipped_spatial: int | None = None,
|
|
35
|
+
n_skipped_temporal: int | None = None,
|
|
36
|
+
) -> str:
|
|
37
|
+
"""Write grid output files, provenance, and ledger entry.
|
|
38
|
+
|
|
39
|
+
The three n_* parameters are pregridded-compilation diagnostics.
|
|
40
|
+
They are included in the ledger entry only when not None.
|
|
41
|
+
|
|
42
|
+
Returns the output digest string.
|
|
43
|
+
"""
|
|
44
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
45
|
+
|
|
46
|
+
grid_path = output_dir / "grid.npy"
|
|
47
|
+
np.save(grid_path, grid_array)
|
|
48
|
+
np.save(output_dir / "pgids.npy", pgids_2d)
|
|
49
|
+
np.save(output_dir / "time_steps.npy", time_steps)
|
|
50
|
+
(output_dir / "feature_names.json").write_text(
|
|
51
|
+
json.dumps(feature_names)
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
output_digest = compute_file_digest(grid_path)
|
|
55
|
+
|
|
56
|
+
provenance = {
|
|
57
|
+
"source_path": str(source_path),
|
|
58
|
+
"source_digest": source_digest,
|
|
59
|
+
"grid_shape": list(grid_array.shape),
|
|
60
|
+
"feature_names": feature_names,
|
|
61
|
+
"output_digest": output_digest,
|
|
62
|
+
}
|
|
63
|
+
provenance_path = output_dir / "provenance.json"
|
|
64
|
+
provenance_path.write_text(json.dumps(provenance, indent=2))
|
|
65
|
+
|
|
66
|
+
ledger_entry: dict[str, Any] = {
|
|
67
|
+
"dataset": dataset_id,
|
|
68
|
+
"source_path": str(source_path),
|
|
69
|
+
"source_digest": source_digest,
|
|
70
|
+
"grid_shape": list(grid_array.shape),
|
|
71
|
+
"feature_names": feature_names,
|
|
72
|
+
"output_dir": str(output_dir),
|
|
73
|
+
"output_digest": output_digest,
|
|
74
|
+
"ledger_version": LEDGER_VERSION,
|
|
75
|
+
"digest_algorithm": DIGEST_SCHEME,
|
|
76
|
+
}
|
|
77
|
+
if n_placed is not None:
|
|
78
|
+
ledger_entry["n_placed"] = n_placed
|
|
79
|
+
if n_skipped_spatial is not None:
|
|
80
|
+
ledger_entry["n_skipped_spatial"] = n_skipped_spatial
|
|
81
|
+
if n_skipped_temporal is not None:
|
|
82
|
+
ledger_entry["n_skipped_temporal"] = n_skipped_temporal
|
|
83
|
+
append_ledger_entry(ledger_path, ledger_entry)
|
|
84
|
+
|
|
85
|
+
return output_digest
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Pre-flight resource checks for compilation.
|
|
2
|
+
|
|
3
|
+
Validates disk space before allocating memory-mapped output grids.
|
|
4
|
+
Prevents cryptic ENOSPC errors by failing loudly with actionable
|
|
5
|
+
messages.
|
|
6
|
+
|
|
7
|
+
Ref: ADR-037 (bounded-memory compilation).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import logging
|
|
13
|
+
import shutil
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def estimate_grid_bytes(
|
|
20
|
+
n_months: int,
|
|
21
|
+
n_features: int,
|
|
22
|
+
*,
|
|
23
|
+
height: int = 360,
|
|
24
|
+
width: int = 720,
|
|
25
|
+
dtype_bytes: int = 4,
|
|
26
|
+
) -> int:
|
|
27
|
+
"""Estimate output grid size in bytes."""
|
|
28
|
+
return n_months * height * width * n_features * dtype_bytes
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def check_disk_space(
|
|
32
|
+
output_dir: Path,
|
|
33
|
+
required_bytes: int,
|
|
34
|
+
*,
|
|
35
|
+
margin: float = 1.2,
|
|
36
|
+
) -> None:
|
|
37
|
+
"""Fail loudly if insufficient disk space for compilation output.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
output_dir: Directory where output will be written.
|
|
41
|
+
required_bytes: Estimated output size in bytes.
|
|
42
|
+
margin: Safety margin multiplier (default 1.2 = 20%).
|
|
43
|
+
|
|
44
|
+
Raises:
|
|
45
|
+
RuntimeError: If free space < required_bytes * margin.
|
|
46
|
+
"""
|
|
47
|
+
free = shutil.disk_usage(output_dir).free
|
|
48
|
+
needed = int(required_bytes * margin)
|
|
49
|
+
if free < needed:
|
|
50
|
+
raise RuntimeError(
|
|
51
|
+
f"Insufficient disk space in {output_dir}: "
|
|
52
|
+
f"need {needed / 1e9:.1f} GB "
|
|
53
|
+
f"(including {int((margin - 1) * 100)}% margin), "
|
|
54
|
+
f"have {free / 1e9:.1f} GB free. "
|
|
55
|
+
f"Free up space or reduce feature count."
|
|
56
|
+
)
|
|
57
|
+
logger.info(
|
|
58
|
+
"Disk space OK: %.1f GB free, %.1f GB needed",
|
|
59
|
+
free / 1e9,
|
|
60
|
+
required_bytes / 1e9,
|
|
61
|
+
)
|