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,350 @@
|
|
|
1
|
+
"""V-Dem (Varieties of Democracy) harvester — CSV download.
|
|
2
|
+
|
|
3
|
+
Downloads V-Dem country-year data from the V-Dem distribution,
|
|
4
|
+
filters to the 22 variables used by production models, and stores
|
|
5
|
+
as Parquet. No authentication required.
|
|
6
|
+
|
|
7
|
+
Source: V-Dem Institute, University of Gothenburg (CC-BY-SA 4.0)
|
|
8
|
+
https://www.v-dem.net/
|
|
9
|
+
|
|
10
|
+
Ref: ADR-035 (V-Dem source selection).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import io
|
|
16
|
+
import logging
|
|
17
|
+
import time
|
|
18
|
+
import zipfile
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
import pyarrow as pa
|
|
23
|
+
import pyarrow.csv as pcsv
|
|
24
|
+
import pyarrow.parquet as pq
|
|
25
|
+
import requests as _requests
|
|
26
|
+
|
|
27
|
+
from datafactory_harvester.sources import register_source
|
|
28
|
+
from datafactory_harvester.validation import (
|
|
29
|
+
validate_nonempty_string,
|
|
30
|
+
validate_positive_int,
|
|
31
|
+
validate_string_tuple,
|
|
32
|
+
)
|
|
33
|
+
from datafactory_http import request_with_retry
|
|
34
|
+
from datafactory_provenance import (
|
|
35
|
+
DIGEST_SCHEME,
|
|
36
|
+
LEDGER_VERSION,
|
|
37
|
+
append_ledger_entry,
|
|
38
|
+
compute_content_digest,
|
|
39
|
+
last_digest_for_version,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
logger = logging.getLogger(__name__)
|
|
43
|
+
|
|
44
|
+
DATASET_ID = "vdem"
|
|
45
|
+
|
|
46
|
+
VDEM_VARIABLES: tuple[str, ...] = (
|
|
47
|
+
"v2xcl_dmove",
|
|
48
|
+
"v2xeg_eqdr",
|
|
49
|
+
"v2xpe_exlsocgr",
|
|
50
|
+
"v2x_clphy",
|
|
51
|
+
"v2xcl_prpty",
|
|
52
|
+
"v2x_ex_military",
|
|
53
|
+
"v2x_ex_party",
|
|
54
|
+
"v2x_horacc",
|
|
55
|
+
"v2xnp_client",
|
|
56
|
+
"v2xnp_regcorr",
|
|
57
|
+
"v2xpe_exlgeo",
|
|
58
|
+
"v2x_veracc",
|
|
59
|
+
"v2xpe_exlpol",
|
|
60
|
+
"v2x_diagacc",
|
|
61
|
+
"v2x_divparctrl",
|
|
62
|
+
"v2xeg_eqprotec",
|
|
63
|
+
"v2x_genpp",
|
|
64
|
+
"v2xpe_exlgender",
|
|
65
|
+
"v2x_hosabort",
|
|
66
|
+
"v2x_libdem",
|
|
67
|
+
"v2xcl_rol",
|
|
68
|
+
"v2x_accountability",
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
VDEM_ID_COLUMNS: tuple[str, ...] = (
|
|
72
|
+
"country_text_id",
|
|
73
|
+
"year",
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
DEFAULT_DOWNLOAD_URL = (
|
|
77
|
+
"https://v-dem.net/media/datasets/V-Dem-CY-FullOthers-v16_csv.zip"
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
# ---- Config ----
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass(frozen=True)
|
|
85
|
+
class VdemConfig:
|
|
86
|
+
"""Configuration for harvesting V-Dem country-year data.
|
|
87
|
+
|
|
88
|
+
Downloads the V-Dem CSV (inside ZIP), filters to declared
|
|
89
|
+
variables, and stores as Parquet.
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
download_url: str = DEFAULT_DOWNLOAD_URL
|
|
93
|
+
variables: tuple[str, ...] = VDEM_VARIABLES
|
|
94
|
+
data_dir: Path = Path("data/raw/vdem")
|
|
95
|
+
ledger_path: Path = Path(
|
|
96
|
+
"provenance/vdem/ingestion_ledger.jsonl"
|
|
97
|
+
)
|
|
98
|
+
version: str = "v16"
|
|
99
|
+
timeout: int = 300
|
|
100
|
+
|
|
101
|
+
def __post_init__(self) -> None:
|
|
102
|
+
validate_string_tuple(self.variables, "variables")
|
|
103
|
+
validate_positive_int(self.timeout, "timeout")
|
|
104
|
+
validate_nonempty_string(self.version, "version")
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def output_path(self) -> Path:
|
|
108
|
+
return self.data_dir / f"vdem_{self.version}.parquet"
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
# ---- Fetch ----
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def fetch_vdem(
|
|
115
|
+
config: VdemConfig | None = None,
|
|
116
|
+
*,
|
|
117
|
+
force_refresh: bool = False,
|
|
118
|
+
) -> dict:
|
|
119
|
+
"""Download V-Dem CSV and store as filtered Parquet.
|
|
120
|
+
|
|
121
|
+
1. Check cache (Parquet exists + ledger has digest) → skip
|
|
122
|
+
2. Download ZIP from V-Dem distribution (~80 MB compressed)
|
|
123
|
+
3. Extract CSV, read only needed columns
|
|
124
|
+
4. Write filtered Parquet to data_dir
|
|
125
|
+
5. Record provenance in ledger
|
|
126
|
+
|
|
127
|
+
Args:
|
|
128
|
+
config: Harvest configuration. Defaults to VdemConfig().
|
|
129
|
+
force_refresh: Re-download even if cached.
|
|
130
|
+
|
|
131
|
+
Returns:
|
|
132
|
+
Result dict with dataset, version, outcome, content_digest.
|
|
133
|
+
|
|
134
|
+
Raises:
|
|
135
|
+
requests.ConnectionError: Network failure (after retries).
|
|
136
|
+
zipfile.BadZipFile: Downloaded content is not a valid ZIP.
|
|
137
|
+
ValueError: CSV missing required columns.
|
|
138
|
+
"""
|
|
139
|
+
if config is None:
|
|
140
|
+
config = VdemConfig()
|
|
141
|
+
|
|
142
|
+
config.data_dir.mkdir(parents=True, exist_ok=True)
|
|
143
|
+
|
|
144
|
+
output_path = config.output_path
|
|
145
|
+
|
|
146
|
+
# Cache check
|
|
147
|
+
if not force_refresh and output_path.exists():
|
|
148
|
+
previous = last_digest_for_version(
|
|
149
|
+
config.ledger_path, config.version
|
|
150
|
+
)
|
|
151
|
+
if previous is not None:
|
|
152
|
+
logger.info(
|
|
153
|
+
"V-Dem %s cached (digest: %s)",
|
|
154
|
+
config.version, previous,
|
|
155
|
+
)
|
|
156
|
+
return {
|
|
157
|
+
"dataset": DATASET_ID,
|
|
158
|
+
"version": config.version,
|
|
159
|
+
"outcome": "cached",
|
|
160
|
+
"content_digest": previous,
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
# Download
|
|
164
|
+
logger.info(
|
|
165
|
+
"Downloading V-Dem %s from %s ...",
|
|
166
|
+
config.version, config.download_url,
|
|
167
|
+
)
|
|
168
|
+
t0 = time.monotonic()
|
|
169
|
+
|
|
170
|
+
try:
|
|
171
|
+
resp = request_with_retry(
|
|
172
|
+
config.download_url, timeout=config.timeout
|
|
173
|
+
)
|
|
174
|
+
except _requests.RequestException:
|
|
175
|
+
logger.error(
|
|
176
|
+
"Download failed for V-Dem %s", config.version
|
|
177
|
+
)
|
|
178
|
+
append_ledger_entry(config.ledger_path, {
|
|
179
|
+
"dataset": DATASET_ID,
|
|
180
|
+
"version": config.version,
|
|
181
|
+
"outcome": "failed",
|
|
182
|
+
"ledger_version": LEDGER_VERSION,
|
|
183
|
+
"digest_algorithm": DIGEST_SCHEME,
|
|
184
|
+
})
|
|
185
|
+
raise
|
|
186
|
+
|
|
187
|
+
content = resp.content
|
|
188
|
+
elapsed = time.monotonic() - t0
|
|
189
|
+
size_mb = len(content) / 1e6
|
|
190
|
+
logger.info("Downloaded %.0f MB in %.1fs", size_mb, elapsed)
|
|
191
|
+
|
|
192
|
+
# Extract CSV from ZIP
|
|
193
|
+
csv_bytes = _extract_csv_from_zip(content, config)
|
|
194
|
+
|
|
195
|
+
# Parse CSV and filter columns
|
|
196
|
+
try:
|
|
197
|
+
table = _parse_and_filter(csv_bytes, config)
|
|
198
|
+
except ValueError as exc:
|
|
199
|
+
append_ledger_entry(config.ledger_path, {
|
|
200
|
+
"dataset": DATASET_ID,
|
|
201
|
+
"version": config.version,
|
|
202
|
+
"outcome": "failed",
|
|
203
|
+
"reason": str(exc),
|
|
204
|
+
"ledger_version": LEDGER_VERSION,
|
|
205
|
+
"digest_algorithm": DIGEST_SCHEME,
|
|
206
|
+
})
|
|
207
|
+
raise
|
|
208
|
+
|
|
209
|
+
if table.num_rows == 0:
|
|
210
|
+
msg = "V-Dem CSV produced zero rows after filtering"
|
|
211
|
+
logger.error(msg)
|
|
212
|
+
append_ledger_entry(config.ledger_path, {
|
|
213
|
+
"dataset": DATASET_ID,
|
|
214
|
+
"version": config.version,
|
|
215
|
+
"outcome": "failed",
|
|
216
|
+
"reason": msg,
|
|
217
|
+
"ledger_version": LEDGER_VERSION,
|
|
218
|
+
"digest_algorithm": DIGEST_SCHEME,
|
|
219
|
+
})
|
|
220
|
+
raise ValueError(msg)
|
|
221
|
+
|
|
222
|
+
# Write Parquet
|
|
223
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
224
|
+
pq.write_table(table, output_path, compression="snappy")
|
|
225
|
+
|
|
226
|
+
# Provenance
|
|
227
|
+
content_digest = compute_content_digest(csv_bytes)
|
|
228
|
+
|
|
229
|
+
previous = last_digest_for_version(
|
|
230
|
+
config.ledger_path, config.version
|
|
231
|
+
)
|
|
232
|
+
outcome = (
|
|
233
|
+
"unchanged" if previous == content_digest else "success"
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
country_col = table.column("country_text_id").to_pylist()
|
|
237
|
+
n_countries = len(set(country_col))
|
|
238
|
+
year_col = table.column("year").to_pylist()
|
|
239
|
+
min_year = int(min(year_col))
|
|
240
|
+
max_year = int(max(year_col))
|
|
241
|
+
|
|
242
|
+
append_ledger_entry(config.ledger_path, {
|
|
243
|
+
"dataset": DATASET_ID,
|
|
244
|
+
"version": config.version,
|
|
245
|
+
"n_rows": table.num_rows,
|
|
246
|
+
"n_variables": len(config.variables),
|
|
247
|
+
"n_countries": n_countries,
|
|
248
|
+
"year_range": [min_year, max_year],
|
|
249
|
+
"content_digest": content_digest,
|
|
250
|
+
"outcome": outcome,
|
|
251
|
+
"ledger_version": LEDGER_VERSION,
|
|
252
|
+
"digest_algorithm": DIGEST_SCHEME,
|
|
253
|
+
})
|
|
254
|
+
|
|
255
|
+
logger.info(
|
|
256
|
+
"V-Dem %s: %d rows, %d variables, years %d–%d "
|
|
257
|
+
"(digest: %s)",
|
|
258
|
+
config.version,
|
|
259
|
+
table.num_rows,
|
|
260
|
+
len(config.variables),
|
|
261
|
+
min_year, max_year,
|
|
262
|
+
content_digest,
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
return {
|
|
266
|
+
"dataset": DATASET_ID,
|
|
267
|
+
"version": config.version,
|
|
268
|
+
"outcome": outcome,
|
|
269
|
+
"content_digest": content_digest,
|
|
270
|
+
"n_rows": table.num_rows,
|
|
271
|
+
"path": str(output_path),
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _extract_csv_from_zip(
|
|
276
|
+
content: bytes,
|
|
277
|
+
config: VdemConfig,
|
|
278
|
+
) -> bytes:
|
|
279
|
+
"""Extract the CSV file from V-Dem ZIP archive."""
|
|
280
|
+
try:
|
|
281
|
+
zf = zipfile.ZipFile(io.BytesIO(content))
|
|
282
|
+
except zipfile.BadZipFile:
|
|
283
|
+
logger.error("Bad ZIP file for V-Dem %s", config.version)
|
|
284
|
+
append_ledger_entry(config.ledger_path, {
|
|
285
|
+
"dataset": DATASET_ID,
|
|
286
|
+
"version": config.version,
|
|
287
|
+
"outcome": "failed",
|
|
288
|
+
"reason": "Bad ZIP file",
|
|
289
|
+
"ledger_version": LEDGER_VERSION,
|
|
290
|
+
"digest_algorithm": DIGEST_SCHEME,
|
|
291
|
+
})
|
|
292
|
+
raise
|
|
293
|
+
|
|
294
|
+
with zf:
|
|
295
|
+
csv_files = [
|
|
296
|
+
n for n in zf.namelist()
|
|
297
|
+
if n.endswith(".csv")
|
|
298
|
+
]
|
|
299
|
+
if not csv_files:
|
|
300
|
+
msg = (
|
|
301
|
+
f"No CSV found in V-Dem ZIP. "
|
|
302
|
+
f"Contents: {zf.namelist()}"
|
|
303
|
+
)
|
|
304
|
+
logger.error(msg)
|
|
305
|
+
append_ledger_entry(config.ledger_path, {
|
|
306
|
+
"dataset": DATASET_ID,
|
|
307
|
+
"version": config.version,
|
|
308
|
+
"outcome": "failed",
|
|
309
|
+
"reason": msg,
|
|
310
|
+
"ledger_version": LEDGER_VERSION,
|
|
311
|
+
"digest_algorithm": DIGEST_SCHEME,
|
|
312
|
+
})
|
|
313
|
+
raise ValueError(msg)
|
|
314
|
+
|
|
315
|
+
csv_name = csv_files[0]
|
|
316
|
+
logger.info("Extracting %s from ZIP", csv_name)
|
|
317
|
+
return zf.read(csv_name)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _parse_and_filter(
|
|
321
|
+
csv_bytes: bytes,
|
|
322
|
+
config: VdemConfig,
|
|
323
|
+
) -> pa.Table:
|
|
324
|
+
"""Parse V-Dem CSV and filter to requested columns."""
|
|
325
|
+
needed_cols = list(VDEM_ID_COLUMNS) + list(config.variables)
|
|
326
|
+
|
|
327
|
+
read_opts = pcsv.ReadOptions(
|
|
328
|
+
column_names=None,
|
|
329
|
+
autogenerate_column_names=False,
|
|
330
|
+
)
|
|
331
|
+
convert_opts = pcsv.ConvertOptions(
|
|
332
|
+
include_columns=needed_cols,
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
try:
|
|
336
|
+
table = pcsv.read_csv(
|
|
337
|
+
io.BytesIO(csv_bytes),
|
|
338
|
+
read_options=read_opts,
|
|
339
|
+
convert_options=convert_opts,
|
|
340
|
+
)
|
|
341
|
+
except (pa.ArrowInvalid, pa.ArrowKeyError) as exc:
|
|
342
|
+
msg = f"V-Dem CSV missing required columns: {exc}"
|
|
343
|
+
logger.error(msg)
|
|
344
|
+
raise ValueError(msg) from exc
|
|
345
|
+
|
|
346
|
+
return table
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
# Auto-register
|
|
350
|
+
register_source("vdem", fetch_vdem)
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Shared config validation utilities for harvester dataclasses.
|
|
2
|
+
|
|
3
|
+
Each function raises ``ValueError`` with a descriptive message on
|
|
4
|
+
invalid input. Designed for use in ``__post_init__`` of frozen
|
|
5
|
+
dataclasses — call the relevant validators instead of writing
|
|
6
|
+
inline ``if … raise`` blocks.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"validate_month",
|
|
13
|
+
"validate_nonempty_string",
|
|
14
|
+
"validate_positive_float",
|
|
15
|
+
"validate_positive_int",
|
|
16
|
+
"validate_string_tuple",
|
|
17
|
+
"validate_year_range",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def validate_positive_int(value: int, name: str) -> None:
|
|
22
|
+
"""Raise if *value* < 1."""
|
|
23
|
+
if value < 1:
|
|
24
|
+
msg = f"{name} must be >= 1, got {value}"
|
|
25
|
+
raise ValueError(msg)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def validate_positive_float(value: float, name: str) -> None:
|
|
29
|
+
"""Raise if *value* <= 0."""
|
|
30
|
+
if value <= 0:
|
|
31
|
+
msg = f"{name} must be > 0, got {value}"
|
|
32
|
+
raise ValueError(msg)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def validate_nonempty_string(value: str, name: str) -> None:
|
|
36
|
+
"""Raise if *value* is empty."""
|
|
37
|
+
if not value:
|
|
38
|
+
msg = f"{name} must be non-empty"
|
|
39
|
+
raise ValueError(msg)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def validate_string_tuple(
|
|
43
|
+
values: tuple[str, ...], name: str,
|
|
44
|
+
) -> None:
|
|
45
|
+
"""Raise if *values* is empty, contains empty strings, or has duplicates."""
|
|
46
|
+
if not values:
|
|
47
|
+
msg = f"{name} must be non-empty"
|
|
48
|
+
raise ValueError(msg)
|
|
49
|
+
seen: set[str] = set()
|
|
50
|
+
for v in values:
|
|
51
|
+
if not v:
|
|
52
|
+
msg = f"{name} must not contain empty strings"
|
|
53
|
+
raise ValueError(msg)
|
|
54
|
+
if v in seen:
|
|
55
|
+
msg = f"duplicate variable: {v}"
|
|
56
|
+
raise ValueError(msg)
|
|
57
|
+
seen.add(v)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def validate_month(value: int, name: str) -> None:
|
|
61
|
+
"""Raise if *value* not in [1, 12]."""
|
|
62
|
+
if not (1 <= value <= 12):
|
|
63
|
+
msg = f"{name} must be in [1, 12], got {value}"
|
|
64
|
+
raise ValueError(msg)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def validate_year_range(start_year: int, end_year: int) -> None:
|
|
68
|
+
"""Raise if *end_year* < *start_year*."""
|
|
69
|
+
if end_year < start_year:
|
|
70
|
+
msg = (
|
|
71
|
+
f"end_year ({end_year}) must be >= "
|
|
72
|
+
f"start_year ({start_year})"
|
|
73
|
+
)
|
|
74
|
+
raise ValueError(msg)
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""HTTP request utilities — retry with exponential backoff.
|
|
2
|
+
|
|
3
|
+
Shared across datafactory_harvester and datafactory_priogrid.
|
|
4
|
+
No outbound imports to other datafactory_* packages.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
import random
|
|
11
|
+
import time
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import requests
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def request_with_retry(
|
|
20
|
+
url: str,
|
|
21
|
+
*,
|
|
22
|
+
method: str = "GET",
|
|
23
|
+
headers: dict[str, str] | None = None,
|
|
24
|
+
params: dict[str, Any] | None = None,
|
|
25
|
+
data: dict[str, Any] | None = None,
|
|
26
|
+
json_payload: dict[str, Any] | None = None,
|
|
27
|
+
max_retries: int = 3,
|
|
28
|
+
timeout: int = 30,
|
|
29
|
+
) -> requests.Response:
|
|
30
|
+
"""HTTP request with exponential backoff retry.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
url: URL to request.
|
|
34
|
+
method: HTTP method (GET, POST, etc.).
|
|
35
|
+
headers: Optional HTTP headers.
|
|
36
|
+
params: Optional query parameters.
|
|
37
|
+
data: Optional form-encoded body (POST/PUT).
|
|
38
|
+
json_payload: Optional JSON body (POST/PUT).
|
|
39
|
+
max_retries: Maximum number of attempts.
|
|
40
|
+
timeout: Request timeout in seconds.
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
The successful response.
|
|
44
|
+
|
|
45
|
+
Raises:
|
|
46
|
+
requests.RequestException: After all retries exhausted.
|
|
47
|
+
"""
|
|
48
|
+
for attempt in range(max_retries):
|
|
49
|
+
try:
|
|
50
|
+
resp = requests.request(
|
|
51
|
+
method,
|
|
52
|
+
url,
|
|
53
|
+
headers=headers,
|
|
54
|
+
params=params,
|
|
55
|
+
data=data,
|
|
56
|
+
json=json_payload,
|
|
57
|
+
timeout=timeout,
|
|
58
|
+
)
|
|
59
|
+
resp.raise_for_status()
|
|
60
|
+
return resp
|
|
61
|
+
except requests.HTTPError as exc:
|
|
62
|
+
# 4xx client errors will never succeed on retry — fail fast
|
|
63
|
+
if (
|
|
64
|
+
exc.response is not None
|
|
65
|
+
and 400 <= exc.response.status_code < 500
|
|
66
|
+
):
|
|
67
|
+
logger.error(
|
|
68
|
+
"Client error %d (not retryable): %s",
|
|
69
|
+
exc.response.status_code,
|
|
70
|
+
url,
|
|
71
|
+
)
|
|
72
|
+
raise
|
|
73
|
+
_retry_or_raise(attempt, max_retries, url)
|
|
74
|
+
except requests.RequestException:
|
|
75
|
+
_retry_or_raise(attempt, max_retries, url)
|
|
76
|
+
msg = "Unreachable"
|
|
77
|
+
raise AssertionError(msg)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _retry_or_raise(
|
|
81
|
+
attempt: int, max_retries: int, url: str
|
|
82
|
+
) -> None:
|
|
83
|
+
"""Log and sleep for retry, or raise on final attempt.
|
|
84
|
+
|
|
85
|
+
Must be called from an except block — bare raise re-raises
|
|
86
|
+
the caller's active exception.
|
|
87
|
+
"""
|
|
88
|
+
if attempt == max_retries - 1:
|
|
89
|
+
logger.error(
|
|
90
|
+
"Request failed after %d attempts: %s",
|
|
91
|
+
max_retries,
|
|
92
|
+
url,
|
|
93
|
+
)
|
|
94
|
+
raise
|
|
95
|
+
delay = 2**attempt + random.uniform(0, 1)
|
|
96
|
+
logger.warning(
|
|
97
|
+
"Request attempt %d/%d failed, retrying in %.1fs",
|
|
98
|
+
attempt + 1,
|
|
99
|
+
max_retries,
|
|
100
|
+
delay,
|
|
101
|
+
)
|
|
102
|
+
time.sleep(delay)
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# datafactory_priogrid -- Architecture
|
|
2
|
+
|
|
3
|
+
## Purpose
|
|
4
|
+
|
|
5
|
+
PRIO-GRID spatial backbone and temporal backbone. Defines the shared coordinate system that all compiled data aligns to: 259,200 cells at 0.5 degree resolution, monthly time steps from 1989 to 2024. Pure numpy with zero external data dependencies for grid generation. This is a Layer 1 package in the dependency DAG (ADR-012).
|
|
6
|
+
|
|
7
|
+
**Migration source:** `lab_grid/` in views-metric-lab (868 LOC).
|
|
8
|
+
|
|
9
|
+
## Responsibility Boundary
|
|
10
|
+
|
|
11
|
+
**Owns:**
|
|
12
|
+
- Spatial grid definition (PRIO-GRID: 360 rows x 720 columns, 0.5 deg, row-major from bottom-left, 1-indexed pgids)
|
|
13
|
+
- Temporal backbone definition (monthly, 1989-2024, VIEWS month_id adapter)
|
|
14
|
+
- Composed spatiotemporal grid (GridConfig + TemporalConfig)
|
|
15
|
+
- Coordinate array generation (pgids, latitudes, longitudes, time steps)
|
|
16
|
+
- Parity validation against PRIO reference shapefile (one-time)
|
|
17
|
+
- Pluggable shapefile reader via Protocol (DIP)
|
|
18
|
+
|
|
19
|
+
**Does NOT own:**
|
|
20
|
+
- Data values (no event counts, fatalities, or features)
|
|
21
|
+
- Source-specific logic (no UCDP, no ACLED)
|
|
22
|
+
- Compilation (no event-to-grid placement)
|
|
23
|
+
- Consumer formatting (no model-specific output)
|
|
24
|
+
- Provenance tracking (uses core's utilities)
|
|
25
|
+
|
|
26
|
+
## Dependency Rules
|
|
27
|
+
|
|
28
|
+
**May import:** `datafactory_provenance`, numpy, pyshp (shapefile reader only)
|
|
29
|
+
**Must never import:** `datafactory_harvester`, `datafactory_compilation`, or any consumer
|
|
30
|
+
|
|
31
|
+
## Key Concepts
|
|
32
|
+
|
|
33
|
+
| Concept | Description |
|
|
34
|
+
|---------|-------------|
|
|
35
|
+
| GridConfig | Frozen dataclass: resolution, bounds, CRS. Validated in `__post_init__`. Default: 0.5 deg, global extent, 360x720 grid. |
|
|
36
|
+
| TemporalConfig | Frozen dataclass: start/end year and month. Validates range constraints. VIEWS month_id adapter (month_id 1 = January 1980). |
|
|
37
|
+
| SpatioTemporalGrid | Composes GridConfig + TemporalConfig. Lazy coordinate generation via `cached_property`. |
|
|
38
|
+
| generate_grid | Pure numpy: generates pgid array, bounding box arrays, lat/lon coordinate arrays. |
|
|
39
|
+
| generate_time_steps | Generates `datetime64[M]` array. Converts to/from VIEWS month_id. |
|
|
40
|
+
| ReferenceGeometryReader | Protocol for pluggable shapefile readers. Decouples validation from pyshp. |
|
|
41
|
+
| validate_parity | Validates generated grid against PRIO reference shapefile. Records result to provenance ledger. |
|
|
42
|
+
| land_mask | Fetches land cell pgids from PRIO-GRID API (`landarea` variable, 64,818 cells). Cached to disk. Not auto-imported (avoids pulling `requests`). |
|
|
43
|
+
|
|
44
|
+
## Invariants
|
|
45
|
+
- **Single-writer access assumed.** No concurrent operations supported (see technical_risk_register_resolved.md C-16)
|
|
46
|
+
|
|
47
|
+
- Default configuration produces exactly 259,200 cells (360 x 720)
|
|
48
|
+
- pgid numbering: row-major from bottom-left, 1-indexed (pgid 1 is southwest corner)
|
|
49
|
+
- Temporal backbone uses VIEWS month_id convention: month_id = (year - 1980) * 12 + month
|
|
50
|
+
- Grid resolution must evenly divide the spatial extent (validated in `__post_init__`)
|
|
51
|
+
- start_year <= end_year (validated in `__post_init__`)
|
|
52
|
+
- Coordinate arrays are generated lazily but are deterministic
|
|
53
|
+
- Pure numpy: no heavy geospatial libraries (NF-6)
|
|
54
|
+
|
|
55
|
+
## Intent Contracts
|
|
56
|
+
|
|
57
|
+
Formal CICs for this module's non-trivial classes:
|
|
58
|
+
|
|
59
|
+
- [GridConfig](../../docs/CICs/GridConfig.md)
|
|
60
|
+
- [TemporalConfig](../../docs/CICs/TemporalConfig.md)
|
|
61
|
+
- [SpatioTemporalGrid](../../docs/CICs/SpatioTemporalGrid.md)
|
|
62
|
+
- [ShapefileHarvesterConfig](../../docs/CICs/ShapefileHarvesterConfig.md)
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""PRIO-GRID spatial and temporal backbone.
|
|
2
|
+
|
|
3
|
+
Pure numpy. Zero external data dependencies for grid generation.
|
|
4
|
+
Shapefile used only for one-time parity validation.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from datafactory_priogrid.cell_generator import (
|
|
8
|
+
generate_bounding_boxes,
|
|
9
|
+
generate_grid,
|
|
10
|
+
latlon_to_pgid,
|
|
11
|
+
pgid_to_latlon,
|
|
12
|
+
)
|
|
13
|
+
from datafactory_priogrid.grid_config import GridConfig
|
|
14
|
+
from datafactory_priogrid.parity_validation import (
|
|
15
|
+
ParityResult,
|
|
16
|
+
ReferenceGeometryReader,
|
|
17
|
+
record_parity_result,
|
|
18
|
+
validate_parity,
|
|
19
|
+
)
|
|
20
|
+
from datafactory_priogrid.shapefile_reader import PyShpReader
|
|
21
|
+
from datafactory_priogrid.spatiotemporal import SpatioTemporalGrid
|
|
22
|
+
from datafactory_priogrid.temporal_config import TemporalConfig
|
|
23
|
+
from datafactory_priogrid.temporal_generator import (
|
|
24
|
+
from_views_month_id,
|
|
25
|
+
generate_time_steps,
|
|
26
|
+
to_views_month_id,
|
|
27
|
+
)
|
|
28
|
+
from datafactory_provenance.constants import VIEWS_EPOCH_YEAR
|
|
29
|
+
|
|
30
|
+
# harvester.fetch_shapefile is not imported here to avoid pulling
|
|
31
|
+
# 'requests' on every `import datafactory_priogrid`. Access it via:
|
|
32
|
+
# from datafactory_priogrid.shapefile_harvester import fetch_shapefile
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
"GridConfig",
|
|
36
|
+
"TemporalConfig",
|
|
37
|
+
"VIEWS_EPOCH_YEAR",
|
|
38
|
+
"SpatioTemporalGrid",
|
|
39
|
+
"generate_grid",
|
|
40
|
+
"generate_bounding_boxes",
|
|
41
|
+
"generate_time_steps",
|
|
42
|
+
"pgid_to_latlon",
|
|
43
|
+
"latlon_to_pgid",
|
|
44
|
+
"to_views_month_id",
|
|
45
|
+
"from_views_month_id",
|
|
46
|
+
"ReferenceGeometryReader",
|
|
47
|
+
"ParityResult",
|
|
48
|
+
"validate_parity",
|
|
49
|
+
"record_parity_result",
|
|
50
|
+
"PyShpReader",
|
|
51
|
+
]
|