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,52 @@
|
|
|
1
|
+
"""Public output-format contract for ``load_dataset`` (ADR-050).
|
|
2
|
+
|
|
3
|
+
This module is the importable projection of the consumer contract
|
|
4
|
+
whose canonical, language-neutral form lives at
|
|
5
|
+
``tests/fixtures/feature_frame_contract/contract.json``. A test
|
|
6
|
+
asserts the two never drift (three-way agreement with the internal
|
|
7
|
+
``_VALID_FORMATS`` alias).
|
|
8
|
+
|
|
9
|
+
Stability promise (ADR-050):
|
|
10
|
+
- The meaning of existing members never changes.
|
|
11
|
+
- Removing or renaming a member is a MAJOR version event for the
|
|
12
|
+
package and for CONTRACT_VERSION.
|
|
13
|
+
- Adding a member is a MINOR event for both.
|
|
14
|
+
- CONTRACT_VERSION is independent of the package version and
|
|
15
|
+
changes only for contract-affecting changes (vocabulary, on-disk
|
|
16
|
+
layout, identifier/dtype semantics).
|
|
17
|
+
|
|
18
|
+
Consumers who cannot install the views-datafactory wheel should
|
|
19
|
+
read contract.json instead — both adoption paths are first-class.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from enum import StrEnum
|
|
25
|
+
|
|
26
|
+
CONTRACT_VERSION: str = "1.0.0"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class OutputFormat(StrEnum):
|
|
30
|
+
"""Valid ``load_dataset(output_format=...)`` values.
|
|
31
|
+
|
|
32
|
+
Each member names what ``load_dataset`` returns:
|
|
33
|
+
|
|
34
|
+
- ``FEATURE_FRAME``: a ``views_frames.FeatureFrame`` — float32
|
|
35
|
+
values of shape (N, F, S), index identifiers ``time`` (VIEWS
|
|
36
|
+
month_id, epoch 1980) and ``unit`` (``priogrid_id``).
|
|
37
|
+
- ``DATAFRAME``: a ``pandas.DataFrame`` with a
|
|
38
|
+
``(month_id, priogrid_id)`` MultiIndex, one column per
|
|
39
|
+
feature.
|
|
40
|
+
- ``COUNTRY_MONTH``: a ``pandas.DataFrame`` with a
|
|
41
|
+
``(month_id, country_id)`` MultiIndex — grid cells summed
|
|
42
|
+
per country for declared-extensive features (ADR-048).
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
FEATURE_FRAME = "feature_frame"
|
|
46
|
+
DATAFRAME = "dataframe"
|
|
47
|
+
COUNTRY_MONTH = "country_month"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def is_valid_output_format(value: str) -> bool:
|
|
51
|
+
"""True when *value* is a valid ``output_format`` string."""
|
|
52
|
+
return value in OutputFormat._value2member_map_
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
"""Region definitions — resolve region names to PRIO-GRID cell sets.
|
|
2
|
+
|
|
3
|
+
Source of truth: GAUL Parquet files (data/raw/gaul_admin/).
|
|
4
|
+
Region groupings are curated mappings of GAUL country names.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import logging
|
|
11
|
+
from functools import lru_cache
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
import pyarrow.parquet as pq
|
|
15
|
+
|
|
16
|
+
from datafactory_priogrid.grid_config import DEFAULT_GRID_CONFIG
|
|
17
|
+
|
|
18
|
+
__all__ = ["list_regions", "load_region_pgids"]
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
_DEFAULT_GAUL_DIR = Path("data/raw/gaul_admin")
|
|
23
|
+
|
|
24
|
+
# ── Curated region definitions ─────────────────────────
|
|
25
|
+
# Keys: GAUL country/territory names (from gaul0_name.parquet).
|
|
26
|
+
# These match FAO GAUL 2024 naming conventions exactly.
|
|
27
|
+
|
|
28
|
+
_AFRICA: list[str] = [
|
|
29
|
+
"Abyei", # disputed (Sudan/South Sudan)
|
|
30
|
+
"Algeria", "Angola", "Benin", "Botswana", "Burkina Faso",
|
|
31
|
+
"Burundi", "Cameroon", "Central African Republic", "Chad",
|
|
32
|
+
"Comoros", "Congo", "Côte D'Ivoire",
|
|
33
|
+
"Democratic Republic of the Congo", "Djibouti", "Egypt",
|
|
34
|
+
"Equatorial Guinea", "Eritrea", "Eswatini", "Ethiopia",
|
|
35
|
+
"Gabon", "Gambia", "Ghana", "Guinea", "Guinea-Bissau",
|
|
36
|
+
"Hala'Ib Triangle", # disputed (Egypt/Sudan)
|
|
37
|
+
"Ilemi Triangle", # disputed (Kenya/South Sudan)
|
|
38
|
+
"Kenya", "Lesotho", "Liberia", "Libya", "Madagascar",
|
|
39
|
+
"Malawi", "Mali", "Mauritania", "Mauritius", "Morocco",
|
|
40
|
+
"Mozambique", "Namibia", "Niger", "Nigeria", "Rwanda",
|
|
41
|
+
"Réunion", "Senegal", "Sierra Leone", "Somalia",
|
|
42
|
+
"South Africa", "South Sudan", "Sudan", "Togo", "Tunisia",
|
|
43
|
+
"Uganda", "United Republic of Tanzania", "Western Sahara",
|
|
44
|
+
"Zambia", "Zimbabwe",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
_MIDDLE_EAST: list[str] = [
|
|
48
|
+
"Iran (Islamic Republic Of)", "Iraq", "Israel",
|
|
49
|
+
"Jordan", "Kuwait", "Lebanon", "Oman", "Palestine", "Qatar",
|
|
50
|
+
"Saudi Arabia", "Syrian Arab Republic", "Türkiye",
|
|
51
|
+
"United Arab Emirates", "Yemen",
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
_AMERICAS: list[str] = [
|
|
55
|
+
"Argentina", "Bahamas", "Belize",
|
|
56
|
+
"Bolivia (Plurinational State of)", "Brazil", "Canada",
|
|
57
|
+
"Cayman Islands", "Chile", "Colombia", "Costa Rica", "Cuba",
|
|
58
|
+
"Dominican Republic", "Ecuador", "El Salvador",
|
|
59
|
+
"Falkland Islands (Malvinas)", "French Guiana",
|
|
60
|
+
"Greenland", "Guadeloupe", "Guatemala",
|
|
61
|
+
"Guyana", "Haiti", "Honduras", "Jamaica", "Mexico",
|
|
62
|
+
"Nicaragua", "Panama", "Paraguay", "Peru", "Puerto Rico",
|
|
63
|
+
"Saint Vincent and the Grenadines", "Suriname",
|
|
64
|
+
"Trinidad And Tobago",
|
|
65
|
+
"Turks And Caicos Islands", "United States Virgin Islands",
|
|
66
|
+
"United States of America", "Uruguay",
|
|
67
|
+
"Venezuela (Bolivarian Republic Of)",
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
_EUROPE: list[str] = [
|
|
71
|
+
"Albania", "Armenia", "Austria", "Azerbaijan", "Belarus",
|
|
72
|
+
"Belgium",
|
|
73
|
+
"Bosnia and Herzegovina", "Bulgaria", "Croatia", "Cyprus",
|
|
74
|
+
"Czechia", "Denmark", "Estonia", "Finland", "France",
|
|
75
|
+
"Georgia", "Germany", "Greece", "Hungary", "Iceland",
|
|
76
|
+
"Ireland", "Italy", "Jersey", "Kazakhstan", "Kuril Islands",
|
|
77
|
+
"Kyrgyzstan",
|
|
78
|
+
"Latvia", "Lithuania", "Luxembourg", "Montenegro",
|
|
79
|
+
"Netherlands (Kingdom of the)", "North Macedonia", "Norway",
|
|
80
|
+
"Poland", "Portugal", "Republic of Moldova", "Romania",
|
|
81
|
+
"Russian Federation", "Serbia", "Slovakia", "Slovenia",
|
|
82
|
+
"Spain", "Svalbard and Jan Mayen Islands",
|
|
83
|
+
"Sweden", "Switzerland", "Tajikistan",
|
|
84
|
+
"Turkmenistan",
|
|
85
|
+
"Ukraine",
|
|
86
|
+
"United Kingdom of Great Britain and Northern Ireland",
|
|
87
|
+
"Uzbekistan", "Åland Islands",
|
|
88
|
+
]
|
|
89
|
+
|
|
90
|
+
_ASIA_OCEANIA: list[str] = [
|
|
91
|
+
"Afghanistan", "Aksai Chin", # disputed (China/India)
|
|
92
|
+
"Arunachal Pradesh", # disputed (India/China)
|
|
93
|
+
"Australia",
|
|
94
|
+
"Bangladesh", "Bhutan", "Brunei Darussalam",
|
|
95
|
+
"Cambodia", "China", "China, Hong Kong SAR", "Cook Islands",
|
|
96
|
+
"Democratic People's Republic of Korea", "Fiji",
|
|
97
|
+
"French Polynesia", "India",
|
|
98
|
+
"Indonesia", "Jammu And Kashmir", # disputed (India/Pakistan)
|
|
99
|
+
"Japan", "Kiribati",
|
|
100
|
+
"Lao People's Democratic Republic", "Malaysia", "Maldives",
|
|
101
|
+
"Marshall Islands", "Mongolia", "Myanmar", "Nepal",
|
|
102
|
+
"New Caledonia", "New Zealand", "Pakistan", "Papua New Guinea",
|
|
103
|
+
"Philippines", "Republic Of Korea", "Samoa",
|
|
104
|
+
"Solomon Islands", "Sri Lanka",
|
|
105
|
+
"Taiwan Province of China", "Thailand", "Timor-Leste",
|
|
106
|
+
"Vanuatu", "Viet Nam",
|
|
107
|
+
]
|
|
108
|
+
|
|
109
|
+
REGIONS: dict[str, list[str]] = {
|
|
110
|
+
"africa": _AFRICA,
|
|
111
|
+
"middle_east": _MIDDLE_EAST,
|
|
112
|
+
"africa_me": _AFRICA + _MIDDLE_EAST,
|
|
113
|
+
"americas": _AMERICAS,
|
|
114
|
+
"europe": _EUROPE,
|
|
115
|
+
"asia_oceania": _ASIA_OCEANIA,
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def list_regions() -> list[str]:
|
|
120
|
+
"""List available predefined region names.
|
|
121
|
+
|
|
122
|
+
Returns region names that can be passed to load_region_pgids().
|
|
123
|
+
Special values "global", "land", and "land_gaul" are always
|
|
124
|
+
available. Individual country names (matching GAUL) also work.
|
|
125
|
+
"""
|
|
126
|
+
return sorted([
|
|
127
|
+
"global", "land", "land_gaul",
|
|
128
|
+
"africa_me_legacy", "africa_me_gaul",
|
|
129
|
+
*REGIONS.keys(),
|
|
130
|
+
])
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@lru_cache(maxsize=1)
|
|
134
|
+
def _load_land_pgids() -> set[int]:
|
|
135
|
+
"""Load the 64,818 land PRIO-GRID cell IDs.
|
|
136
|
+
|
|
137
|
+
Bundled with the package as land_pgids.json.
|
|
138
|
+
"""
|
|
139
|
+
path = Path(__file__).parent / "land_pgids.json"
|
|
140
|
+
pgids = json.loads(path.read_text())
|
|
141
|
+
return set(pgids)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
@lru_cache(maxsize=1)
|
|
145
|
+
def _load_land_gaul_pgids() -> set[int]:
|
|
146
|
+
"""Load the 64,742 land cells with GAUL coverage.
|
|
147
|
+
|
|
148
|
+
Intersection of land (64,818) and cells with gaul0_code != -1.
|
|
149
|
+
The 76 excluded cells are small islands outside FAO GAUL 2024
|
|
150
|
+
polygon coverage. Bundled as land_gaul_pgids.json.
|
|
151
|
+
"""
|
|
152
|
+
path = Path(__file__).parent / "land_gaul_pgids.json"
|
|
153
|
+
pgids = json.loads(path.read_text())
|
|
154
|
+
return set(pgids)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@lru_cache(maxsize=1)
|
|
158
|
+
def _load_legacy_pgids() -> set[int]:
|
|
159
|
+
"""Load the VIEWSER-era Africa+ME pgid set (13,110 cells).
|
|
160
|
+
|
|
161
|
+
Bundled with the package as africa_me_legacy_pgids.json.
|
|
162
|
+
This is the exact spatial coverage used by VIEWSER's
|
|
163
|
+
priogrid_month table, extracted from purple_alien's cached
|
|
164
|
+
data. It does not correspond exactly to any GAUL-based
|
|
165
|
+
region due to VIEWSER's independent land mask.
|
|
166
|
+
"""
|
|
167
|
+
path = Path(__file__).parent / "africa_me_legacy_pgids.json"
|
|
168
|
+
pgids = json.loads(path.read_text())
|
|
169
|
+
return set(pgids)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@lru_cache(maxsize=1)
|
|
173
|
+
def _load_africa_me_gaul_pgids() -> set[int]:
|
|
174
|
+
"""Load the africa_me_legacy ∩ land_gaul pgid set (13,105 cells).
|
|
175
|
+
|
|
176
|
+
Bundled with the package as africa_me_gaul_pgids.json.
|
|
177
|
+
This is africa_me_legacy minus the 5 cells absent from
|
|
178
|
+
land_gaul (gids 62356, 94776, 99027, 107733, 107742).
|
|
179
|
+
Solves the region/coverage mismatch (#215).
|
|
180
|
+
"""
|
|
181
|
+
path = Path(__file__).parent / "africa_me_gaul_pgids.json"
|
|
182
|
+
pgids = json.loads(path.read_text())
|
|
183
|
+
return set(pgids)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
@lru_cache(maxsize=1)
|
|
187
|
+
def _load_country_pgids(
|
|
188
|
+
gaul_dir: Path,
|
|
189
|
+
) -> dict[str, set[int]]:
|
|
190
|
+
"""Load country_name → set[pgid] mapping from GAUL Parquets.
|
|
191
|
+
|
|
192
|
+
Cached after first call. Reads gaul0_name.parquet.
|
|
193
|
+
"""
|
|
194
|
+
name_path = gaul_dir / "gaul0_name.parquet"
|
|
195
|
+
if not name_path.exists():
|
|
196
|
+
msg = (
|
|
197
|
+
f"GAUL data not found at {gaul_dir}. "
|
|
198
|
+
f"Run: uv run python scripts/harvest_gaul.py"
|
|
199
|
+
)
|
|
200
|
+
raise FileNotFoundError(msg)
|
|
201
|
+
|
|
202
|
+
table = pq.read_table(name_path)
|
|
203
|
+
gids = table.column("gid").to_pylist()
|
|
204
|
+
names = table.column("value").to_pylist()
|
|
205
|
+
|
|
206
|
+
country_pgids: dict[str, set[int]] = {}
|
|
207
|
+
for gid, name in zip(gids, names, strict=True):
|
|
208
|
+
country_pgids.setdefault(name, set()).add(gid)
|
|
209
|
+
|
|
210
|
+
logger.info(
|
|
211
|
+
"Loaded %d countries, %d cells from %s",
|
|
212
|
+
len(country_pgids),
|
|
213
|
+
len(gids),
|
|
214
|
+
name_path,
|
|
215
|
+
)
|
|
216
|
+
return country_pgids
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def load_region_pgids(
|
|
220
|
+
region: str,
|
|
221
|
+
*,
|
|
222
|
+
gaul_dir: Path = _DEFAULT_GAUL_DIR,
|
|
223
|
+
) -> set[int]:
|
|
224
|
+
"""Resolve a region name to a set of PRIO-GRID cell IDs.
|
|
225
|
+
|
|
226
|
+
Args:
|
|
227
|
+
region: One of:
|
|
228
|
+
- Predefined region: "africa", "middle_east", "africa_me",
|
|
229
|
+
"americas", "europe", "asia_oceania"
|
|
230
|
+
- Special: "global" (all 259,200), "land" (64,818),
|
|
231
|
+
"land_gaul" (64,742 = land ∩ GAUL coverage)
|
|
232
|
+
- Country name matching GAUL (e.g., "Ethiopia")
|
|
233
|
+
gaul_dir: Path to GAUL admin Parquet files.
|
|
234
|
+
|
|
235
|
+
Returns:
|
|
236
|
+
Set of pgids belonging to the region.
|
|
237
|
+
|
|
238
|
+
Raises:
|
|
239
|
+
ValueError: If region name is not recognized.
|
|
240
|
+
FileNotFoundError: If GAUL data is not available.
|
|
241
|
+
"""
|
|
242
|
+
if region == "global":
|
|
243
|
+
return set(range(1, DEFAULT_GRID_CONFIG.n_cells + 1))
|
|
244
|
+
|
|
245
|
+
if region == "land":
|
|
246
|
+
return _load_land_pgids()
|
|
247
|
+
|
|
248
|
+
if region == "land_gaul":
|
|
249
|
+
return _load_land_gaul_pgids()
|
|
250
|
+
|
|
251
|
+
if region == "africa_me_legacy":
|
|
252
|
+
return _load_legacy_pgids()
|
|
253
|
+
|
|
254
|
+
if region == "africa_me_gaul":
|
|
255
|
+
return _load_africa_me_gaul_pgids()
|
|
256
|
+
|
|
257
|
+
# Predefined macro-region
|
|
258
|
+
if region in REGIONS:
|
|
259
|
+
country_pgids = _load_country_pgids(gaul_dir)
|
|
260
|
+
result: set[int] = set()
|
|
261
|
+
missing = []
|
|
262
|
+
for country in REGIONS[region]:
|
|
263
|
+
pgids = country_pgids.get(country)
|
|
264
|
+
if pgids is not None:
|
|
265
|
+
result |= pgids
|
|
266
|
+
else:
|
|
267
|
+
missing.append(country)
|
|
268
|
+
if missing:
|
|
269
|
+
logger.warning(
|
|
270
|
+
"Region %r: %d countries not found in GAUL: %s",
|
|
271
|
+
region, len(missing), missing,
|
|
272
|
+
)
|
|
273
|
+
return result
|
|
274
|
+
|
|
275
|
+
# Try as individual country name
|
|
276
|
+
country_pgids = _load_country_pgids(gaul_dir)
|
|
277
|
+
if region in country_pgids:
|
|
278
|
+
return country_pgids[region]
|
|
279
|
+
|
|
280
|
+
# Case-insensitive fallback
|
|
281
|
+
lower_map = {k.lower(): k for k in country_pgids}
|
|
282
|
+
if region.lower() in lower_map:
|
|
283
|
+
return country_pgids[lower_map[region.lower()]]
|
|
284
|
+
|
|
285
|
+
available = sorted(
|
|
286
|
+
["global", "land"] + list(REGIONS.keys())
|
|
287
|
+
)
|
|
288
|
+
msg = (
|
|
289
|
+
f"Unknown region {region!r}. "
|
|
290
|
+
f"Available: {available}. "
|
|
291
|
+
f"Or use a GAUL country name."
|
|
292
|
+
)
|
|
293
|
+
raise ValueError(msg)
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Temporal query parsing — flexible input to datetime64[M] range.
|
|
2
|
+
|
|
3
|
+
Accepts ISO strings, VIEWS month_ids, year-only strings, or None.
|
|
4
|
+
Delegates to datafactory_priogrid for the VIEWS epoch convention.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
from datafactory_priogrid.temporal_generator import from_views_month_id
|
|
14
|
+
|
|
15
|
+
__all__ = ["parse_time_range", "time_range_to_slice"]
|
|
16
|
+
|
|
17
|
+
_YEAR_RE = re.compile(r"^\d{4}$")
|
|
18
|
+
_MONTH_RE = re.compile(r"^\d{4}-\d{2}$")
|
|
19
|
+
_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _parse_single(value: str | int) -> np.datetime64:
|
|
23
|
+
"""Parse a single time value to datetime64[M]."""
|
|
24
|
+
if isinstance(value, int):
|
|
25
|
+
# VIEWS month_id
|
|
26
|
+
result: np.datetime64 = from_views_month_id(value).item()
|
|
27
|
+
return result
|
|
28
|
+
|
|
29
|
+
if _YEAR_RE.match(value):
|
|
30
|
+
return np.datetime64(f"{value}-01", "M")
|
|
31
|
+
|
|
32
|
+
if _MONTH_RE.match(value):
|
|
33
|
+
return np.datetime64(value, "M")
|
|
34
|
+
|
|
35
|
+
if _DATE_RE.match(value):
|
|
36
|
+
# Truncate to month
|
|
37
|
+
return np.datetime64(value[:7], "M")
|
|
38
|
+
|
|
39
|
+
msg = (
|
|
40
|
+
f"Cannot parse time value {value!r}. "
|
|
41
|
+
f"Expected: 'YYYY', 'YYYY-MM', 'YYYY-MM-DD', "
|
|
42
|
+
f"or int (VIEWS month_id)."
|
|
43
|
+
)
|
|
44
|
+
raise ValueError(msg)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def parse_time_range(
|
|
48
|
+
start: str | int | None = None,
|
|
49
|
+
end: str | int | None = None,
|
|
50
|
+
*,
|
|
51
|
+
time_steps: np.ndarray | None = None,
|
|
52
|
+
) -> tuple[np.datetime64, np.datetime64]:
|
|
53
|
+
"""Parse flexible time inputs to a datetime64[M] range.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
start: Start of range (inclusive). Accepts ISO string,
|
|
57
|
+
VIEWS month_id (int), year-only string, or None
|
|
58
|
+
(uses first time step).
|
|
59
|
+
end: End of range (inclusive). Same formats as start,
|
|
60
|
+
or None (uses last time step). Year-only strings
|
|
61
|
+
resolve to December of that year.
|
|
62
|
+
time_steps: Reference array for None defaults. Required
|
|
63
|
+
if start or end is None.
|
|
64
|
+
|
|
65
|
+
Returns:
|
|
66
|
+
(start_dt, end_dt) as datetime64[M], both inclusive.
|
|
67
|
+
|
|
68
|
+
Raises:
|
|
69
|
+
ValueError: If input cannot be parsed or time_steps is
|
|
70
|
+
needed but not provided.
|
|
71
|
+
"""
|
|
72
|
+
if start is None:
|
|
73
|
+
if time_steps is None:
|
|
74
|
+
msg = "start=None requires time_steps"
|
|
75
|
+
raise ValueError(msg)
|
|
76
|
+
start_dt = time_steps[0]
|
|
77
|
+
else:
|
|
78
|
+
start_dt = _parse_single(start)
|
|
79
|
+
|
|
80
|
+
if end is None:
|
|
81
|
+
if time_steps is None:
|
|
82
|
+
msg = "end=None requires time_steps"
|
|
83
|
+
raise ValueError(msg)
|
|
84
|
+
end_dt = time_steps[-1]
|
|
85
|
+
elif isinstance(end, str) and _YEAR_RE.match(end):
|
|
86
|
+
# Year-only end → December of that year
|
|
87
|
+
end_dt = np.datetime64(f"{end}-12", "M")
|
|
88
|
+
else:
|
|
89
|
+
end_dt = _parse_single(end)
|
|
90
|
+
|
|
91
|
+
return np.datetime64(start_dt, "M"), np.datetime64(end_dt, "M")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def time_range_to_slice(
|
|
95
|
+
time_steps: np.ndarray,
|
|
96
|
+
start: np.datetime64,
|
|
97
|
+
end: np.datetime64,
|
|
98
|
+
) -> slice:
|
|
99
|
+
"""Convert a datetime64 range to an index slice into time_steps.
|
|
100
|
+
|
|
101
|
+
Both start and end are inclusive. Returns a slice object
|
|
102
|
+
suitable for indexing the T dimension of the grid.
|
|
103
|
+
|
|
104
|
+
Raises:
|
|
105
|
+
ValueError: If the range has no overlap with time_steps.
|
|
106
|
+
"""
|
|
107
|
+
mask = (time_steps >= start) & (time_steps <= end)
|
|
108
|
+
indices = np.where(mask)[0]
|
|
109
|
+
if len(indices) == 0:
|
|
110
|
+
msg = (
|
|
111
|
+
f"Time range {start}..{end} has no overlap with "
|
|
112
|
+
f"time_steps ({time_steps[0]}..{time_steps[-1]})"
|
|
113
|
+
)
|
|
114
|
+
raise ValueError(msg)
|
|
115
|
+
return slice(int(indices[0]), int(indices[-1]) + 1)
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# datafactory_viewpoint -- Architecture
|
|
2
|
+
|
|
3
|
+
## Purpose
|
|
4
|
+
|
|
5
|
+
Opinionated, versioned, rebuildable materialized views over consolidated event stores. Each viewpoint applies explicit survivorship rules, temporal distribution strategies, and uncertainty handling to produce a single perspective on the data. Multiple viewpoints coexist over the same consolidated base. This implements the golden record concept from master data management (ADR-014). This is a Layer 3 package in the dependency DAG (ADR-012).
|
|
6
|
+
|
|
7
|
+
## Responsibility Boundary
|
|
8
|
+
|
|
9
|
+
**Owns:**
|
|
10
|
+
- Survivorship rules (which version of an event wins when sources disagree — `annual_wins`, `dot9_wins`)
|
|
11
|
+
- Temporal distribution (how summary events spanning multiple months are spread — `even_split`, `ceil_split`)
|
|
12
|
+
- Event filtering (priogrid_gid, type_of_violence, where_prec — configurable per viewpoint)
|
|
13
|
+
- Field selection (which fields from the consolidated store propagate to the viewpoint)
|
|
14
|
+
- Month assignment (whether `date_start` or `date_end` determines the event's month)
|
|
15
|
+
- Named profiles — pre-configured strategy + filter combinations (`production_parity`, etc.)
|
|
16
|
+
- Viewpoint configuration versioning
|
|
17
|
+
|
|
18
|
+
**Does NOT own:**
|
|
19
|
+
- Data fetching or harvesting (datafactory_harvester — Layer 1)
|
|
20
|
+
- Raw snapshot consolidation (datafactory_consolidation — Layer 2)
|
|
21
|
+
- Grid placement or aggregation (datafactory_compilation — Layer 4)
|
|
22
|
+
- Output format decisions (datafactory_compilation — Layer 4)
|
|
23
|
+
|
|
24
|
+
## Dependency Rules
|
|
25
|
+
|
|
26
|
+
**May import:** `datafactory_provenance`
|
|
27
|
+
**Reads filesystem output of:** `datafactory_consolidation` (consolidated event store)
|
|
28
|
+
**Must never import:** `datafactory_priogrid`, `datafactory_harvester`, `datafactory_consolidation`, `datafactory_compilation`, or any consumer
|
|
29
|
+
|
|
30
|
+
## Package Structure
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
datafactory_viewpoint/
|
|
34
|
+
__init__.py # Public API: ViewpointConfig, ViewpointResult, registry
|
|
35
|
+
ARCHITECTURE.md # This file
|
|
36
|
+
viewpoint_config.py # Frozen config: strategies, filters, version tag
|
|
37
|
+
viewpoint_result.py # Frozen result dataclass
|
|
38
|
+
survivorship.py # Strategy registry: annual_wins, dot9_wins
|
|
39
|
+
temporal_distribution.py # Strategy registry: even_split, ceil_split
|
|
40
|
+
profiles.py # Named presets: production_parity, etc.
|
|
41
|
+
raster_io.py # GeoTIFF raster I/O: read, reproject, aggregate to PRIO-GRID
|
|
42
|
+
temporal.py # Temporal interpolation for epoch-based raster sources
|
|
43
|
+
builders/
|
|
44
|
+
__init__.py # Registry: register_builder, build_viewpoint
|
|
45
|
+
ucdp_v1.py # UCDP viewpoint builder (survivorship + distribution + filters)
|
|
46
|
+
acled_v1.py # ACLED viewpoint builder (event type filter + aggregation)
|
|
47
|
+
ghspop_v1.py # GHS-POP viewpoint builder (raster spatial agg + temporal interp)
|
|
48
|
+
ghsbuilts_v1.py # GHS-BUILT-S viewpoint builder (raster spatial agg + temporal interp)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Key Concepts
|
|
52
|
+
|
|
53
|
+
| Concept | Description |
|
|
54
|
+
|---------|-------------|
|
|
55
|
+
| Viewpoint | An opinionated materialized view: one perspective on consolidated data, produced by explicit rules |
|
|
56
|
+
| Builder | Source-specific function that reads a consolidated store and writes a viewpoint Parquet |
|
|
57
|
+
| Survivorship strategy | Pluggable rule for choosing between versions of the same event (decorator-registered, OCP) |
|
|
58
|
+
| Temporal distribution strategy | Pluggable rule for distributing summary events across months (decorator-registered, OCP) |
|
|
59
|
+
| ViewpointConfig | Frozen dataclass declaring which strategies to apply, which fields to select, which version tag |
|
|
60
|
+
|
|
61
|
+
## Invariants
|
|
62
|
+
|
|
63
|
+
- **Rebuildable:** A viewpoint can be deleted and rebuilt from the consolidated store at any time. This is normal operation, not error recovery.
|
|
64
|
+
- **Pure function:** Output = f(consolidated store, configuration). No hidden state.
|
|
65
|
+
- **Versioned:** Each viewpoint configuration has a version tag. Multiple versions coexist.
|
|
66
|
+
- **Provenance:** Every build writes a ledger entry: consolidated store digest + config version → output digest.
|
|
67
|
+
- **Fail-loud:** Build failures are logged and raised (ADR-008). No silent fallbacks.
|
|
68
|
+
- **No data invention:** A viewpoint must not contain information absent from the consolidated store.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Viewpoint builders: opinionated, versioned views over consolidated data.
|
|
2
|
+
|
|
3
|
+
A viewpoint is a disposable, rebuildable, materialized view that applies
|
|
4
|
+
explicit rules (survivorship, temporal distribution, uncertainty handling)
|
|
5
|
+
to produce a single perspective on the consolidated event store. Multiple
|
|
6
|
+
viewpoints coexist. This implements the golden record concept (ADR-014).
|
|
7
|
+
|
|
8
|
+
Access specific builders via:
|
|
9
|
+
from datafactory_viewpoint.builders.ucdp_v1 import build_ucdp_v1
|
|
10
|
+
|
|
11
|
+
Or use the registry:
|
|
12
|
+
from datafactory_viewpoint.builders import build_viewpoint
|
|
13
|
+
build_viewpoint("ucdp_v1", config=...)
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from datafactory_viewpoint.builders import (
|
|
17
|
+
build_viewpoint,
|
|
18
|
+
list_builders,
|
|
19
|
+
register_builder,
|
|
20
|
+
)
|
|
21
|
+
from datafactory_viewpoint.profiles import list_profiles, load_profile
|
|
22
|
+
from datafactory_viewpoint.viewpoint_config import ViewpointConfig
|
|
23
|
+
from datafactory_viewpoint.viewpoint_result import ViewpointResult
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"ViewpointConfig",
|
|
27
|
+
"ViewpointResult",
|
|
28
|
+
"build_viewpoint",
|
|
29
|
+
"list_builders",
|
|
30
|
+
"list_profiles",
|
|
31
|
+
"load_profile",
|
|
32
|
+
"register_builder",
|
|
33
|
+
]
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Pluggable viewpoint builder registry.
|
|
2
|
+
|
|
3
|
+
Each builder module registers itself via register_builder().
|
|
4
|
+
Consumers call build_viewpoint(name, ...) without knowing the implementation.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
__all__ = ["build_viewpoint", "list_builders", "register_builder"]
|
|
13
|
+
|
|
14
|
+
from datafactory_provenance.registry import Registry
|
|
15
|
+
|
|
16
|
+
_registry: Registry[Callable[..., Any]] = Registry("viewpoint builder")
|
|
17
|
+
|
|
18
|
+
register_builder = _registry.register
|
|
19
|
+
list_builders = _registry.list_entries
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def build_viewpoint(name: str, **kwargs: Any) -> Any:
|
|
23
|
+
"""Build a viewpoint using a registered builder.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
name: Builder identifier.
|
|
27
|
+
**kwargs: Passed to the builder function.
|
|
28
|
+
|
|
29
|
+
Raises:
|
|
30
|
+
KeyError: If the builder name is not registered.
|
|
31
|
+
"""
|
|
32
|
+
return _registry.get(name)(**kwargs)
|