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.
Files changed (103) hide show
  1. datafactory_adapters/ARCHITECTURE.md +54 -0
  2. datafactory_adapters/__init__.py +38 -0
  3. datafactory_adapters/_conservation.py +95 -0
  4. datafactory_adapters/_reconciliation.py +92 -0
  5. datafactory_adapters/_validation.py +39 -0
  6. datafactory_adapters/feature_frame.py +25 -0
  7. datafactory_adapters/grid_from_feature_frame.py +89 -0
  8. datafactory_adapters/grid_to_country_month.py +169 -0
  9. datafactory_adapters/grid_to_dataframe.py +176 -0
  10. datafactory_compilation/ARCHITECTURE.md +63 -0
  11. datafactory_compilation/__init__.py +39 -0
  12. datafactory_compilation/aggregation.py +64 -0
  13. datafactory_compilation/compilation_config.py +97 -0
  14. datafactory_compilation/conservation.py +36 -0
  15. datafactory_compilation/grid_compilation.py +352 -0
  16. datafactory_compilation/output.py +85 -0
  17. datafactory_compilation/preflight.py +61 -0
  18. datafactory_compilation/pregridded_compilation.py +291 -0
  19. datafactory_consolidation/ARCHITECTURE.md +58 -0
  20. datafactory_consolidation/__init__.py +28 -0
  21. datafactory_consolidation/consolidation_result.py +27 -0
  22. datafactory_consolidation/consolidators/__init__.py +32 -0
  23. datafactory_consolidation/consolidators/acled.py +462 -0
  24. datafactory_consolidation/consolidators/ucdp.py +524 -0
  25. datafactory_consolidation/event_store.py +67 -0
  26. datafactory_consolidation/tagging.py +46 -0
  27. datafactory_harvester/ARCHITECTURE.md +103 -0
  28. datafactory_harvester/__init__.py +37 -0
  29. datafactory_harvester/event_validation.py +372 -0
  30. datafactory_harvester/harvest_runner.py +72 -0
  31. datafactory_harvester/pipeline_runner.py +125 -0
  32. datafactory_harvester/snapshot_storage.py +117 -0
  33. datafactory_harvester/sources/__init__.py +36 -0
  34. datafactory_harvester/sources/_ucdp_common.py +34 -0
  35. datafactory_harvester/sources/acled.py +743 -0
  36. datafactory_harvester/sources/gaul_admin.py +567 -0
  37. datafactory_harvester/sources/ghsbuilts.py +271 -0
  38. datafactory_harvester/sources/ghspop.py +267 -0
  39. datafactory_harvester/sources/priogrid_static.py +359 -0
  40. datafactory_harvester/sources/shdi.py +625 -0
  41. datafactory_harvester/sources/ucdp_annual.py +616 -0
  42. datafactory_harvester/sources/ucdp_candidate.py +419 -0
  43. datafactory_harvester/sources/ucdp_dot9.py +407 -0
  44. datafactory_harvester/sources/vdem.py +350 -0
  45. datafactory_harvester/validation.py +74 -0
  46. datafactory_http/__init__.py +10 -0
  47. datafactory_http/retry.py +102 -0
  48. datafactory_priogrid/ARCHITECTURE.md +62 -0
  49. datafactory_priogrid/__init__.py +51 -0
  50. datafactory_priogrid/cell_generator.py +137 -0
  51. datafactory_priogrid/grid_config.py +107 -0
  52. datafactory_priogrid/land_mask.py +62 -0
  53. datafactory_priogrid/parity_validation.py +176 -0
  54. datafactory_priogrid/shapefile_harvester.py +174 -0
  55. datafactory_priogrid/shapefile_reader.py +125 -0
  56. datafactory_priogrid/spatiotemporal.py +66 -0
  57. datafactory_priogrid/temporal_config.py +78 -0
  58. datafactory_priogrid/temporal_generator.py +65 -0
  59. datafactory_provenance/ARCHITECTURE.md +61 -0
  60. datafactory_provenance/__init__.py +81 -0
  61. datafactory_provenance/constants.py +3 -0
  62. datafactory_provenance/digests_and_ledgers.py +370 -0
  63. datafactory_provenance/health.py +310 -0
  64. datafactory_provenance/pipeline_lock.py +200 -0
  65. datafactory_provenance/registry.py +92 -0
  66. datafactory_provenance/skip.py +212 -0
  67. datafactory_provenance/source_registry.py +466 -0
  68. datafactory_query/ARCHITECTURE.md +60 -0
  69. datafactory_query/__init__.py +36 -0
  70. datafactory_query/africa_me_gaul_pgids.json +1 -0
  71. datafactory_query/africa_me_legacy_pgids.json +1 -0
  72. datafactory_query/backends_npy.py +90 -0
  73. datafactory_query/backends_zarr.py +259 -0
  74. datafactory_query/coverage.py +64 -0
  75. datafactory_query/dataset.py +263 -0
  76. datafactory_query/defaults.py +101 -0
  77. datafactory_query/land_gaul_pgids.json +1 -0
  78. datafactory_query/land_pgids.json +1 -0
  79. datafactory_query/output_format.py +52 -0
  80. datafactory_query/regions.py +293 -0
  81. datafactory_query/temporal.py +115 -0
  82. datafactory_viewpoint/ARCHITECTURE.md +68 -0
  83. datafactory_viewpoint/__init__.py +33 -0
  84. datafactory_viewpoint/builders/__init__.py +32 -0
  85. datafactory_viewpoint/builders/acled_v1.py +213 -0
  86. datafactory_viewpoint/builders/ghsbuilts_v1.py +351 -0
  87. datafactory_viewpoint/builders/ghspop_v1.py +471 -0
  88. datafactory_viewpoint/builders/shdi_v1.py +389 -0
  89. datafactory_viewpoint/builders/ucdp_v1.py +437 -0
  90. datafactory_viewpoint/builders/vdem_v1.py +419 -0
  91. datafactory_viewpoint/profiles.py +169 -0
  92. datafactory_viewpoint/raster_io.py +49 -0
  93. datafactory_viewpoint/spatial_distribution.py +203 -0
  94. datafactory_viewpoint/spatial_weights.py +207 -0
  95. datafactory_viewpoint/survivorship.py +108 -0
  96. datafactory_viewpoint/temporal.py +111 -0
  97. datafactory_viewpoint/temporal_distribution.py +295 -0
  98. datafactory_viewpoint/viewpoint_config.py +124 -0
  99. datafactory_viewpoint/viewpoint_result.py +33 -0
  100. views_datafactory-1.9.0.dist-info/METADATA +528 -0
  101. views_datafactory-1.9.0.dist-info/RECORD +103 -0
  102. views_datafactory-1.9.0.dist-info/WHEEL +4 -0
  103. views_datafactory-1.9.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,295 @@
