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,616 @@
|
|
|
1
|
+
"""UCDP/GED Annual dataset source.
|
|
2
|
+
|
|
3
|
+
Fetches georeferenced event data from the Uppsala Conflict Data Program.
|
|
4
|
+
API docs: https://ucdp.uu.se/apidocs/
|
|
5
|
+
|
|
6
|
+
Source-specific concerns: API URL, schema definition, pagination,
|
|
7
|
+
token handling, version string. Uses the shared harvester skeleton
|
|
8
|
+
(validation, storage, provenance) from the parent package.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import datetime
|
|
14
|
+
import logging
|
|
15
|
+
import os
|
|
16
|
+
import random
|
|
17
|
+
import time
|
|
18
|
+
from collections.abc import Callable
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
import requests
|
|
23
|
+
|
|
24
|
+
from datafactory_harvester.event_validation import (
|
|
25
|
+
ComparisonResult,
|
|
26
|
+
compare_snapshots,
|
|
27
|
+
date_range,
|
|
28
|
+
validate_dgp_assumptions,
|
|
29
|
+
validate_events,
|
|
30
|
+
)
|
|
31
|
+
from datafactory_harvester.snapshot_storage import archive_snapshot, save_event_snapshot
|
|
32
|
+
from datafactory_harvester.sources import register_source
|
|
33
|
+
from datafactory_harvester.sources._ucdp_common import (
|
|
34
|
+
UCDP_GED_API_BASE,
|
|
35
|
+
validate_envelope,
|
|
36
|
+
)
|
|
37
|
+
from datafactory_harvester.validation import (
|
|
38
|
+
validate_nonempty_string,
|
|
39
|
+
validate_positive_float,
|
|
40
|
+
validate_positive_int,
|
|
41
|
+
validate_year_range,
|
|
42
|
+
)
|
|
43
|
+
from datafactory_http import request_with_retry
|
|
44
|
+
from datafactory_provenance import (
|
|
45
|
+
DIGEST_SCHEME,
|
|
46
|
+
LEDGER_VERSION,
|
|
47
|
+
append_ledger_entry,
|
|
48
|
+
last_digest,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
logger = logging.getLogger(__name__)
|
|
52
|
+
|
|
53
|
+
DATASET_ID = "ucdp_annual"
|
|
54
|
+
_LOG_EVERY_N_PAGES: int = 50
|
|
55
|
+
_FETCH_DURATION_PRECISION: int = 1 # Decimal places for fetch_duration_s in ledger
|
|
56
|
+
_RATE_LIMIT_MAX_RETRIES: int = 5
|
|
57
|
+
_YEAR_OFFSET: int = 1999 # v25.1 covers through 2024 → major + 1999
|
|
58
|
+
_RATE_LIMIT_BASE_DELAY: float = 30.0 # seconds; UCDP rate window is ~1 minute
|
|
59
|
+
_TOTALCOUNT_ABS_TOLERANCE: int = 1100
|
|
60
|
+
_TOTALCOUNT_PCT_TOLERANCE: float = 0.01
|
|
61
|
+
|
|
62
|
+
# ---- UCDP-specific schema definition ----
|
|
63
|
+
|
|
64
|
+
REQUIRED_FIELDS: set[str] = {
|
|
65
|
+
"id",
|
|
66
|
+
"country_id",
|
|
67
|
+
"country",
|
|
68
|
+
"date_start",
|
|
69
|
+
"best",
|
|
70
|
+
"high",
|
|
71
|
+
"low",
|
|
72
|
+
"type_of_violence",
|
|
73
|
+
"event_clarity",
|
|
74
|
+
"code_status",
|
|
75
|
+
"where_prec",
|
|
76
|
+
"date_prec",
|
|
77
|
+
"number_of_sources",
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
FIELD_TYPES: dict[str, tuple[type, ...]] = {
|
|
81
|
+
"id": (int,),
|
|
82
|
+
"country_id": (int,),
|
|
83
|
+
"country": (str,),
|
|
84
|
+
"date_start": (str,),
|
|
85
|
+
"best": (int, float),
|
|
86
|
+
"high": (int, float),
|
|
87
|
+
"low": (int, float),
|
|
88
|
+
"type_of_violence": (int,),
|
|
89
|
+
"event_clarity": (int, float),
|
|
90
|
+
"where_prec": (int,),
|
|
91
|
+
"date_prec": (int,),
|
|
92
|
+
"number_of_sources": (int,),
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
# ---- DGP assumption checks (C-257) ----
|
|
96
|
+
|
|
97
|
+
_VALID_DATE_PREC = {1, 2, 3, 4, 5}
|
|
98
|
+
_VALID_VIOLENCE_TYPE = {1, 2, 3}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _check_date_prec_range(event: dict) -> str | None:
|
|
102
|
+
"""date_prec must be in {1,2,3,4,5}."""
|
|
103
|
+
val = event.get("date_prec")
|
|
104
|
+
if val is not None and val not in _VALID_DATE_PREC:
|
|
105
|
+
return f"date_prec={val} outside {_VALID_DATE_PREC}"
|
|
106
|
+
return None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _check_violence_type(event: dict) -> str | None:
|
|
110
|
+
"""type_of_violence must be in {1,2,3}."""
|
|
111
|
+
val = event.get("type_of_violence")
|
|
112
|
+
if val is not None and val not in _VALID_VIOLENCE_TYPE:
|
|
113
|
+
return f"type_of_violence={val} outside {_VALID_VIOLENCE_TYPE}"
|
|
114
|
+
return None
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _check_coordinate_bounds(event: dict) -> str | None:
|
|
118
|
+
"""Latitude in [-90,90], longitude in [-180,180]."""
|
|
119
|
+
for field, lo, hi in (
|
|
120
|
+
("latitude", -90, 90),
|
|
121
|
+
("longitude", -180, 180),
|
|
122
|
+
):
|
|
123
|
+
val = event.get(field)
|
|
124
|
+
if val is not None:
|
|
125
|
+
try:
|
|
126
|
+
fval = float(val)
|
|
127
|
+
if not (lo <= fval <= hi):
|
|
128
|
+
return f"{field}={fval} outside [{lo},{hi}]"
|
|
129
|
+
except (TypeError, ValueError):
|
|
130
|
+
pass
|
|
131
|
+
return None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _check_best_high_low_ordering(event: dict) -> str | None:
|
|
135
|
+
"""low <= best <= high."""
|
|
136
|
+
low = event.get("low")
|
|
137
|
+
best = event.get("best")
|
|
138
|
+
high = event.get("high")
|
|
139
|
+
if (
|
|
140
|
+
low is not None
|
|
141
|
+
and best is not None
|
|
142
|
+
and isinstance(low, (int, float))
|
|
143
|
+
and isinstance(best, (int, float))
|
|
144
|
+
and low > best
|
|
145
|
+
):
|
|
146
|
+
return f"low ({low}) > best ({best})"
|
|
147
|
+
if (
|
|
148
|
+
best is not None
|
|
149
|
+
and high is not None
|
|
150
|
+
and isinstance(best, (int, float))
|
|
151
|
+
and isinstance(high, (int, float))
|
|
152
|
+
and best > high
|
|
153
|
+
):
|
|
154
|
+
return f"best ({best}) > high ({high})"
|
|
155
|
+
return None
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _check_coords_non_null(event: dict) -> str | None:
|
|
159
|
+
"""Latitude and longitude must not be None."""
|
|
160
|
+
if event.get("latitude") is None:
|
|
161
|
+
return "latitude is None"
|
|
162
|
+
if event.get("longitude") is None:
|
|
163
|
+
return "longitude is None"
|
|
164
|
+
return None
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
UCDP_DGP_CHECKS: tuple[
|
|
168
|
+
Callable[[dict], str | None], ...
|
|
169
|
+
] = (
|
|
170
|
+
_check_date_prec_range,
|
|
171
|
+
_check_violence_type,
|
|
172
|
+
_check_coordinate_bounds,
|
|
173
|
+
_check_coords_non_null,
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
# Published UCDP data violates low <= best <= high in ~1.3% of
|
|
177
|
+
# events (v25.1: 3,594 best>high + 1,415 low>best across
|
|
178
|
+
# 1989-2024). A known source characteristic, not corruption —
|
|
179
|
+
# warn, never block the harvest.
|
|
180
|
+
UCDP_DGP_WARN_CHECKS: tuple[
|
|
181
|
+
Callable[[dict], str | None], ...
|
|
182
|
+
] = (
|
|
183
|
+
_check_best_high_low_ordering,
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
# ---- Config ----
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
@dataclass(frozen=True)
|
|
191
|
+
class UcdpAnnualConfig:
|
|
192
|
+
"""Configuration for fetching UCDP/GED Annual data.
|
|
193
|
+
|
|
194
|
+
Separates harvesting concerns from reporting concerns (SRP).
|
|
195
|
+
No ranking_months, escalation_months, or top_n_countries here.
|
|
196
|
+
"""
|
|
197
|
+
|
|
198
|
+
# Dataset identity — sentinels resolved in __post_init__
|
|
199
|
+
version: str = ""
|
|
200
|
+
start_year: int = 1989
|
|
201
|
+
end_year: int = 0
|
|
202
|
+
|
|
203
|
+
# API transport
|
|
204
|
+
base_url: str = UCDP_GED_API_BASE
|
|
205
|
+
page_size: int = 1000
|
|
206
|
+
timeout: int = 30 # paginated JSON ~100 KB/page (ADR-018)
|
|
207
|
+
max_retries: int = 3
|
|
208
|
+
page_delay: float = 2.0 # seconds between paginated requests
|
|
209
|
+
|
|
210
|
+
# Storage
|
|
211
|
+
data_dir: Path = Path("data/raw/ucdp_annual")
|
|
212
|
+
ledger_path: Path = Path("provenance/ucdp_annual/ingestion_ledger.jsonl")
|
|
213
|
+
|
|
214
|
+
def __post_init__(self) -> None:
|
|
215
|
+
if not self.version:
|
|
216
|
+
major = datetime.datetime.now(tz=datetime.UTC).year - 2001
|
|
217
|
+
object.__setattr__(self, "version", f"{major}.1")
|
|
218
|
+
if self.end_year == 0:
|
|
219
|
+
major = int(self.version.split(".")[0])
|
|
220
|
+
object.__setattr__(self, "end_year", major + _YEAR_OFFSET)
|
|
221
|
+
validate_year_range(self.start_year, self.end_year)
|
|
222
|
+
validate_positive_int(self.page_size, "page_size")
|
|
223
|
+
validate_positive_int(self.max_retries, "max_retries")
|
|
224
|
+
validate_positive_float(self.page_delay, "page_delay")
|
|
225
|
+
validate_positive_int(self.timeout, "timeout")
|
|
226
|
+
validate_nonempty_string(self.version, "version")
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
# ---- API client ----
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def get_ucdp_token(token: str | None = None) -> str:
|
|
233
|
+
"""Resolve API token from argument or environment."""
|
|
234
|
+
resolved = token or os.environ.get("UCDP_API_TOKEN")
|
|
235
|
+
if not resolved:
|
|
236
|
+
err_msg = (
|
|
237
|
+
"UCDP API token required. Set UCDP_API_TOKEN environment "
|
|
238
|
+
"variable or pass token= to fetch_ucdp_annual()."
|
|
239
|
+
)
|
|
240
|
+
logger.error(err_msg)
|
|
241
|
+
raise ValueError(err_msg)
|
|
242
|
+
return resolved
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def fetch_paginated(
|
|
246
|
+
config: UcdpAnnualConfig,
|
|
247
|
+
token: str | None = None,
|
|
248
|
+
*,
|
|
249
|
+
max_pages: int | None = None,
|
|
250
|
+
) -> list[dict]:
|
|
251
|
+
"""Fetch all UCDP/GED Annual events with pagination.
|
|
252
|
+
|
|
253
|
+
Args:
|
|
254
|
+
config: Harvest configuration.
|
|
255
|
+
token: API token (falls back to UCDP_API_TOKEN env var).
|
|
256
|
+
max_pages: Stop after this many pages (None = fetch all).
|
|
257
|
+
|
|
258
|
+
Returns:
|
|
259
|
+
List of raw event dicts.
|
|
260
|
+
"""
|
|
261
|
+
api_token = get_ucdp_token(token)
|
|
262
|
+
url = f"{config.base_url}/{config.version}"
|
|
263
|
+
headers = {"x-ucdp-access-token": api_token}
|
|
264
|
+
params: dict = {
|
|
265
|
+
"StartDate": f"{config.start_year}-01-01",
|
|
266
|
+
"EndDate": f"{config.end_year}-12-31",
|
|
267
|
+
"pagesize": config.page_size,
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
all_events: list[dict] = []
|
|
271
|
+
page = 1
|
|
272
|
+
total_pages = None
|
|
273
|
+
|
|
274
|
+
while True:
|
|
275
|
+
params["page"] = page
|
|
276
|
+
|
|
277
|
+
# The UCDP API rate-limits after ~40 requests with HTTP 400.
|
|
278
|
+
# request_with_retry correctly fails fast on 4xx (non-retryable
|
|
279
|
+
# in general), but rate limiting IS retryable — just not
|
|
280
|
+
# immediately. Catch 400s here and back off before retrying
|
|
281
|
+
# the same page.
|
|
282
|
+
for rate_attempt in range(_RATE_LIMIT_MAX_RETRIES):
|
|
283
|
+
try:
|
|
284
|
+
response = request_with_retry(
|
|
285
|
+
url,
|
|
286
|
+
headers=headers,
|
|
287
|
+
params=params,
|
|
288
|
+
max_retries=config.max_retries,
|
|
289
|
+
timeout=config.timeout,
|
|
290
|
+
)
|
|
291
|
+
break
|
|
292
|
+
except requests.HTTPError as exc:
|
|
293
|
+
if (
|
|
294
|
+
exc.response is not None
|
|
295
|
+
and exc.response.status_code == 400
|
|
296
|
+
and rate_attempt < _RATE_LIMIT_MAX_RETRIES - 1
|
|
297
|
+
):
|
|
298
|
+
delay = (
|
|
299
|
+
_RATE_LIMIT_BASE_DELAY * (2 ** rate_attempt)
|
|
300
|
+
+ random.uniform(0, 5)
|
|
301
|
+
)
|
|
302
|
+
logger.warning(
|
|
303
|
+
"Rate limited at page %d (attempt %d/%d), "
|
|
304
|
+
"backing off %.0fs",
|
|
305
|
+
page,
|
|
306
|
+
rate_attempt + 1,
|
|
307
|
+
_RATE_LIMIT_MAX_RETRIES,
|
|
308
|
+
delay,
|
|
309
|
+
)
|
|
310
|
+
time.sleep(delay)
|
|
311
|
+
else:
|
|
312
|
+
raise
|
|
313
|
+
|
|
314
|
+
data = response.json()
|
|
315
|
+
|
|
316
|
+
if page == 1:
|
|
317
|
+
validate_envelope(data)
|
|
318
|
+
|
|
319
|
+
if total_pages is None:
|
|
320
|
+
total_pages = data.get("TotalPages", 1)
|
|
321
|
+
total_count = data.get("TotalCount", 0)
|
|
322
|
+
logger.info(
|
|
323
|
+
"UCDP GED %s: %d events across %d pages (%d-%d)",
|
|
324
|
+
config.version,
|
|
325
|
+
total_count,
|
|
326
|
+
total_pages,
|
|
327
|
+
config.start_year,
|
|
328
|
+
config.end_year,
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
results = data.get("Result", [])
|
|
332
|
+
if not results:
|
|
333
|
+
break
|
|
334
|
+
|
|
335
|
+
all_events.extend(results)
|
|
336
|
+
if page % _LOG_EVERY_N_PAGES == 0 or page == 1:
|
|
337
|
+
logger.info(
|
|
338
|
+
"Page %d/%d (%d events so far)",
|
|
339
|
+
page,
|
|
340
|
+
total_pages,
|
|
341
|
+
len(all_events),
|
|
342
|
+
)
|
|
343
|
+
|
|
344
|
+
if page >= total_pages:
|
|
345
|
+
break
|
|
346
|
+
if max_pages is not None and page >= max_pages:
|
|
347
|
+
logger.info("Stopped after %d pages (max_pages limit)", max_pages)
|
|
348
|
+
break
|
|
349
|
+
time.sleep(config.page_delay)
|
|
350
|
+
page += 1
|
|
351
|
+
|
|
352
|
+
logger.info("Fetched %d total events", len(all_events))
|
|
353
|
+
|
|
354
|
+
# Assert fetched count against API's TotalCount. The UCDP API
|
|
355
|
+
# includes type_of_violence=4 events in TotalCount but excludes
|
|
356
|
+
# them from Result — a consistent offset of ~1000 events across
|
|
357
|
+
# all versions (annual and candidate). For annual (384K events)
|
|
358
|
+
# this is 0.26%; for small candidate versions (200–2300 events)
|
|
359
|
+
# it can be 40–100%. Use both absolute and percentage thresholds:
|
|
360
|
+
# only raise if shortfall exceeds BOTH 1% AND 1100 events.
|
|
361
|
+
if max_pages is None and total_count and total_count > 0:
|
|
362
|
+
shortfall = total_count - len(all_events)
|
|
363
|
+
shortfall_pct = shortfall / total_count
|
|
364
|
+
exceeds_pct = shortfall_pct > _TOTALCOUNT_PCT_TOLERANCE
|
|
365
|
+
exceeds_abs = shortfall > _TOTALCOUNT_ABS_TOLERANCE
|
|
366
|
+
if exceeds_pct and exceeds_abs:
|
|
367
|
+
err_msg = (
|
|
368
|
+
f"Fetch count mismatch: API reports {total_count} "
|
|
369
|
+
f"events but only {len(all_events)} fetched "
|
|
370
|
+
f"({shortfall_pct:.1%} shortfall, {shortfall} events). "
|
|
371
|
+
f"Exceeds both {_TOTALCOUNT_PCT_TOLERANCE:.0%} and "
|
|
372
|
+
f"{_TOTALCOUNT_ABS_TOLERANCE} absolute tolerance."
|
|
373
|
+
)
|
|
374
|
+
logger.error(err_msg)
|
|
375
|
+
raise ValueError(err_msg)
|
|
376
|
+
if shortfall > 0:
|
|
377
|
+
logger.info(
|
|
378
|
+
"TotalCount=%d, fetched=%d (shortfall=%d, %.2f%% "
|
|
379
|
+
"— within tolerance, likely type_of_violence=4 "
|
|
380
|
+
"filtering)",
|
|
381
|
+
total_count,
|
|
382
|
+
len(all_events),
|
|
383
|
+
shortfall,
|
|
384
|
+
shortfall_pct * 100,
|
|
385
|
+
)
|
|
386
|
+
|
|
387
|
+
return all_events
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
# ---- Version Discovery ----
|
|
391
|
+
|
|
392
|
+
_ANNUAL_DISCOVERY_MAX_PROBES: int = 3
|
|
393
|
+
_ANNUAL_DISCOVERY_PROBE_PAGE_SIZE: int = 1
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def discover_annual_version(
|
|
397
|
+
current_version: str,
|
|
398
|
+
*,
|
|
399
|
+
base_url: str = UCDP_GED_API_BASE,
|
|
400
|
+
timeout: int = 30,
|
|
401
|
+
max_retries: int = 3,
|
|
402
|
+
token: str | None = None,
|
|
403
|
+
) -> str:
|
|
404
|
+
"""Probe the UCDP API for a newer annual version.
|
|
405
|
+
|
|
406
|
+
Annual versions follow the pattern ``{major}.1`` (25.1, 26.1, …).
|
|
407
|
+
Probes forward from the current major number until no data is found
|
|
408
|
+
or the probe limit is reached.
|
|
409
|
+
|
|
410
|
+
Returns the newest version with data, or *current_version* if
|
|
411
|
+
nothing newer exists.
|
|
412
|
+
"""
|
|
413
|
+
api_token = get_ucdp_token(token)
|
|
414
|
+
current_major = int(current_version.split(".")[0])
|
|
415
|
+
latest = current_version
|
|
416
|
+
|
|
417
|
+
for major in range(
|
|
418
|
+
current_major + 1,
|
|
419
|
+
current_major + 1 + _ANNUAL_DISCOVERY_MAX_PROBES,
|
|
420
|
+
):
|
|
421
|
+
probe_version = f"{major}.1"
|
|
422
|
+
url = f"{base_url}/{probe_version}"
|
|
423
|
+
headers = {"x-ucdp-access-token": api_token}
|
|
424
|
+
params = {"pagesize": _ANNUAL_DISCOVERY_PROBE_PAGE_SIZE}
|
|
425
|
+
|
|
426
|
+
try:
|
|
427
|
+
resp = request_with_retry(
|
|
428
|
+
url,
|
|
429
|
+
headers=headers,
|
|
430
|
+
params=params,
|
|
431
|
+
max_retries=max_retries,
|
|
432
|
+
timeout=timeout,
|
|
433
|
+
)
|
|
434
|
+
except requests.RequestException:
|
|
435
|
+
logger.debug(
|
|
436
|
+
"Annual version %s not available — stopping discovery",
|
|
437
|
+
probe_version,
|
|
438
|
+
)
|
|
439
|
+
break
|
|
440
|
+
|
|
441
|
+
data = resp.json()
|
|
442
|
+
try:
|
|
443
|
+
validate_envelope(data)
|
|
444
|
+
except ValueError:
|
|
445
|
+
logger.debug(
|
|
446
|
+
"Annual version %s returned invalid envelope",
|
|
447
|
+
probe_version,
|
|
448
|
+
)
|
|
449
|
+
break
|
|
450
|
+
|
|
451
|
+
total = data["TotalCount"]
|
|
452
|
+
if total == 0:
|
|
453
|
+
logger.info(
|
|
454
|
+
"Annual version %s has 0 events — stopping discovery",
|
|
455
|
+
probe_version,
|
|
456
|
+
)
|
|
457
|
+
break
|
|
458
|
+
|
|
459
|
+
latest = probe_version
|
|
460
|
+
logger.info(
|
|
461
|
+
"Discovered annual version %s (%d events)",
|
|
462
|
+
probe_version,
|
|
463
|
+
total,
|
|
464
|
+
)
|
|
465
|
+
|
|
466
|
+
return latest
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
# ---- Orchestrator ----
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def _snapshot_path(config: UcdpAnnualConfig) -> Path:
|
|
473
|
+
"""Deterministic path for the raw event snapshot."""
|
|
474
|
+
return (
|
|
475
|
+
config.data_dir
|
|
476
|
+
/ f"ucdp_ged_v{config.version}_{config.start_year}_{config.end_year}.parquet"
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def fetch_ucdp_annual(
|
|
481
|
+
config: UcdpAnnualConfig | None = None,
|
|
482
|
+
*,
|
|
483
|
+
token: str | None = None,
|
|
484
|
+
force_refresh: bool = False,
|
|
485
|
+
) -> Path:
|
|
486
|
+
"""Fetch UCDP/GED Annual data: fetch -> validate -> compare -> store -> provenance.
|
|
487
|
+
|
|
488
|
+
Args:
|
|
489
|
+
config: Harvest configuration (defaults to standard PRIO range).
|
|
490
|
+
token: API token (falls back to UCDP_API_TOKEN env var).
|
|
491
|
+
force_refresh: If True, re-fetch even if snapshot exists.
|
|
492
|
+
|
|
493
|
+
Returns:
|
|
494
|
+
Path to the stored Parquet snapshot.
|
|
495
|
+
"""
|
|
496
|
+
if config is None:
|
|
497
|
+
config = UcdpAnnualConfig()
|
|
498
|
+
|
|
499
|
+
# Probe for a newer annual release before checking the cache.
|
|
500
|
+
discovered = discover_annual_version(
|
|
501
|
+
config.version,
|
|
502
|
+
base_url=config.base_url,
|
|
503
|
+
timeout=config.timeout,
|
|
504
|
+
max_retries=config.max_retries,
|
|
505
|
+
token=token,
|
|
506
|
+
)
|
|
507
|
+
if discovered != config.version:
|
|
508
|
+
new_major = int(discovered.split(".")[0])
|
|
509
|
+
config = UcdpAnnualConfig(
|
|
510
|
+
version=discovered,
|
|
511
|
+
start_year=config.start_year,
|
|
512
|
+
end_year=new_major + _YEAR_OFFSET,
|
|
513
|
+
base_url=config.base_url,
|
|
514
|
+
page_size=config.page_size,
|
|
515
|
+
timeout=config.timeout,
|
|
516
|
+
max_retries=config.max_retries,
|
|
517
|
+
page_delay=config.page_delay,
|
|
518
|
+
data_dir=config.data_dir,
|
|
519
|
+
ledger_path=config.ledger_path,
|
|
520
|
+
)
|
|
521
|
+
logger.info(
|
|
522
|
+
"Upgraded to annual version %s (end_year=%d)",
|
|
523
|
+
discovered,
|
|
524
|
+
config.end_year,
|
|
525
|
+
)
|
|
526
|
+
|
|
527
|
+
snap_path = _snapshot_path(config)
|
|
528
|
+
|
|
529
|
+
# Digest-based short-circuit
|
|
530
|
+
if not force_refresh and snap_path.exists():
|
|
531
|
+
previous = last_digest(config.ledger_path)
|
|
532
|
+
if previous is not None:
|
|
533
|
+
logger.info(
|
|
534
|
+
"Snapshot exists and ledger has digest; skipping fetch "
|
|
535
|
+
"(use force_refresh=True to override)"
|
|
536
|
+
)
|
|
537
|
+
return snap_path
|
|
538
|
+
|
|
539
|
+
# Fetch
|
|
540
|
+
t0 = time.monotonic()
|
|
541
|
+
events = fetch_paginated(config, token=token)
|
|
542
|
+
fetch_duration = time.monotonic() - t0
|
|
543
|
+
|
|
544
|
+
# Validate
|
|
545
|
+
validation = validate_events(events, REQUIRED_FIELDS, FIELD_TYPES)
|
|
546
|
+
|
|
547
|
+
# Compute actual date coverage
|
|
548
|
+
min_date, max_date = date_range(events)
|
|
549
|
+
|
|
550
|
+
base_entry = {
|
|
551
|
+
"dataset": DATASET_ID,
|
|
552
|
+
"version": config.version,
|
|
553
|
+
"start_year": config.start_year,
|
|
554
|
+
"end_year": config.end_year,
|
|
555
|
+
"n_events": validation.n_events,
|
|
556
|
+
"min_date_start": min_date,
|
|
557
|
+
"max_date_start": max_date,
|
|
558
|
+
"fetch_duration_s": round(
|
|
559
|
+
fetch_duration, _FETCH_DURATION_PRECISION
|
|
560
|
+
),
|
|
561
|
+
"content_digest": validation.content_digest,
|
|
562
|
+
"ledger_version": LEDGER_VERSION,
|
|
563
|
+
"digest_algorithm": DIGEST_SCHEME,
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
if not validation.valid:
|
|
567
|
+
err_msg = f"Validation failed: {validation.errors}"
|
|
568
|
+
logger.error(err_msg)
|
|
569
|
+
append_ledger_entry(config.ledger_path, {
|
|
570
|
+
**base_entry,
|
|
571
|
+
"outcome": "failed",
|
|
572
|
+
"errors": validation.errors,
|
|
573
|
+
"warnings": validation.warnings,
|
|
574
|
+
})
|
|
575
|
+
raise ValueError(err_msg)
|
|
576
|
+
|
|
577
|
+
validate_dgp_assumptions(
|
|
578
|
+
events, UCDP_DGP_CHECKS, source_name="UCDP-annual",
|
|
579
|
+
)
|
|
580
|
+
validate_dgp_assumptions(
|
|
581
|
+
events,
|
|
582
|
+
UCDP_DGP_WARN_CHECKS,
|
|
583
|
+
source_name="UCDP-annual",
|
|
584
|
+
warn_only=True,
|
|
585
|
+
)
|
|
586
|
+
|
|
587
|
+
# Compare with previous snapshot
|
|
588
|
+
comparison: ComparisonResult | None = None
|
|
589
|
+
if snap_path.exists():
|
|
590
|
+
comparison = compare_snapshots(snap_path, events)
|
|
591
|
+
if comparison.has_previous and comparison.n_revised == 0:
|
|
592
|
+
logger.info("No revisions detected since previous snapshot")
|
|
593
|
+
|
|
594
|
+
# Archive old snapshot if it exists
|
|
595
|
+
if snap_path.exists():
|
|
596
|
+
archive_snapshot(snap_path)
|
|
597
|
+
|
|
598
|
+
# Store
|
|
599
|
+
save_event_snapshot(events, snap_path)
|
|
600
|
+
|
|
601
|
+
# Provenance
|
|
602
|
+
revision_warnings = comparison.warnings if comparison else []
|
|
603
|
+
append_ledger_entry(config.ledger_path, {
|
|
604
|
+
**base_entry,
|
|
605
|
+
"outcome": "success",
|
|
606
|
+
"schema_fields": sorted(validation.schema_snapshot.keys()),
|
|
607
|
+
"schema_types": validation.schema_snapshot,
|
|
608
|
+
"warnings": validation.warnings + revision_warnings,
|
|
609
|
+
"errors": validation.errors,
|
|
610
|
+
})
|
|
611
|
+
|
|
612
|
+
return snap_path
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
# Auto-register this source
|
|
616
|
+
register_source("ucdp_annual", fetch_ucdp_annual)
|