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,419 @@
|
|
|
1
|
+
"""V-Dem viewpoint v1 — country-year to grid-monthly broadcast.
|
|
2
|
+
|
|
3
|
+
Reads V-Dem harvest output (country-year Parquet), applies ISO3→pgid
|
|
4
|
+
crosswalk via GAUL admin boundaries, and expands annual values to
|
|
5
|
+
monthly (step function: constant within each year).
|
|
6
|
+
|
|
7
|
+
No consolidation layer (ADR-035: single annual release).
|
|
8
|
+
Viewpoint reads directly from data/raw/vdem/.
|
|
9
|
+
|
|
10
|
+
Implements ADR-014 (viewpoints as derived views), ADR-035 (V-Dem).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import logging
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
import pyarrow as pa
|
|
21
|
+
import pyarrow.parquet as pq
|
|
22
|
+
|
|
23
|
+
from datafactory_provenance import (
|
|
24
|
+
DIGEST_SCHEME,
|
|
25
|
+
LEDGER_VERSION,
|
|
26
|
+
VIEWS_EPOCH_YEAR,
|
|
27
|
+
append_ledger_entry,
|
|
28
|
+
compute_file_digest,
|
|
29
|
+
)
|
|
30
|
+
from datafactory_viewpoint.builders import register_builder
|
|
31
|
+
from datafactory_viewpoint.temporal import (
|
|
32
|
+
VALID_TEMPORAL_INTERPOLATIONS,
|
|
33
|
+
interpolate_temporal,
|
|
34
|
+
)
|
|
35
|
+
from datafactory_viewpoint.viewpoint_result import ViewpointResult
|
|
36
|
+
|
|
37
|
+
logger = logging.getLogger(__name__)
|
|
38
|
+
|
|
39
|
+
DATASET_ID = "vdem_viewpoint"
|
|
40
|
+
|
|
41
|
+
VDEM_VARIABLES: tuple[str, ...] = (
|
|
42
|
+
"v2xcl_dmove",
|
|
43
|
+
"v2xeg_eqdr",
|
|
44
|
+
"v2xpe_exlsocgr",
|
|
45
|
+
"v2x_clphy",
|
|
46
|
+
"v2xcl_prpty",
|
|
47
|
+
"v2x_ex_military",
|
|
48
|
+
"v2x_ex_party",
|
|
49
|
+
"v2x_horacc",
|
|
50
|
+
"v2xnp_client",
|
|
51
|
+
"v2xnp_regcorr",
|
|
52
|
+
"v2xpe_exlgeo",
|
|
53
|
+
"v2x_veracc",
|
|
54
|
+
"v2xpe_exlpol",
|
|
55
|
+
"v2x_diagacc",
|
|
56
|
+
"v2x_divparctrl",
|
|
57
|
+
"v2xeg_eqprotec",
|
|
58
|
+
"v2x_genpp",
|
|
59
|
+
"v2xpe_exlgender",
|
|
60
|
+
"v2x_hosabort",
|
|
61
|
+
"v2x_libdem",
|
|
62
|
+
"v2xcl_rol",
|
|
63
|
+
"v2x_accountability",
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# ---- Config ----
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(frozen=True)
|
|
71
|
+
class VdemViewpointConfig:
|
|
72
|
+
"""Configuration for building a V-Dem viewpoint.
|
|
73
|
+
|
|
74
|
+
Reads harvest Parquet (country-year), applies ISO3→pgid
|
|
75
|
+
crosswalk from GAUL, expands annual to monthly, writes
|
|
76
|
+
Parquet with (pgid, month_id, variable_columns).
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
source_path: Path = field(
|
|
80
|
+
default_factory=lambda: Path(
|
|
81
|
+
"data/raw/vdem/vdem_v16.parquet"
|
|
82
|
+
)
|
|
83
|
+
)
|
|
84
|
+
crosswalk_path: Path = field(
|
|
85
|
+
default_factory=lambda: Path(
|
|
86
|
+
"data/raw/gaul_admin/iso3_code.parquet"
|
|
87
|
+
)
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
output_path: Path = Path("data/viewpoint/vdem_v1.parquet")
|
|
91
|
+
ledger_path: Path = Path(
|
|
92
|
+
"provenance/viewpoint/vdem_v1_ledger.jsonl"
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
variables: tuple[str, ...] = VDEM_VARIABLES
|
|
96
|
+
|
|
97
|
+
start_year: int = 1980
|
|
98
|
+
end_year: int = 2025
|
|
99
|
+
|
|
100
|
+
temporal_interpolation: str = "step"
|
|
101
|
+
|
|
102
|
+
version: str = "vdem_v1"
|
|
103
|
+
|
|
104
|
+
def __post_init__(self) -> None:
|
|
105
|
+
if not self.version:
|
|
106
|
+
msg = "version must be non-empty"
|
|
107
|
+
logger.error(msg)
|
|
108
|
+
raise ValueError(msg)
|
|
109
|
+
if not self.variables:
|
|
110
|
+
msg = "variables must be non-empty"
|
|
111
|
+
logger.error(msg)
|
|
112
|
+
raise ValueError(msg)
|
|
113
|
+
if (
|
|
114
|
+
self.temporal_interpolation
|
|
115
|
+
not in VALID_TEMPORAL_INTERPOLATIONS
|
|
116
|
+
):
|
|
117
|
+
msg = (
|
|
118
|
+
f"temporal_interpolation "
|
|
119
|
+
f"'{self.temporal_interpolation}' not in "
|
|
120
|
+
f"{VALID_TEMPORAL_INTERPOLATIONS}"
|
|
121
|
+
)
|
|
122
|
+
logger.error(msg)
|
|
123
|
+
raise ValueError(msg)
|
|
124
|
+
if self.start_year < VIEWS_EPOCH_YEAR:
|
|
125
|
+
msg = (
|
|
126
|
+
f"start_year {self.start_year} is before "
|
|
127
|
+
f"VIEWS epoch {VIEWS_EPOCH_YEAR}"
|
|
128
|
+
)
|
|
129
|
+
logger.error(msg)
|
|
130
|
+
raise ValueError(msg)
|
|
131
|
+
if self.end_year < self.start_year:
|
|
132
|
+
msg = (
|
|
133
|
+
f"end_year {self.end_year} < "
|
|
134
|
+
f"start_year {self.start_year}"
|
|
135
|
+
)
|
|
136
|
+
logger.error(msg)
|
|
137
|
+
raise ValueError(msg)
|
|
138
|
+
|
|
139
|
+
@classmethod
|
|
140
|
+
def from_shortcuts(
|
|
141
|
+
cls,
|
|
142
|
+
*,
|
|
143
|
+
source_path: Path | None = None,
|
|
144
|
+
crosswalk_path: Path | None = None,
|
|
145
|
+
) -> VdemViewpointConfig:
|
|
146
|
+
"""Construct config from shortcut arguments."""
|
|
147
|
+
kwargs: dict = {}
|
|
148
|
+
if source_path is not None:
|
|
149
|
+
kwargs["source_path"] = source_path
|
|
150
|
+
if crosswalk_path is not None:
|
|
151
|
+
kwargs["crosswalk_path"] = crosswalk_path
|
|
152
|
+
return cls(**kwargs)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
# ---- Crosswalk ----
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _build_iso3_to_pgids(
|
|
159
|
+
crosswalk_path: Path,
|
|
160
|
+
) -> dict[str, list[int]]:
|
|
161
|
+
"""Build ISO3 → list[pgid] mapping from GAUL iso3_code.parquet.
|
|
162
|
+
|
|
163
|
+
The GAUL harvester writes iso3_code.parquet with columns
|
|
164
|
+
(gid, value) where gid is pgid and value is ISO3 alpha-3.
|
|
165
|
+
"""
|
|
166
|
+
table = pq.read_table(crosswalk_path)
|
|
167
|
+
gids = table.column("gid").to_pylist()
|
|
168
|
+
iso3s = table.column("value").to_pylist()
|
|
169
|
+
|
|
170
|
+
mapping: dict[str, list[int]] = {}
|
|
171
|
+
for gid, iso3 in zip(gids, iso3s, strict=True):
|
|
172
|
+
if iso3 is None or iso3 == "":
|
|
173
|
+
continue
|
|
174
|
+
iso3_str = str(iso3)
|
|
175
|
+
if iso3_str not in mapping:
|
|
176
|
+
mapping[iso3_str] = []
|
|
177
|
+
mapping[iso3_str].append(int(gid))
|
|
178
|
+
|
|
179
|
+
logger.info(
|
|
180
|
+
"Crosswalk: %d ISO3 codes → %d pgids",
|
|
181
|
+
len(mapping),
|
|
182
|
+
sum(len(v) for v in mapping.values()),
|
|
183
|
+
)
|
|
184
|
+
return mapping
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
# ---- Builder ----
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def build_vdem_v1(
|
|
191
|
+
config: VdemViewpointConfig,
|
|
192
|
+
) -> ViewpointResult:
|
|
193
|
+
"""Build V-Dem viewpoint v1 from harvested country-year data.
|
|
194
|
+
|
|
195
|
+
For each (country, year): look up pgids via GAUL crosswalk,
|
|
196
|
+
create 12 monthly rows (step function), write Parquet with
|
|
197
|
+
(pgid, month_id, variable_columns).
|
|
198
|
+
|
|
199
|
+
Returns:
|
|
200
|
+
ViewpointResult with row counts and output digest.
|
|
201
|
+
"""
|
|
202
|
+
if not config.source_path.exists():
|
|
203
|
+
msg = f"Source file not found: {config.source_path}"
|
|
204
|
+
logger.error(msg)
|
|
205
|
+
raise FileNotFoundError(msg)
|
|
206
|
+
|
|
207
|
+
if not config.crosswalk_path.exists():
|
|
208
|
+
msg = (
|
|
209
|
+
f"Crosswalk file not found: {config.crosswalk_path}"
|
|
210
|
+
)
|
|
211
|
+
logger.error(msg)
|
|
212
|
+
raise FileNotFoundError(msg)
|
|
213
|
+
|
|
214
|
+
# Build ISO3 → pgids mapping
|
|
215
|
+
iso3_to_pgids = _build_iso3_to_pgids(config.crosswalk_path)
|
|
216
|
+
|
|
217
|
+
# Read harvest output
|
|
218
|
+
source_table = pq.read_table(config.source_path)
|
|
219
|
+
n_input = source_table.num_rows
|
|
220
|
+
|
|
221
|
+
iso3_col = source_table.column(
|
|
222
|
+
"country_text_id"
|
|
223
|
+
).to_pylist()
|
|
224
|
+
year_col = source_table.column("year").to_pylist()
|
|
225
|
+
var_arrays = {
|
|
226
|
+
var: source_table.column(var).to_numpy(
|
|
227
|
+
zero_copy_only=False
|
|
228
|
+
)
|
|
229
|
+
for var in config.variables
|
|
230
|
+
if var in source_table.column_names
|
|
231
|
+
}
|
|
232
|
+
del source_table
|
|
233
|
+
|
|
234
|
+
missing_vars = (
|
|
235
|
+
set(config.variables) - set(var_arrays.keys())
|
|
236
|
+
)
|
|
237
|
+
if missing_vars:
|
|
238
|
+
msg = (
|
|
239
|
+
f"Source Parquet missing variables: "
|
|
240
|
+
f"{sorted(missing_vars)}"
|
|
241
|
+
)
|
|
242
|
+
logger.error(msg)
|
|
243
|
+
raise ValueError(msg)
|
|
244
|
+
|
|
245
|
+
# Phase 1: group source rows by country, building epoch dicts
|
|
246
|
+
unmapped_countries: set[str] = set()
|
|
247
|
+
n_filtered = 0
|
|
248
|
+
|
|
249
|
+
country_epochs: dict[
|
|
250
|
+
str, dict[str, dict[int, float]]
|
|
251
|
+
] = {}
|
|
252
|
+
|
|
253
|
+
for i in range(n_input):
|
|
254
|
+
iso3 = str(iso3_col[i])
|
|
255
|
+
year = int(year_col[i])
|
|
256
|
+
|
|
257
|
+
if year < config.start_year or year > config.end_year:
|
|
258
|
+
n_filtered += 1
|
|
259
|
+
continue
|
|
260
|
+
|
|
261
|
+
if iso3_to_pgids.get(iso3) is None:
|
|
262
|
+
unmapped_countries.add(iso3)
|
|
263
|
+
continue
|
|
264
|
+
|
|
265
|
+
if iso3 not in country_epochs:
|
|
266
|
+
country_epochs[iso3] = {
|
|
267
|
+
var: {} for var in config.variables
|
|
268
|
+
}
|
|
269
|
+
for var in config.variables:
|
|
270
|
+
country_epochs[iso3][var][year] = float(
|
|
271
|
+
var_arrays[var][i]
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
# Phase 2: interpolate via shared temporal module, expand
|
|
275
|
+
pgid_chunks: list[np.ndarray] = []
|
|
276
|
+
month_chunks: list[np.ndarray] = []
|
|
277
|
+
var_chunks: dict[str, list[np.ndarray]] = {
|
|
278
|
+
var: [] for var in config.variables
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
for iso3, var_epoch_map in country_epochs.items():
|
|
282
|
+
pgid_arr = np.array(
|
|
283
|
+
iso3_to_pgids[iso3], dtype=np.int32
|
|
284
|
+
)
|
|
285
|
+
n_pgids = len(pgid_arr)
|
|
286
|
+
|
|
287
|
+
first_var = next(iter(var_epoch_map))
|
|
288
|
+
years_present = sorted(var_epoch_map[first_var].keys())
|
|
289
|
+
min_year = years_present[0]
|
|
290
|
+
max_year = years_present[-1]
|
|
291
|
+
|
|
292
|
+
monthly_vals: dict[str, list[float]] = {}
|
|
293
|
+
for var, epochs in var_epoch_map.items():
|
|
294
|
+
monthly_vals[var] = interpolate_temporal(
|
|
295
|
+
epochs,
|
|
296
|
+
strategy=config.temporal_interpolation,
|
|
297
|
+
start_year=min_year,
|
|
298
|
+
start_month=1,
|
|
299
|
+
end_year=max_year,
|
|
300
|
+
end_month=12,
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
n_months = len(monthly_vals[first_var])
|
|
304
|
+
month_id_arr = np.array(
|
|
305
|
+
[
|
|
306
|
+
(min_year - VIEWS_EPOCH_YEAR) * 12 + m + 1
|
|
307
|
+
for m in range(n_months)
|
|
308
|
+
],
|
|
309
|
+
dtype=np.int32,
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
pgid_chunks.append(np.tile(pgid_arr, n_months))
|
|
313
|
+
month_chunks.append(
|
|
314
|
+
np.repeat(month_id_arr, n_pgids)
|
|
315
|
+
)
|
|
316
|
+
for var in config.variables:
|
|
317
|
+
vals = np.array(
|
|
318
|
+
monthly_vals[var], dtype=np.float64
|
|
319
|
+
)
|
|
320
|
+
var_chunks[var].append(
|
|
321
|
+
np.repeat(vals, n_pgids)
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
empty_i32 = np.array([], dtype=np.int32)
|
|
325
|
+
empty_f64 = np.array([], dtype=np.float64)
|
|
326
|
+
pgid_rows = (
|
|
327
|
+
np.concatenate(pgid_chunks) if pgid_chunks
|
|
328
|
+
else empty_i32
|
|
329
|
+
)
|
|
330
|
+
month_id_rows = (
|
|
331
|
+
np.concatenate(month_chunks) if month_chunks
|
|
332
|
+
else empty_i32
|
|
333
|
+
)
|
|
334
|
+
var_rows: dict[str, np.ndarray] = {}
|
|
335
|
+
for var in config.variables:
|
|
336
|
+
chunks = var_chunks[var]
|
|
337
|
+
var_rows[var] = (
|
|
338
|
+
np.concatenate(chunks) if chunks else empty_f64
|
|
339
|
+
)
|
|
340
|
+
|
|
341
|
+
if unmapped_countries:
|
|
342
|
+
logger.warning(
|
|
343
|
+
"%d V-Dem countries not in GAUL crosswalk: %s",
|
|
344
|
+
len(unmapped_countries),
|
|
345
|
+
sorted(unmapped_countries)[:10],
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
if n_filtered > 0:
|
|
349
|
+
logger.info(
|
|
350
|
+
"Filtered %d rows outside year range %d–%d",
|
|
351
|
+
n_filtered, config.start_year, config.end_year,
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
n_output = len(pgid_rows)
|
|
355
|
+
if n_output == 0:
|
|
356
|
+
msg = "Viewpoint produced zero output rows"
|
|
357
|
+
logger.error(msg)
|
|
358
|
+
raise ValueError(msg)
|
|
359
|
+
|
|
360
|
+
# Build Arrow table
|
|
361
|
+
columns: dict[str, pa.Array] = {
|
|
362
|
+
"pgid": pa.array(pgid_rows, type=pa.int32()),
|
|
363
|
+
"month_id": pa.array(month_id_rows, type=pa.int32()),
|
|
364
|
+
}
|
|
365
|
+
for var in config.variables:
|
|
366
|
+
columns[var] = pa.array(
|
|
367
|
+
var_rows[var], type=pa.float64()
|
|
368
|
+
)
|
|
369
|
+
del pgid_rows, month_id_rows, var_rows
|
|
370
|
+
|
|
371
|
+
table = pa.table(columns)
|
|
372
|
+
|
|
373
|
+
# Write Parquet
|
|
374
|
+
config.output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
375
|
+
pq.write_table(table, config.output_path, compression="snappy")
|
|
376
|
+
|
|
377
|
+
output_digest = compute_file_digest(config.output_path)
|
|
378
|
+
|
|
379
|
+
# Provenance
|
|
380
|
+
append_ledger_entry(config.ledger_path, {
|
|
381
|
+
"dataset": DATASET_ID,
|
|
382
|
+
"version": config.version,
|
|
383
|
+
"n_input_rows": n_input,
|
|
384
|
+
"n_output_rows": n_output,
|
|
385
|
+
"n_variables": len(config.variables),
|
|
386
|
+
"unmapped_countries": len(unmapped_countries),
|
|
387
|
+
"n_filtered_years": n_filtered,
|
|
388
|
+
"year_range": [config.start_year, config.end_year],
|
|
389
|
+
"output_path": str(config.output_path),
|
|
390
|
+
"output_digest": output_digest,
|
|
391
|
+
"outcome": "success",
|
|
392
|
+
"ledger_version": LEDGER_VERSION,
|
|
393
|
+
"digest_algorithm": DIGEST_SCHEME,
|
|
394
|
+
})
|
|
395
|
+
|
|
396
|
+
logger.info(
|
|
397
|
+
"V-Dem viewpoint %s built: %d input → %d output rows "
|
|
398
|
+
"(%d variables, %d unmapped countries, digest: %s)",
|
|
399
|
+
config.version,
|
|
400
|
+
n_input,
|
|
401
|
+
n_output,
|
|
402
|
+
len(config.variables),
|
|
403
|
+
len(unmapped_countries),
|
|
404
|
+
output_digest,
|
|
405
|
+
)
|
|
406
|
+
|
|
407
|
+
return ViewpointResult(
|
|
408
|
+
output_path=config.output_path,
|
|
409
|
+
n_events_input=n_input,
|
|
410
|
+
n_events_output=n_output,
|
|
411
|
+
n_summary_expanded=0,
|
|
412
|
+
n_spatially_distributed=0,
|
|
413
|
+
n_filtered=n_filtered,
|
|
414
|
+
output_digest=output_digest,
|
|
415
|
+
version=config.version,
|
|
416
|
+
)
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
register_builder("vdem_v1", build_vdem_v1)
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""Named viewpoint profiles — pre-configured research choice sets.
|
|
2
|
+
|
|
3
|
+
A profile is a named combination of strategy choices (survivorship,
|
|
4
|
+
distribution, etc.) that defines a specific viewpoint. Users either
|
|
5
|
+
pick a profile by name or freestyle with individual strategy keys.
|
|
6
|
+
|
|
7
|
+
Adding a new profile means calling _register() — no changes to the
|
|
8
|
+
builder or config classes (OCP).
|
|
9
|
+
|
|
10
|
+
Usage:
|
|
11
|
+
# Pick from menu
|
|
12
|
+
config = load_profile("production_parity", my_path)
|
|
13
|
+
|
|
14
|
+
# Freestyle (no profile)
|
|
15
|
+
config = ViewpointConfig(consolidated_path=my_path, ...)
|
|
16
|
+
|
|
17
|
+
# Preset with override
|
|
18
|
+
config = load_profile("production_parity", my_path,
|
|
19
|
+
distribution_strategy="ceil_split")
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import logging
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import TYPE_CHECKING, Any
|
|
27
|
+
|
|
28
|
+
from datafactory_viewpoint.viewpoint_config import ViewpointConfig
|
|
29
|
+
|
|
30
|
+
if TYPE_CHECKING:
|
|
31
|
+
from datafactory_viewpoint.builders.acled_v1 import (
|
|
32
|
+
AcledViewpointConfig,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
logger = logging.getLogger(__name__)
|
|
36
|
+
|
|
37
|
+
__all__ = [
|
|
38
|
+
"load_profile",
|
|
39
|
+
"load_acled_profile",
|
|
40
|
+
"list_profiles",
|
|
41
|
+
"list_acled_profiles",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
PROFILES: dict[str, dict[str, Any]] = {}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _register(name: str, **kwargs: Any) -> None:
|
|
48
|
+
"""Register a named viewpoint profile."""
|
|
49
|
+
kwargs["version"] = name # Version tag always matches profile name
|
|
50
|
+
PROFILES[name] = kwargs
|
|
51
|
+
logger.info("Registered viewpoint profile: %s", name)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def load_profile(
|
|
55
|
+
name: str,
|
|
56
|
+
consolidated_path: Path,
|
|
57
|
+
**overrides: Any,
|
|
58
|
+
) -> ViewpointConfig:
|
|
59
|
+
"""Load a named viewpoint profile.
|
|
60
|
+
|
|
61
|
+
Combines the profile's research choices with the caller's
|
|
62
|
+
runtime paths. Overrides allow tweaking individual choices.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
name: Profile name (e.g., "production_parity").
|
|
66
|
+
consolidated_path: Path to the consolidated event store.
|
|
67
|
+
**overrides: Override specific profile choices.
|
|
68
|
+
|
|
69
|
+
Returns:
|
|
70
|
+
A fully configured ViewpointConfig.
|
|
71
|
+
|
|
72
|
+
Raises:
|
|
73
|
+
KeyError: If the profile name is not registered.
|
|
74
|
+
"""
|
|
75
|
+
if name not in PROFILES:
|
|
76
|
+
available = sorted(PROFILES.keys())
|
|
77
|
+
err_msg = (
|
|
78
|
+
f"Unknown viewpoint profile '{name}'. "
|
|
79
|
+
f"Available: {available}"
|
|
80
|
+
)
|
|
81
|
+
logger.error(err_msg)
|
|
82
|
+
raise KeyError(err_msg)
|
|
83
|
+
|
|
84
|
+
merged = {**PROFILES[name], **overrides}
|
|
85
|
+
return ViewpointConfig(
|
|
86
|
+
consolidated_path=consolidated_path,
|
|
87
|
+
**merged,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def list_profiles() -> list[str]:
|
|
92
|
+
"""Return sorted list of registered profile names."""
|
|
93
|
+
return sorted(PROFILES.keys())
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
# ---- Registered profiles ----
|
|
97
|
+
|
|
98
|
+
_register(
|
|
99
|
+
"production_parity",
|
|
100
|
+
survivorship_strategy="dot9_wins",
|
|
101
|
+
distribution_strategy="ceil_split",
|
|
102
|
+
spatial_distribution_strategy="passthrough",
|
|
103
|
+
source_distribution_map={"annual": "date_end_only"},
|
|
104
|
+
filter_stale_versions=True,
|
|
105
|
+
min_priogrid_gid=1,
|
|
106
|
+
max_type_of_violence=3,
|
|
107
|
+
exclude_where_prec=(4, 6),
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
# ---- ACLED profiles ----
|
|
112
|
+
|
|
113
|
+
ACLED_PROFILES: dict[str, dict[str, Any]] = {}
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _register_acled(name: str, **kwargs: Any) -> None:
|
|
117
|
+
"""Register a named ACLED viewpoint profile."""
|
|
118
|
+
kwargs["version"] = name
|
|
119
|
+
ACLED_PROFILES[name] = kwargs
|
|
120
|
+
logger.info("Registered ACLED viewpoint profile: %s", name)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def list_acled_profiles() -> list[str]:
|
|
124
|
+
"""Return sorted list of registered ACLED profile names."""
|
|
125
|
+
return sorted(ACLED_PROFILES.keys())
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def load_acled_profile(
|
|
129
|
+
name: str,
|
|
130
|
+
consolidated_path: Path,
|
|
131
|
+
**overrides: Any,
|
|
132
|
+
) -> AcledViewpointConfig:
|
|
133
|
+
"""Load a named ACLED viewpoint profile.
|
|
134
|
+
|
|
135
|
+
Returns an AcledViewpointConfig (imported lazily to avoid
|
|
136
|
+
circular imports).
|
|
137
|
+
"""
|
|
138
|
+
if name not in ACLED_PROFILES:
|
|
139
|
+
available = sorted(ACLED_PROFILES.keys())
|
|
140
|
+
err_msg = (
|
|
141
|
+
f"Unknown ACLED profile '{name}'. "
|
|
142
|
+
f"Available: {available}"
|
|
143
|
+
)
|
|
144
|
+
logger.error(err_msg)
|
|
145
|
+
raise KeyError(err_msg)
|
|
146
|
+
|
|
147
|
+
from datafactory_viewpoint.builders.acled_v1 import (
|
|
148
|
+
AcledViewpointConfig,
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
merged = {**ACLED_PROFILES[name], **overrides}
|
|
152
|
+
return AcledViewpointConfig(
|
|
153
|
+
consolidated_path=consolidated_path,
|
|
154
|
+
**merged,
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
_register_acled(
|
|
159
|
+
"acled_violence_only",
|
|
160
|
+
event_type_filter=(
|
|
161
|
+
"Battles",
|
|
162
|
+
"Explosions/Remote violence",
|
|
163
|
+
"Violence against civilians",
|
|
164
|
+
),
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
_register_acled(
|
|
168
|
+
"acled_all_events",
|
|
169
|
+
)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""GeoTIFF reading for raster-based viewpoint builders."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import tifffile
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def read_geotiff(
|
|
15
|
+
path: Path,
|
|
16
|
+
) -> tuple[np.ndarray, float, float, float, float]:
|
|
17
|
+
"""Read GeoTIFF and extract geotransform from TIFF tags.
|
|
18
|
+
|
|
19
|
+
Returns native dtype — no in-memory conversion. Strip-based
|
|
20
|
+
aggregation handles any input dtype directly.
|
|
21
|
+
|
|
22
|
+
Returns:
|
|
23
|
+
(data, tiepoint_x, tiepoint_y, pixel_scale_x, pixel_scale_y)
|
|
24
|
+
where tiepoint is the top-left geographic coordinate.
|
|
25
|
+
"""
|
|
26
|
+
with tifffile.TiffFile(str(path)) as tif:
|
|
27
|
+
page = tif.pages.first
|
|
28
|
+
data = page.asarray(maxworkers=1)
|
|
29
|
+
|
|
30
|
+
scale_tag = page.tags.get("ModelPixelScaleTag")
|
|
31
|
+
tie_tag = page.tags.get("ModelTiepointTag")
|
|
32
|
+
|
|
33
|
+
if scale_tag is None or tie_tag is None:
|
|
34
|
+
msg = (
|
|
35
|
+
f"GeoTIFF {path} missing geotransform tags "
|
|
36
|
+
"(ModelPixelScaleTag, ModelTiepointTag)"
|
|
37
|
+
)
|
|
38
|
+
logger.error(msg)
|
|
39
|
+
raise ValueError(msg)
|
|
40
|
+
|
|
41
|
+
scale = scale_tag.value
|
|
42
|
+
tie = tie_tag.value
|
|
43
|
+
|
|
44
|
+
pixel_scale_x = float(scale[0])
|
|
45
|
+
pixel_scale_y = float(scale[1])
|
|
46
|
+
tiepoint_x = float(tie[3])
|
|
47
|
+
tiepoint_y = float(tie[4])
|
|
48
|
+
|
|
49
|
+
return data, tiepoint_x, tiepoint_y, pixel_scale_x, pixel_scale_y
|