1
+ """Temporal distribution strategy registry for viewpoint building.
2
+
3
+ Each strategy is a function: dict -> list[dict].
4
+ Given a single event, the strategy returns one or more rows
5
+ depending on whether the event spans multiple months.
6
+
7
+ Adding a new strategy means adding a function here with the
8
+ @_registry.decorator — no changes to the builder (OCP).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ import math
15
+ import re
16
+ import warnings
17
+ from collections.abc import Callable
18
+
19
+ from datafactory_provenance.registry import Registry
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ _registry: Registry[Callable[[dict], list[dict]]] = Registry(
24
+ "distribution strategy"
25
+ )
26
+
27
+ __all__ = [
28
+ "get_distribution",
29
+ "date_end_only",
30
+ "even_split",
31
+ "ceil_split",
32
+ "floor_split",
33
+ "source_aware",
34
+ ]
35
+
36
+ _SUMMARY_DATE_PREC: int = 5 # date_prec value indicating multi-month span
37
+ _DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
38
+
39
+
40
+ def _validate_date_str(date_str: str) -> str:
41
+ """Validate date string is strictly YYYY-MM-DD.
42
+
43
+ Raises:
44
+ ValueError: For non-conforming strings (e.g., ISO datetime,
45
+ slash-separated, missing leading zeros).
46
+ """
47
+ if not _DATE_RE.match(date_str):
48
+ err_msg = (
49
+ f"Expected YYYY-MM-DD date format, got {date_str!r}"
50
+ )
51
+ raise ValueError(err_msg)
52
+ return date_str
53
+
54
+
55
+ def get_distribution(name: str) -> Callable[[dict], list[dict]]:
56
+ """Look up a temporal distribution strategy by name.
57
+
58
+ Raises:
59
+ KeyError: If the strategy name is not registered.
60
+ """
61
+ return _registry.get(name)
62
+
63
+
64
+ def _month_first_day(date_str: str) -> str:
65
+ """Extract the first day of the month from a YYYY-MM-DD string.
66
+
67
+ Example: "2023-03-15" → "2023-03-01"
68
+ """
69
+ _validate_date_str(date_str)
70
+ parts = date_str.split("-")
71
+ return f"{parts[0]}-{parts[1]}-01"
72
+
73
+
74
+ def _months_between(start_str: str, end_str: str) -> list[str]:
75
+ """Generate first-of-month strings between two dates (inclusive).
76
+
77
+ Example: "2023-01-15" to "2023-03-31" → ["2023-01-01",
78
+ "2023-02-01", "2023-03-01"]
79
+ """
80
+ _validate_date_str(start_str)
81
+ _validate_date_str(end_str)
82
+ start_parts = start_str.split("-")
83
+ end_parts = end_str.split("-")
84
+
85
+ start_year = int(start_parts[0])
86
+ start_month = int(start_parts[1])
87
+ end_year = int(end_parts[0])
88
+ end_month = int(end_parts[1])
89
+
90
+ months: list[str] = []
91
+ year, month = start_year, start_month
92
+ while (year, month) <= (end_year, end_month):
93
+ months.append(f"{year}-{month:02d}-01")
94
+ month += 1
95
+ if month > 12:
96
+ month = 1
97
+ year += 1
98
+
99
+ return months
100
+
101
+
102
+ @_registry.decorator("date_end_only")
103
+ def date_end_only(event: dict) -> list[dict]:
104
+ """Assign all events to their date_end month. No distribution.
105
+
106
+ Matches VIEWSER GedLoader behavior when fix_summary_events
107
+ is not enabled. Every event produces exactly one output row
108
+ with date_month derived from date_end, regardless of whether
109
+ the event spans multiple months.
110
+ """
111
+ date_end = event.get("date_end") or event.get("date_start")
112
+ return [{**event, "date_month": _month_first_day(str(date_end))}]
113
+
114
+
115
+ @_registry.decorator("even_split")
116
+ def even_split(event: dict) -> list[dict]:
117
+ """Distribute summary events evenly across spanned months.
118
+
119
+ For date_prec=5 events: divides best/low/high evenly across
120
+ months from date_start to date_end (inclusive). Each output
121
+ row gets a date_month field.
122
+
123
+ For all other events: returns a single row with date_month
124
+ derived from date_end (matching production GedLoader behavior).
125
+ """
126
+ date_prec = event.get("date_prec")
127
+ date_end = event.get("date_end") or event.get("date_start")
128
+
129
+ if date_prec != _SUMMARY_DATE_PREC:
130
+ # Non-summary: single row, month from date_end
131
+ row = {**event, "date_month": _month_first_day(str(date_end))}
132
+ return [row]
133
+
134
+ # Summary event: distribute across months
135
+ date_start = event.get("date_start")
136
+ if not date_start or not date_end:
137
+ err_msg = (
138
+ f"Summary event (date_prec=5) missing date_start or "
139
+ f"date_end: id={event.get('id')}"
140
+ )
141
+ logger.error(err_msg)
142
+ raise ValueError(err_msg)
143
+
144
+ months = _months_between(date_start, date_end)
145
+ if not months:
146
+ err_msg = (
147
+ f"Summary event spans zero months: "
148
+ f"date_start={date_start}, date_end={date_end}"
149
+ )
150
+ logger.error(err_msg)
151
+ raise ValueError(err_msg)
152
+
153
+ n_months = len(months)
154
+ best = (event.get("best") or 0) / n_months
155
+ low = (event.get("low") or 0) / n_months
156
+ high = (event.get("high") or 0) / n_months
157
+
158
+ rows: list[dict] = []
159
+ for month_str in months:
160
+ row = {
161
+ **event,
162
+ "best": best,
163
+ "low": low,
164
+ "high": high,
165
+ "date_month": month_str,
166
+ }
167
+ rows.append(row)
168
+
169
+ return rows
170
+
171
+
172
+ def _split_summary(
173
+ event: dict,
174
+ rounding_fn: Callable[[float], float],
175
+ ) -> list[dict]:
176
+ """Shared detection + distribution for summary events.
177
+
178
+ Detection (ADR-023 invariant): event is summary if best > 0,
179
+ spans > 1 month, AND best >= span. Non-summary events produce
180
+ a single row with date_month from date_end.
181
+
182
+ Summary events are expanded to one row per spanned month, with
183
+ fatalities divided by the rounding function (ceil or floor).
184
+ """
185
+ date_end = event.get("date_end") or event.get("date_start")
186
+ date_start = event.get("date_start")
187
+ best = event.get("best") or 0
188
+
189
+ if date_start and date_end:
190
+ months = _months_between(date_start, date_end)
191
+ summary_period = len(months)
192
+ else:
193
+ summary_period = 1
194
+ months = []
195
+
196
+ is_summary = (
197
+ best > 0
198
+ and summary_period > 1
199
+ and best >= summary_period
200
+ )
201
+
202
+ if not is_summary:
203
+ row = {
204
+ **event,
205
+ "date_month": _month_first_day(str(date_end)),
206
+ }
207
+ return [row]
208
+
209
+ if not months:
210
+ err_msg = (
211
+ f"Summary event has no month span: "
212
+ f"date_start={date_start}, date_end={date_end}"
213
+ )
214
+ logger.error(err_msg)
215
+ raise ValueError(err_msg)
216
+
217
+ low = event.get("low") or 0
218
+ high = event.get("high") or 0
219
+ r_best = int(rounding_fn(best / summary_period))
220
+ r_low = int(rounding_fn(low / summary_period))
221
+ r_high = int(rounding_fn(high / summary_period))
222
+
223
+ rows: list[dict] = []
224
+ for month_str in months:
225
+ row = {
226
+ **event,
227
+ "best": r_best,
228
+ "low": r_low,
229
+ "high": r_high,
230
+ "date_month": month_str,
231
+ }
232
+ rows.append(row)
233
+
234
+ return rows
235
+
236
+
237
+ @_registry.decorator("ceil_split")
238
+ def ceil_split(event: dict) -> list[dict]:
239
+ """Production-parity summary event distribution.
240
+
241
+ Matches the production GedLoader's fix_summary_events logic:
242
+
243
+ Detection: event is summary if best > 0, spans > 1 month,
244
+ AND best >= span (enough fatalities for at least 1 per month).
245
+ This differs from even_split which uses date_prec == 5.
246
+
247
+ Distribution: ceil(fatalities / span) — rounds up to ensure
248
+ every month gets at least 1 fatality. This may inflate totals
249
+ (e.g., best=7 over 3 months → 3+3+3=9, not 7).
250
+
251
+ Non-summary events get date_month from date_end.
252
+ """
253
+ return _split_summary(event, math.ceil)
254
+
255
+
256
+ @_registry.decorator("floor_split")
257
+ def floor_split(event: dict) -> list[dict]:
258
+ """Summary event distribution with floor rounding.
259
+
260
+ Same detection logic as ceil_split but uses
261
+ floor(fatalities / span). Matches older VIEWSER .9 loader
262
+ versions (pre-v25.9.11).
263
+
264
+ Non-summary events get date_month from date_end.
265
+ """
266
+ return _split_summary(event, math.floor)
267
+
268
+
269
+ @_registry.decorator("source_aware")
270
+ def source_aware(event: dict) -> list[dict]:
271
+ """Source-type-aware distribution matching VIEWSER behavior.
272
+
273
+ .. deprecated::
274
+ Use ``source_distribution_map={"annual": "date_end_only"}``
275
+ with ``distribution_strategy="ceil_split"`` in
276
+ ViewpointConfig instead.
277
+
278
+ VIEWSER loads data sources sequentially with different settings:
279
+ - Annual loader: fix_summary_events=False → date_end_only
280
+ - .9 / candidate loader: fix_summary_events=True → ceil_split
281
+
282
+ This composite strategy reads _source_type from the event and
283
+ delegates to the appropriate strategy.
284
+ """
285
+ warnings.warn(
286
+ "source_aware strategy is deprecated; use "
287
+ "source_distribution_map={'annual': 'date_end_only'} "
288
+ "with distribution_strategy='ceil_split' instead.",
289
+ DeprecationWarning,
290
+ stacklevel=2,
291
+ )
292
+ source_type = event.get("_source_type", "")
293
+ if source_type == "annual":
294
+ return date_end_only(event)
295
+ return ceil_split(event)
@@ -0,0 +1,124 @@
1
+ """Viewpoint configuration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+ from datafactory_viewpoint.spatial_distribution import (
10
+ get_spatial_distribution,
11
+ )
12
+ from datafactory_viewpoint.survivorship import get_survivorship
13
+ from datafactory_viewpoint.temporal_distribution import (
14
+ get_distribution,
15
+ )
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class ViewpointConfig:
22
+ """Configuration for building a viewpoint from a consolidated store.
23
+
24
+ Declares which survivorship and distribution strategies to apply,
25
+ the version tag, and I/O paths. Strategy names are validated
26
+ against the strategy registries at config time.
27
+
28
+ consolidated_path existence is checked at build time, not config
29
+ time (the file may not exist yet).
30
+ """
31
+
32
+ # Input
33
+ consolidated_path: Path
34
+
35
+ # Output
36
+ output_path: Path = Path("data/viewpoint/ucdp_v1.parquet")
37
+ ledger_path: Path = Path(
38
+ "provenance/viewpoint/ucdp_v1_ledger.jsonl"
39
+ )
40
+
41
+ # Strategy selection
42
+ survivorship_strategy: str = "annual_wins"
43
+ distribution_strategy: str = "even_split"
44
+ spatial_distribution_strategy: str = "proportional"
45
+
46
+ # GAUL crosswalk paths for spatial distribution
47
+ gaul1_crosswalk_path: Path = Path(
48
+ "data/raw/gaul_admin/gaul1_code.parquet"
49
+ )
50
+ gaul0_crosswalk_path: Path = Path(
51
+ "data/raw/gaul_admin/gaul0_code.parquet"
52
+ )
53
+
54
+ # Pre-processing
55
+ filter_stale_versions: bool = True
56
+
57
+ # Per-source-type distribution overrides.
58
+ # Keys: source type strings ("annual", "dot9", "candidate").
59
+ # Values: registered distribution strategy names.
60
+ # When None, distribution_strategy applies uniformly.
61
+ source_distribution_map: dict[str, str] | None = None
62
+
63
+ # Filtering (applied after survivorship + distribution)
64
+ # None means no filter; profiles set values for production parity
65
+ min_priogrid_gid: int | None = None
66
+ max_type_of_violence: int | None = None
67
+ exclude_where_prec: tuple[int, ...] = ()
68
+
69
+ # Version tag for provenance (set by profile or caller)
70
+ version: str = "custom"
71
+
72
+ def __post_init__(self) -> None:
73
+ if not self.version:
74
+ err_msg = "version must be non-empty"
75
+ logger.error(err_msg)
76
+ raise ValueError(err_msg)
77
+ try:
78
+ get_survivorship(self.survivorship_strategy)
79
+ except KeyError as exc:
80
+ err_msg = (
81
+ f"Unknown survivorship strategy: "
82
+ f"'{self.survivorship_strategy}'"
83
+ )
84
+ logger.error(err_msg)
85
+ raise ValueError(err_msg) from exc
86
+ try:
87
+ get_distribution(self.distribution_strategy)
88
+ except KeyError as exc:
89
+ err_msg = (
90
+ f"Unknown distribution strategy: "
91
+ f"'{self.distribution_strategy}'"
92
+ )
93
+ logger.error(err_msg)
94
+ raise ValueError(err_msg) from exc
95
+ try:
96
+ get_spatial_distribution(
97
+ self.spatial_distribution_strategy,
98
+ )
99
+ except KeyError as exc:
100
+ err_msg = (
101
+ f"Unknown spatial distribution strategy: "
102
+ f"'{self.spatial_distribution_strategy}'"
103
+ )
104
+ logger.error(err_msg)
105
+ raise ValueError(err_msg) from exc
106
+ if self.source_distribution_map is not None:
107
+ for src, strat in self.source_distribution_map.items():
108
+ try:
109
+ get_distribution(strat)
110
+ except KeyError as exc:
111
+ err_msg = (
112
+ f"Unknown distribution strategy "
113
+ f"'{strat}' for source type "
114
+ f"'{src}' in source_distribution_map"
115
+ )
116
+ logger.error(err_msg)
117
+ raise ValueError(err_msg) from exc
118
+
119
+ @classmethod
120
+ def from_shortcuts(
121
+ cls, *, consolidated_path: Path,
122
+ ) -> ViewpointConfig:
123
+ """Construct config from minimal shortcut arguments."""
124
+ return cls(consolidated_path=consolidated_path)
@@ -0,0 +1,33 @@
1
+ """Structured result from a viewpoint build operation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class ViewpointResult:
11
+ """Immutable result of a viewpoint build.
12
+
13
+ Attributes:
14
+ output_path: Path to the viewpoint Parquet.
15
+ n_events_input: Events in the consolidated store.
16
+ n_events_output: Rows in the viewpoint output (may differ
17
+ due to survivorship dedup and summary event expansion).
18
+ n_summary_expanded: Summary events that were expanded.
19
+ n_spatially_distributed: Events spatially distributed
20
+ across polygon cells (ADR-049).
21
+ n_filtered: Events removed by filters.
22
+ output_digest: SHA-256 content digest of the output file.
23
+ version: Viewpoint version tag from config.
24
+ """
25
+
26
+ output_path: Path
27
+ n_events_input: int
28
+ n_events_output: int
29
+ n_summary_expanded: int
30
+ n_spatially_distributed: int
31
+ n_filtered: int
32
+ output_digest: str
33
+ version: str