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,466 @@
1
+ """Source registry — single source of truth for pipeline sources.
2
+
3
+ Every data source in the pipeline is declared here as a SourceEntry.
4
+ Consumers (health checks, pre-flight validation, assembly, remote
5
+ verification) import from this module instead of maintaining their
6
+ own hardcoded lists. Adding or removing a source is a one-entry
7
+ change. ADR-003 (declarations over inference), ADR-009 (boundary
8
+ contracts).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+
17
+ __all__ = [
18
+ "PIPELINE_SOURCES",
19
+ "SourceEntry",
20
+ "get_all_features",
21
+ "get_feature_agg_type_map",
22
+ "get_required_env_vars",
23
+ "get_source_slo",
24
+ "validate_preflight",
25
+ ]
26
+
27
+ _VALID_AGG_TYPES = frozenset({"extensive", "intensive", "static"})
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class SourceEntry:
32
+ """A declared pipeline data source.
33
+
34
+ Fields
35
+ ------
36
+ name : str
37
+ Human-readable source name (must be unique across the registry).
38
+ required_env_vars : tuple[str, ...]
39
+ Environment variables that must be set for this source to run.
40
+ features : tuple[str, ...]
41
+ Feature names this source contributes to the assembled grid.
42
+ Empty for sources that don't produce grid features directly
43
+ (e.g. downstream layers like Consolidation).
44
+ slo_hours : int | None
45
+ Maximum acceptable age in hours before data is stale.
46
+ None means static (never stale from age alone).
47
+ ledger_path : Path | None
48
+ Path to the provenance ledger relative to the provenance
49
+ root directory (e.g. ``ucdp_annual/ingestion_ledger.jsonl``,
50
+ not ``provenance/ucdp_annual/...``). Health scripts prepend
51
+ their ``--provenance-dir`` argument.
52
+ """
53
+
54
+ name: str
55
+ required_env_vars: tuple[str, ...] = ()
56
+ features: tuple[str, ...] = ()
57
+ feature_agg_types: tuple[str, ...] = ()
58
+ slo_hours: int | None = None
59
+ ledger_path: Path | None = None
60
+
61
+ def __post_init__(self) -> None:
62
+ if not self.name:
63
+ msg = "SourceEntry.name must be non-empty"
64
+ raise ValueError(msg)
65
+ for var in self.required_env_vars:
66
+ if not var:
67
+ msg = "required_env_vars must not contain empty strings"
68
+ raise ValueError(msg)
69
+ for feat in self.features:
70
+ if not feat:
71
+ msg = "features must not contain empty strings"
72
+ raise ValueError(msg)
73
+ if len(self.feature_agg_types) != len(self.features):
74
+ msg = (
75
+ f"feature_agg_types length ({len(self.feature_agg_types)}) "
76
+ f"must match features length ({len(self.features)})"
77
+ )
78
+ raise ValueError(msg)
79
+ for agg_type in self.feature_agg_types:
80
+ if agg_type not in _VALID_AGG_TYPES:
81
+ msg = (
82
+ f"invalid feature_agg_type {agg_type!r}, "
83
+ f"must be one of {sorted(_VALID_AGG_TYPES)}"
84
+ )
85
+ raise ValueError(msg)
86
+ if self.slo_hours is not None and self.slo_hours <= 0:
87
+ msg = f"slo_hours must be positive, got {self.slo_hours}"
88
+ raise ValueError(msg)
89
+
90
+
91
+ PIPELINE_SOURCES: tuple[SourceEntry, ...] = (
92
+ # ── Harvest layer (raw data ingestion) ──
93
+ SourceEntry(
94
+ name="UCDP Annual",
95
+ required_env_vars=("UCDP_API_TOKEN",),
96
+ features=(
97
+ "ged_sb_count", "ged_sb_best",
98
+ "ged_ns_count", "ged_ns_best",
99
+ "ged_os_count", "ged_os_best",
100
+ ),
101
+ feature_agg_types=(
102
+ "extensive", "extensive",
103
+ "extensive", "extensive",
104
+ "extensive", "extensive",
105
+ ),
106
+ slo_hours=8760,
107
+ ledger_path=Path(
108
+ "ucdp_annual/ingestion_ledger.jsonl"
109
+ ),
110
+ ),
111
+ SourceEntry(
112
+ name="UCDP Candidate",
113
+ required_env_vars=("UCDP_API_TOKEN",),
114
+ slo_hours=744,
115
+ ledger_path=Path(
116
+ "ucdp_candidate/ingestion_ledger.jsonl"
117
+ ),
118
+ ),
119
+ SourceEntry(
120
+ name="UCDP .9",
121
+ required_env_vars=("UCDP_API_TOKEN",),
122
+ slo_hours=744,
123
+ ledger_path=Path(
124
+ "ucdp_dot9/ingestion_ledger.jsonl"
125
+ ),
126
+ ),
127
+ SourceEntry(
128
+ name="ACLED",
129
+ required_env_vars=("ACLED_USERNAME", "ACLED_PASSWORD"),
130
+ features=(
131
+ "acled_count", "acled_battles",
132
+ "acled_explosions", "acled_vac",
133
+ "acled_protests", "acled_riots",
134
+ "acled_strategic", "acled_fatalities",
135
+ ),
136
+ feature_agg_types=(
137
+ "extensive", "extensive",
138
+ "extensive", "extensive",
139
+ "extensive", "extensive",
140
+ "extensive", "extensive",
141
+ ),
142
+ slo_hours=744,
143
+ ledger_path=Path(
144
+ "acled/ingestion_ledger.jsonl"
145
+ ),
146
+ ),
147
+ SourceEntry(
148
+ name="GHS-POP",
149
+ features=(
150
+ "ghspop_pop_count",
151
+ ),
152
+ feature_agg_types=(
153
+ "extensive",
154
+ ),
155
+ slo_hours=None,
156
+ ledger_path=Path(
157
+ "ghspop/ingestion_ledger.jsonl"
158
+ ),
159
+ ),
160
+ SourceEntry(
161
+ name="GHS-BUILT-S",
162
+ features=(
163
+ "ghsbuilts_built_area",
164
+ ),
165
+ feature_agg_types=(
166
+ "intensive",
167
+ ),
168
+ slo_hours=None,
169
+ ledger_path=Path(
170
+ "ghsbuilts/ingestion_ledger.jsonl"
171
+ ),
172
+ ),
173
+ SourceEntry(
174
+ name="PRIO-GRID Static",
175
+ features=(
176
+ "agri_gc", "aquaveg_gc", "barren_gc",
177
+ "cmr_max", "cmr_mean", "cmr_min", "cmr_sd",
178
+ "diamprim_s", "diamsec_s",
179
+ "forest_gc", "gem_s",
180
+ "goldplacer_s", "goldsurface_s", "goldvein_s",
181
+ "growend", "growstart", "harvarea",
182
+ "herb_gc",
183
+ "imr_max", "imr_mean", "imr_min", "imr_sd",
184
+ "landarea", "maincrop", "mountains_mean",
185
+ "petroleum_s", "rainseas",
186
+ "shrub_gc",
187
+ "ttime_max", "ttime_mean", "ttime_min", "ttime_sd",
188
+ "urban_gc", "water_gc",
189
+ ),
190
+ feature_agg_types=(
191
+ "static", "static", "static",
192
+ "static", "static", "static", "static",
193
+ "static", "static",
194
+ "static", "static",
195
+ "static", "static", "static",
196
+ "static", "static", "static",
197
+ "static",
198
+ "static", "static", "static", "static",
199
+ "static", "static", "static",
200
+ "static", "static",
201
+ "static",
202
+ "static", "static", "static", "static",
203
+ "static", "static",
204
+ ),
205
+ slo_hours=None,
206
+ ledger_path=Path(
207
+ "priogrid_static/ingestion_ledger.jsonl"
208
+ ),
209
+ ),
210
+ SourceEntry(
211
+ name="V-Dem",
212
+ features=(
213
+ "vdem_v2xcl_dmove",
214
+ "vdem_v2xeg_eqdr",
215
+ "vdem_v2xpe_exlsocgr",
216
+ "vdem_v2x_clphy",
217
+ "vdem_v2xcl_prpty",
218
+ "vdem_v2x_ex_military",
219
+ "vdem_v2x_ex_party",
220
+ "vdem_v2x_horacc",
221
+ "vdem_v2xnp_client",
222
+ "vdem_v2xnp_regcorr",
223
+ "vdem_v2xpe_exlgeo",
224
+ "vdem_v2x_veracc",
225
+ "vdem_v2xpe_exlpol",
226
+ "vdem_v2x_diagacc",
227
+ "vdem_v2x_divparctrl",
228
+ "vdem_v2xeg_eqprotec",
229
+ "vdem_v2x_genpp",
230
+ "vdem_v2xpe_exlgender",
231
+ "vdem_v2x_hosabort",
232
+ "vdem_v2x_libdem",
233
+ "vdem_v2xcl_rol",
234
+ "vdem_v2x_accountability",
235
+ ),
236
+ feature_agg_types=(
237
+ "intensive", "intensive", "intensive",
238
+ "intensive", "intensive", "intensive",
239
+ "intensive", "intensive", "intensive",
240
+ "intensive", "intensive", "intensive",
241
+ "intensive", "intensive", "intensive",
242
+ "intensive", "intensive", "intensive",
243
+ "intensive", "intensive", "intensive",
244
+ "intensive",
245
+ ),
246
+ slo_hours=None,
247
+ ledger_path=Path(
248
+ "vdem/ingestion_ledger.jsonl"
249
+ ),
250
+ ),
251
+ SourceEntry(
252
+ name="SHDI",
253
+ required_env_vars=("GDL_API_TOKEN",),
254
+ features=(
255
+ "shdi_shdi", "shdi_healthindex",
256
+ "shdi_edindex", "shdi_incindex",
257
+ ),
258
+ feature_agg_types=(
259
+ "intensive", "intensive",
260
+ "intensive", "intensive",
261
+ ),
262
+ slo_hours=None,
263
+ ledger_path=Path(
264
+ "shdi/ingestion_ledger.jsonl"
265
+ ),
266
+ ),
267
+ SourceEntry(
268
+ name="PRIO-GRID Shapefile",
269
+ slo_hours=None,
270
+ ledger_path=Path(
271
+ "priogrid/ingestion_ledger.jsonl"
272
+ ),
273
+ ),
274
+ SourceEntry(
275
+ name="GAUL Admin",
276
+ features=(
277
+ "gaul0_code", "gaul1_code", "gaul2_code",
278
+ ),
279
+ feature_agg_types=(
280
+ "static", "static", "static",
281
+ ),
282
+ slo_hours=None,
283
+ # No ledger_path: GAUL admin boundaries are static shapefiles
284
+ # read directly by assemble_grid.py, not harvested via a
285
+ # provenance-tracked ingestion pipeline.
286
+ ),
287
+ # ── Downstream layers ──
288
+ SourceEntry(
289
+ name="Consolidation",
290
+ slo_hours=744,
291
+ ledger_path=Path(
292
+ "consolidation/ledger.jsonl"
293
+ ),
294
+ ),
295
+ SourceEntry(
296
+ name="ACLED Consolidation",
297
+ slo_hours=744,
298
+ ledger_path=Path(
299
+ "consolidation/acled_ledger.jsonl"
300
+ ),
301
+ ),
302
+ SourceEntry(
303
+ name="Viewpoint",
304
+ slo_hours=744,
305
+ ledger_path=Path(
306
+ "viewpoint/ledger.jsonl"
307
+ ),
308
+ ),
309
+ SourceEntry(
310
+ name="ACLED Viewpoint",
311
+ slo_hours=744,
312
+ ledger_path=Path(
313
+ "viewpoint/acled_v1_ledger.jsonl"
314
+ ),
315
+ ),
316
+ SourceEntry(
317
+ name="GHS-POP Viewpoint",
318
+ slo_hours=None,
319
+ ledger_path=Path(
320
+ "viewpoint/ghspop_v1_ledger.jsonl"
321
+ ),
322
+ ),
323
+ SourceEntry(
324
+ name="GHS-BUILT-S Viewpoint",
325
+ slo_hours=None,
326
+ ledger_path=Path(
327
+ "viewpoint/ghsbuilts_v1_ledger.jsonl"
328
+ ),
329
+ ),
330
+ SourceEntry(
331
+ name="V-Dem Viewpoint",
332
+ slo_hours=None,
333
+ ledger_path=Path(
334
+ "viewpoint/vdem_v1_ledger.jsonl"
335
+ ),
336
+ ),
337
+ SourceEntry(
338
+ name="SHDI Viewpoint",
339
+ slo_hours=None,
340
+ ledger_path=Path(
341
+ "viewpoint/shdi_v1_ledger.jsonl"
342
+ ),
343
+ ),
344
+ SourceEntry(
345
+ name="Compilation",
346
+ slo_hours=744,
347
+ ledger_path=Path(
348
+ "compilation/ledger.jsonl"
349
+ ),
350
+ ),
351
+ SourceEntry(
352
+ name="ACLED Compilation",
353
+ slo_hours=744,
354
+ ledger_path=Path(
355
+ "compilation/acled_ledger.jsonl"
356
+ ),
357
+ ),
358
+ SourceEntry(
359
+ name="GHS-POP Compilation",
360
+ slo_hours=None,
361
+ ledger_path=Path(
362
+ "compilation/ghspop_ledger.jsonl"
363
+ ),
364
+ ),
365
+ SourceEntry(
366
+ name="GHS-BUILT-S Compilation",
367
+ slo_hours=None,
368
+ ledger_path=Path(
369
+ "compilation/ghsbuilts_ledger.jsonl"
370
+ ),
371
+ ),
372
+ SourceEntry(
373
+ name="V-Dem Compilation",
374
+ slo_hours=None,
375
+ ledger_path=Path(
376
+ "compilation/vdem_ledger.jsonl"
377
+ ),
378
+ ),
379
+ SourceEntry(
380
+ name="SHDI Compilation",
381
+ slo_hours=None,
382
+ ledger_path=Path(
383
+ "compilation/shdi_ledger.jsonl"
384
+ ),
385
+ ),
386
+ )
387
+
388
+
389
+ def get_source_slo(
390
+ sources: tuple[SourceEntry, ...] = PIPELINE_SOURCES,
391
+ ) -> dict[str, int | None]:
392
+ """Build name → SLO-hours mapping from the registry."""
393
+ return {s.name: s.slo_hours for s in sources}
394
+
395
+
396
+ def get_all_features(
397
+ sources: tuple[SourceEntry, ...] = PIPELINE_SOURCES,
398
+ ) -> tuple[str, ...]:
399
+ """Ordered feature tuple from all sources that declare features."""
400
+ result: list[str] = []
401
+ for s in sources:
402
+ result.extend(s.features)
403
+ return tuple(result)
404
+
405
+
406
+ def get_feature_agg_type_map(
407
+ sources: tuple[SourceEntry, ...] = PIPELINE_SOURCES,
408
+ ) -> dict[str, str]:
409
+ """Build feature_name → agg_type mapping from the registry."""
410
+ result: dict[str, str] = {}
411
+ for s in sources:
412
+ for feat, agg_type in zip(
413
+ s.features, s.feature_agg_types, strict=True,
414
+ ):
415
+ result[feat] = agg_type
416
+ return result
417
+
418
+
419
+ def get_required_env_vars(
420
+ sources: tuple[SourceEntry, ...] = PIPELINE_SOURCES,
421
+ ) -> set[str]:
422
+ """Union of all required environment variables."""
423
+ result: set[str] = set()
424
+ for s in sources:
425
+ result.update(s.required_env_vars)
426
+ return result
427
+
428
+
429
+ def validate_preflight(
430
+ sources: tuple[SourceEntry, ...] = PIPELINE_SOURCES,
431
+ ) -> list[dict[str, str]]:
432
+ """Validate all source prerequisites.
433
+
434
+ Checks that required environment variables are set and non-empty.
435
+ Returns a list of {name, source, status, detail} dicts. Status
436
+ is "OK" or "FAIL". The ``source`` field names the first
437
+ SourceEntry that requires this variable.
438
+ """
439
+ results: list[dict[str, str]] = []
440
+ seen_vars: set[str] = set()
441
+
442
+ for source in sources:
443
+ for var in source.required_env_vars:
444
+ if var in seen_vars:
445
+ continue
446
+ seen_vars.add(var)
447
+ value = os.environ.get(var, "")
448
+ if value:
449
+ results.append({
450
+ "name": var,
451
+ "source": source.name,
452
+ "status": "OK",
453
+ "detail": "set",
454
+ })
455
+ else:
456
+ results.append({
457
+ "name": var,
458
+ "source": source.name,
459
+ "status": "FAIL",
460
+ "detail": (
461
+ f"not set — add to ~/.profile: "
462
+ f"export {var}=\"...\""
463
+ ),
464
+ })
465
+
466
+ return results
@@ -0,0 +1,60 @@
1
+ # datafactory_query -- Architecture
2
+
3
+ ## Purpose
4
+
5
+ Consumer-facing query layer -- the primary entry point for training scripts and downstream consumers. Provides temporal subsetting, geographic filtering, and feature selection over assembled grids, returning data as FeatureFrame or DataFrame. Supports both local npy directories and remote zarr stores (HTTP with netrc auth). This package sits alongside the graph, not inside it: it reads assembled output as files and imports from priogrid + adapters.
6
+
7
+ ## Responsibility Boundary
8
+
9
+ **Owns:**
10
+ - `load_dataset()` — unified consumer entry point with region, time, feature, and format parameters
11
+ - Region resolution — mapping region names ("Ethiopia", "africa_me", "land") to PRIO-GRID cell sets via GAUL Parquets
12
+ - Temporal parsing — flexible input (ISO strings, VIEWS month_ids, years) to datetime64[M] ranges
13
+ - Dual backend selection — npy (local, mmap) vs zarr (local or remote via fsspec/xarray)
14
+ - Lazy subsetting for zarr — time and feature slices applied before materializing, avoiding full-grid downloads
15
+ - Credential resolution — reading ~/.netrc for authenticated remote zarr access
16
+
17
+ **Does NOT own:**
18
+ - Grid compilation or event placement (datafactory_compilation)
19
+ - Grid assembly (scripts/assemble_grid.py)
20
+ - Viewpoint building or survivorship rules (datafactory_viewpoint)
21
+ - Data harvesting (datafactory_harvester)
22
+ - Consumer vocabulary translation (scripts/generate_consumer_data.py)
23
+
24
+ ## Dependency Rules
25
+
26
+ **May import:** `datafactory_priogrid` (for GridConfig defaults), `datafactory_adapters` (for FeatureFrame, grid_to_dataframe, grid_to_feature_frame)
27
+ **Reads filesystem output of:** `scripts/assemble_grid.py` (assembled grid at `data/assembled/` or zarr store)
28
+ **Must never import:** `datafactory_harvester`, `datafactory_consolidation`, `datafactory_viewpoint`, `datafactory_compilation`
29
+
30
+ ## Package Structure
31
+
32
+ ```
33
+ datafactory_query/
34
+ __init__.py -- public API: load_dataset, list_regions, load_region_pgids, parse_time_range
35
+ dataset.py -- load_dataset (main function), dual npy/zarr backend, format conversion
36
+ regions.py -- region name → set of PRIO-GRID cell IDs (via GAUL Parquets)
37
+ temporal.py -- flexible time parsing: ISO, month_id, year → datetime64[M] range
38
+ ```
39
+
40
+ ## Key Concepts
41
+
42
+ | Concept | Description |
43
+ |---------|-------------|
44
+ | `load_dataset()` | Unified entry point. Accepts region, time range, feature list, output format, and data path (npy dir or zarr URL). Returns FeatureFrame or DataFrame. |
45
+ | Dual backend | npy path loads via `np.load(mmap_mode="r")` (zero-copy, local only). Zarr path uses `xarray.open_zarr()` with lazy slicing (supports remote HTTP). Backend selected automatically by path suffix. |
46
+ | Region resolution | Predefined regions ("africa_me", "americas", "europe", "asia_oceania") plus any GAUL country name. Resolution uses GAUL Level 0/1/2 Parquet files to map names to PRIO-GRID cell sets. Cached after first load. |
47
+ | VIEWS month_id | Integer encoding: `(year - epoch) * 12 + month`. Default epoch is 1980. Temporal parsing accepts month_ids as integers alongside ISO date strings. |
48
+
49
+ ## Invariants
50
+
51
+ - **Read-only:** Never modifies source data. All subsetting produces new arrays.
52
+ - **Lazy zarr subsetting:** For remote stores, time and feature slices are applied on the xarray Dataset before materializing. Only the requested subset is downloaded.
53
+ - **Fail-loud on missing data:** Raises `FileNotFoundError` if assembled grid or zarr store is not found. Raises `ValueError` for unknown features or invalid regions.
54
+ - **Format validation:** Only "feature_frame" and "dataframe" are valid output formats. Invalid format raises `ValueError`.
55
+ - **Credential warning:** If ~/.netrc lacks credentials for a remote zarr host, logs a warning before attempting unauthenticated access (may fail with 401).
56
+ - **Feature ordering (C-127):** The npy backend returns features in `feature_names.json` order. The zarr backend uses the `feature_order` dataset attribute if present; otherwise falls back to alphabetical (`sorted(ds.data_vars)`). Consumers must access features by name, not by position index. The zarr export should write `feature_order` to ensure backend parity.
57
+
58
+ ## Intent Contracts
59
+
60
+ - None yet — this package has no frozen config dataclass requiring a CIC.
@@ -0,0 +1,36 @@
1
+ """Data access for training consumers.
2
+
3
+ Provides temporal + geographic subsetting of the assembled grid
4
+ in multiple output formats (FeatureFrame, DataFrame). Sits
5
+ downstream in the DAG: imports from priogrid + adapters, reads
6
+ assembled output via filesystem.
7
+ """
8
+
9
+ from datafactory_query.dataset import load_dataset
10
+ from datafactory_query.defaults import (
11
+ DEFAULT_REMOTE,
12
+ PARTITIONS,
13
+ RemoteConfig,
14
+ get_last_valid_month_id,
15
+ )
16
+ from datafactory_query.output_format import (
17
+ CONTRACT_VERSION,
18
+ OutputFormat,
19
+ is_valid_output_format,
20
+ )
21
+ from datafactory_query.regions import list_regions, load_region_pgids
22
+ from datafactory_query.temporal import parse_time_range
23
+
24
+ __all__ = [
25
+ "CONTRACT_VERSION",
26
+ "DEFAULT_REMOTE",
27
+ "OutputFormat",
28
+ "PARTITIONS",
29
+ "RemoteConfig",
30
+ "get_last_valid_month_id",
31
+ "is_valid_output_format",
32
+ "list_regions",
33
+ "load_dataset",
34
+ "load_region_pgids",
35
+ "parse_time_range",
36
+ ]