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,54 @@
1
+ # datafactory_adapters -- Architecture
2
+
3
+ ## Purpose
4
+
5
+ Consumer-facing adapters that convert the datafactory's canonical output ([T, H, W, C] numpy arrays) into transport formats for downstream consumers. This module sits alongside the data graph (ADR-012), not inside it.
6
+
7
+ **Extractability note:** This module is designed to be moved to `views-pipeline-core` or a dedicated micro-service when the adapter pattern matures across the VIEWS platform. Dependencies are intentionally minimal (numpy, pandas, views-frames).
8
+
9
+ ## Responsibility Boundary
10
+
11
+ **Owns:**
12
+ - Grid array → DataFrame conversion (dense or sparse, configurable month_id encoding)
13
+ - Grid array → FeatureFrame conversion
14
+ - FeatureFrame re-export from views-frames v1.0 (analogous to PredictionFrame and EvaluationFrame)
15
+ - month_id encoding logic (configurable epoch)
16
+
17
+ **Does NOT own:**
18
+ - Grid array production (datafactory_compilation)
19
+ - Data fetching or consolidation (datafactory_harvester, datafactory_consolidation)
20
+ - Land mask computation (datafactory_priogrid)
21
+ - Consumer-specific transformations (feature engineering, normalization)
22
+
23
+ ## Dependency Rules
24
+
25
+ **May import:** numpy, pandas, views-frames
26
+ **Must never import:** Any `datafactory_*` package. This ensures clean extractability.
27
+
28
+ ## Package Structure
29
+
30
+ ```
31
+ datafactory_adapters/
32
+ __init__.py # Public API: FeatureFrame, grid_to_dataframe, grid_to_feature_frame
33
+ ARCHITECTURE.md # This file
34
+ _validation.py # Shared shape validation helpers
35
+ feature_frame.py # FeatureFrame re-export shim (views-frames v1.0)
36
+ grid_from_feature_frame.py # FeatureFrame → [T, H, W, F] grid reconstruction
37
+ grid_to_country_month.py # [T, H, W, C] → country-month DataFrame
38
+ grid_to_dataframe.py # [T, H, W, C] → DataFrame and FeatureFrame conversion
39
+ ```
40
+
41
+ ## Key Concepts
42
+
43
+ | Concept | Description |
44
+ |---------|-------------|
45
+ | FeatureFrame | Input-side transport object (re-exported from views-frames v1.0): values (N, D, S), SpatioTemporalIndex {time, unit, level}, feature_names. Analogous to PredictionFrame. |
46
+ | grid_to_dataframe | Converts [T, H, W, C] → pandas DataFrame with (month_id, priogrid_gid) MultiIndex. |
47
+ | grid_to_feature_frame | Converts [T, H, W, C] → FeatureFrame with dense land-cell time series. |
48
+ | month_id_epoch | Configurable base year for month_id encoding. 0 = raw, 1980 = VIEWS convention. |
49
+
50
+ ## Invariants
51
+
52
+ - FeatureFrame validates shape, required identifiers (time, unit), and feature_name count
53
+ - DataFrame output is sorted by index (month_id, priogrid_gid)
54
+ - No datafactory_* imports — extractability is a hard constraint
@@ -0,0 +1,38 @@
1
+ """Consumer-facing adapters for datafactory outputs.
2
+
3
+ Converts canonical [T, H, W, C] grid arrays to transport
4
+ formats: DataFrames, FeatureFrames, etc.
5
+
6
+ Designed to be extractable: this module may move to
7
+ views-pipeline-core or a dedicated micro-service when the
8
+ adapter pattern matures. Dependencies are minimal (numpy,
9
+ pandas, views-frames — no other datafactory_* imports).
10
+ """
11
+
12
+ from datafactory_adapters.feature_frame import (
13
+ FeatureFrame,
14
+ FrameMetadata,
15
+ SpatialLevel,
16
+ SpatioTemporalIndex,
17
+ )
18
+ from datafactory_adapters.grid_from_feature_frame import (
19
+ feature_frame_to_grid,
20
+ )
21
+ from datafactory_adapters.grid_to_country_month import (
22
+ grid_to_country_month,
23
+ )
24
+ from datafactory_adapters.grid_to_dataframe import (
25
+ grid_to_dataframe,
26
+ grid_to_feature_frame,
27
+ )
28
+
29
+ __all__ = [
30
+ "FeatureFrame",
31
+ "FrameMetadata",
32
+ "SpatialLevel",
33
+ "SpatioTemporalIndex",
34
+ "feature_frame_to_grid",
35
+ "grid_to_country_month",
36
+ "grid_to_dataframe",
37
+ "grid_to_feature_frame",
38
+ ]
@@ -0,0 +1,95 @@
1
+ """ADR-040 count conservation for the CM aggregation layer.
2
+
3
+ Invariant 1 at CM boundary: for extensive features (count/sum),
4
+ grid_total = land_total + excluded_total.
5
+
6
+ Extensive features are identified from the declared
7
+ feature_agg_types mapping (ADR-048), not from name prefixes.
8
+
9
+ Uses np.allclose for float32 sums (rounding tolerance).
10
+ Uses if/raise RuntimeError — assert is stripped with -O.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import numpy as np
16
+
17
+ __all__ = ["assert_cm_conservation", "assert_no_unexpected_nan"]
18
+
19
+
20
+ def _extensive_indices(
21
+ feature_names: list[str],
22
+ feature_agg_types: dict[str, str] | None,
23
+ ) -> list[int]:
24
+ """Return column indices of extensive features."""
25
+ if feature_agg_types is None:
26
+ return []
27
+ return [
28
+ i for i, f in enumerate(feature_names)
29
+ if feature_agg_types.get(f) == "extensive"
30
+ ]
31
+
32
+
33
+ def assert_no_unexpected_nan(
34
+ feature_names: list[str],
35
+ data: np.ndarray,
36
+ feature_agg_types: dict[str, str] | None = None,
37
+ label: str = "grid",
38
+ ) -> None:
39
+ """Raise if any extensive feature column contains NaN.
40
+
41
+ Extensive features (counts) should never be NaN in the assembled
42
+ grid. NaN in these columns indicates a bug, not missing data.
43
+ nansum would silently exclude these values, weakening the
44
+ conservation invariant (C-291).
45
+ """
46
+ indices = _extensive_indices(feature_names, feature_agg_types)
47
+ if not indices or data.size == 0:
48
+ return
49
+
50
+ for i in indices:
51
+ n_nan = int(np.isnan(data[:, i]).sum())
52
+ if n_nan > 0:
53
+ raise RuntimeError(
54
+ f"Unexpected NaN in extensive feature "
55
+ f"{feature_names[i]!r} ({label}): {n_nan} NaN values. "
56
+ f"Extensive features must not contain NaN — "
57
+ f"this indicates a data pipeline bug, not missing data."
58
+ )
59
+
60
+
61
+ def assert_cm_conservation(
62
+ feature_names: list[str],
63
+ flat_data_all: np.ndarray,
64
+ flat_data_land: np.ndarray,
65
+ excluded_data: np.ndarray,
66
+ feature_agg_types: dict[str, str] | None = None,
67
+ ) -> None:
68
+ """Verify grid_total = land_total + excluded_total for extensive features."""
69
+ indices = _extensive_indices(feature_names, feature_agg_types)
70
+ if not indices:
71
+ return
72
+
73
+ assert_no_unexpected_nan(
74
+ feature_names, flat_data_all, feature_agg_types, "all",
75
+ )
76
+ assert_no_unexpected_nan(
77
+ feature_names, flat_data_land, feature_agg_types, "land",
78
+ )
79
+ assert_no_unexpected_nan(
80
+ feature_names, excluded_data, feature_agg_types, "excluded",
81
+ )
82
+
83
+ for i in indices:
84
+ grid_total = float(np.nansum(flat_data_all[:, i], dtype=np.float64))
85
+ land_total = float(np.nansum(flat_data_land[:, i], dtype=np.float64))
86
+ excl_total = float(np.nansum(excluded_data[:, i], dtype=np.float64))
87
+ recon = land_total + excl_total
88
+
89
+ if not np.allclose(grid_total, recon, rtol=1e-6, atol=1e-4):
90
+ raise RuntimeError(
91
+ f"CM conservation violated (ADR-040) for "
92
+ f"{feature_names[i]!r}: grid_total={grid_total:.6f} != "
93
+ f"land_total={land_total:.6f} + "
94
+ f"excluded_total={excl_total:.6f} = {recon:.6f}"
95
+ )
@@ -0,0 +1,92 @@
1
+ """ADR-040 hierarchical reconciliation for the GAUL admin family.
2
+
3
+ Invariant 2: every L2 unit nests within exactly one L1, every L1
4
+ within exactly one L0. Summing extensive features by any level
5
+ produces identical totals.
6
+
7
+ Uses if/raise RuntimeError — assert is stripped with -O.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import numpy as np
13
+
14
+ __all__ = [
15
+ "assert_hierarchical_reconciliation",
16
+ "check_nesting",
17
+ ]
18
+
19
+
20
+ def check_nesting(
21
+ gaul0: np.ndarray,
22
+ gaul1: np.ndarray | None = None,
23
+ gaul2: np.ndarray | None = None,
24
+ ) -> list[str]:
25
+ """Return list of nesting violation descriptions (empty = clean)."""
26
+ violations: list[str] = []
27
+
28
+ if gaul1 is not None:
29
+ l1_to_l0: dict[int, int] = {}
30
+ for g1, g0 in zip(gaul1, gaul0, strict=True):
31
+ if g1 in l1_to_l0:
32
+ if l1_to_l0[g1] != g0:
33
+ violations.append(
34
+ f"L1={g1} maps to both L0={l1_to_l0[g1]} and L0={g0}"
35
+ )
36
+ else:
37
+ l1_to_l0[g1] = g0
38
+
39
+ if gaul1 is not None and gaul2 is not None:
40
+ l2_to_l1: dict[int, int] = {}
41
+ for g2, g1 in zip(gaul2, gaul1, strict=True):
42
+ if g2 in l2_to_l1:
43
+ if l2_to_l1[g2] != g1:
44
+ violations.append(
45
+ f"L2={g2} maps to both L1={l2_to_l1[g2]} and L1={g1}"
46
+ )
47
+ else:
48
+ l2_to_l1[g2] = g1
49
+
50
+ return violations
51
+
52
+
53
+ def assert_hierarchical_reconciliation(
54
+ gaul0: np.ndarray,
55
+ gaul1: np.ndarray | None = None,
56
+ gaul2: np.ndarray | None = None,
57
+ feature_values: np.ndarray | None = None,
58
+ ) -> None:
59
+ """Verify GAUL hierarchy nesting and (optionally) sum reconciliation."""
60
+ violations = check_nesting(gaul0=gaul0, gaul1=gaul1, gaul2=gaul2)
61
+ if violations:
62
+ raise RuntimeError(
63
+ f"Hierarchical nesting violation (ADR-040): "
64
+ f"{len(violations)} violation(s): {'; '.join(violations[:5])}"
65
+ )
66
+
67
+ if feature_values is None:
68
+ return
69
+
70
+ # Sum reconciliation: totals grouped by each level must match
71
+ levels = {"gaul0": gaul0}
72
+ if gaul1 is not None:
73
+ levels["gaul1"] = gaul1
74
+ if gaul2 is not None:
75
+ levels["gaul2"] = gaul2
76
+
77
+ totals: dict[str, float] = {}
78
+ for name, codes in levels.items():
79
+ level_total = sum(
80
+ float(feature_values[codes == c].sum())
81
+ for c in np.unique(codes)
82
+ )
83
+ totals[name] = level_total
84
+
85
+ level_names = list(totals.keys())
86
+ for i in range(1, len(level_names)):
87
+ a, b = level_names[0], level_names[i]
88
+ if not np.allclose(totals[a], totals[b], rtol=1e-6, atol=1e-4):
89
+ raise RuntimeError(
90
+ f"Hierarchical sum mismatch (ADR-040): "
91
+ f"{a}={totals[a]:.6f} != {b}={totals[b]:.6f}"
92
+ )
@@ -0,0 +1,39 @@
1
+ """Shared validation helpers for adapter modules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ __all__ = ["validate_grid_pgids", "validate_pgids"]
8
+
9
+
10
+ def validate_grid_pgids(
11
+ grid: np.ndarray, pgids: np.ndarray
12
+ ) -> None:
13
+ """Validate grid [T, H, W, C] and pgids [H, W] compatibility.
14
+
15
+ Raises:
16
+ ValueError: If grid is not 4D, pgids is not 2D, or
17
+ spatial dimensions don't match.
18
+ """
19
+ if grid.ndim != 4:
20
+ msg = f"grid must be 4D [T, H, W, C], got {grid.ndim}D"
21
+ raise ValueError(msg)
22
+ validate_pgids(pgids)
23
+ if grid.shape[1:3] != pgids.shape:
24
+ msg = (
25
+ f"grid spatial dims {grid.shape[1:3]} "
26
+ f"!= pgids shape {pgids.shape}"
27
+ )
28
+ raise ValueError(msg)
29
+
30
+
31
+ def validate_pgids(pgids: np.ndarray) -> None:
32
+ """Validate pgids is 2D [H, W].
33
+
34
+ Raises:
35
+ ValueError: If pgids is not 2D.
36
+ """
37
+ if pgids.ndim != 2:
38
+ msg = f"pgids must be 2D [H, W], got {pgids.ndim}D"
39
+ raise ValueError(msg)
@@ -0,0 +1,25 @@
1
+ """FeatureFrame — re-exported from views-frames v1.0.0.
2
+
3
+ The local FeatureFrame has been replaced by the canonical
4
+ views-frames implementation (#220). This module re-exports
5
+ to preserve the import path.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from views_frames import (
11
+ FeatureFrame,
12
+ FrameMetadata,
13
+ SpatialLevel,
14
+ SpatioTemporalIndex,
15
+ )
16
+
17
+ REQUIRED_IDENTIFIERS: set[str] = {"time", "unit"}
18
+
19
+ __all__ = [
20
+ "FeatureFrame",
21
+ "FrameMetadata",
22
+ "REQUIRED_IDENTIFIERS",
23
+ "SpatialLevel",
24
+ "SpatioTemporalIndex",
25
+ ]
@@ -0,0 +1,89 @@
1
+ """FeatureFrame to grid array reconstruction.
2
+
3
+ Inverse of grid_to_feature_frame: takes a FeatureFrame with
4
+ (time, unit) identifiers and reconstructs the canonical
5
+ [T, H, W, F] grid array using a pgids lookup.
6
+
7
+ Designed to be extractable: depends only on numpy.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+
14
+ import numpy as np
15
+
16
+ from datafactory_adapters.feature_frame import FeatureFrame
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ def feature_frame_to_grid(
22
+ ff: FeatureFrame,
23
+ pgids: np.ndarray,
24
+ ) -> np.ndarray:
25
+ """Reconstruct a [T, H, W, F] grid from a FeatureFrame.
26
+
27
+ Args:
28
+ ff: FeatureFrame with identifiers 'time' (month_ids)
29
+ and 'unit' (priogrid_gid values).
30
+ pgids: Cell ID array of shape [H, W] used to map
31
+ unit values back to (row, col) positions.
32
+
33
+ Returns:
34
+ np.ndarray of shape [T, H, W, F] with dtype float32.
35
+ Cells not present in the FeatureFrame are set to 0.0.
36
+ """
37
+ from datafactory_adapters._validation import validate_pgids
38
+
39
+ validate_pgids(pgids)
40
+ if ff.sample_count > 1:
41
+ raise ValueError(
42
+ f"feature_frame_to_grid requires S=1, "
43
+ f"got S={ff.sample_count}"
44
+ )
45
+ n_h, n_w = pgids.shape
46
+ n_f = ff.n_features
47
+
48
+ month_ids = ff.identifiers["time"]
49
+ unit_ids = ff.identifiers["unit"]
50
+ data = ff.values[:, :, 0] # (N, F) — squeeze trailing S=1
51
+
52
+ # Determine T from unique month_ids, preserving order
53
+ unique_months = np.unique(month_ids)
54
+ n_t = len(unique_months)
55
+ month_to_t: dict[int, int] = {
56
+ int(m): i for i, m in enumerate(unique_months)
57
+ }
58
+
59
+ # Build pgid → (row, col) lookup
60
+ pgid_to_rc: dict[int, tuple[int, int]] = {}
61
+ for r in range(n_h):
62
+ for c in range(n_w):
63
+ pgid_to_rc[int(pgids[r, c])] = (r, c)
64
+
65
+ # Allocate output
66
+ grid = np.zeros((n_t, n_h, n_w, n_f), dtype=np.float32)
67
+
68
+ # Place each row
69
+ n_placed = 0
70
+ n_skipped = 0
71
+ for i in range(len(month_ids)):
72
+ mid = int(month_ids[i])
73
+ uid = int(unit_ids[i])
74
+
75
+ t = month_to_t.get(mid)
76
+ rc = pgid_to_rc.get(uid)
77
+
78
+ if t is not None and rc is not None:
79
+ r, c = rc
80
+ grid[t, r, c, :] = data[i]
81
+ n_placed += 1
82
+ else:
83
+ n_skipped += 1
84
+
85
+ logger.info(
86
+ "Reconstructed [%d, %d, %d, %d]: %d placed, %d skipped",
87
+ n_t, n_h, n_w, n_f, n_placed, n_skipped,
88
+ )
89
+ return grid
@@ -0,0 +1,169 @@
1
+ """Grid array to country-month DataFrame conversion.
2
+
3
+ Aggregates the canonical [T, H, W, C] grid to country-month level:
4
+ sums feature values per (month_id, country_id) using a country
5
+ identifier feature (default: gaul0_code) as the grouping key.
6
+
7
+ Reuses _flatten_grid() from grid_to_dataframe for the initial
8
+ flattening step.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ import warnings
15
+
16
+ import numpy as np
17
+ import pandas as pd
18
+
19
+ from datafactory_adapters._conservation import assert_cm_conservation
20
+ from datafactory_adapters.grid_to_dataframe import _flatten_grid
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+ __all__ = ["grid_to_country_month"]
25
+
26
+
27
+ def grid_to_country_month(
28
+ grid: np.ndarray,
29
+ pgids: np.ndarray,
30
+ time_steps: np.ndarray,
31
+ feature_names: list[str],
32
+ *,
33
+ country_feature: str = "gaul0_code",
34
+ land_pgids: set[int] | None = None,
35
+ month_id_epoch: int = 0,
36
+ feature_agg_types: dict[str, str] | None = None,
37
+ ) -> pd.DataFrame:
38
+ """Convert a [T, H, W, C] grid to a country-month DataFrame.
39
+
40
+ Flattens the grid to cell level, then groups by
41
+ (month_id, country_id) and sums numeric features.
42
+
43
+ When *feature_agg_types* is provided (ADR-048), intensive
44
+ features raise ``ValueError`` (fail-loud, ADR-011) and static
45
+ features are excluded from the aggregation.
46
+
47
+ Args:
48
+ grid: Grid array of shape [T, H, W, C].
49
+ pgids: Cell ID array of shape [H, W].
50
+ time_steps: Time array of shape [T] (datetime64[M]).
51
+ feature_names: List of C feature column names.
52
+ country_feature: Name of the feature used as country
53
+ identifier for grouping (default: "gaul0_code").
54
+ land_pgids: Optional set of land cell IDs. If provided,
55
+ only land cells are included.
56
+ month_id_epoch: Base year for month_id encoding.
57
+ feature_agg_types: Feature name → aggregation type mapping
58
+ from the source registry (ADR-048). When provided,
59
+ enables type-aware aggregation.
60
+
61
+ Returns:
62
+ DataFrame with (month_id, country_id) MultiIndex and
63
+ one column per extensive feature.
64
+
65
+ Raises:
66
+ ValueError: If country_feature is not in feature_names,
67
+ or if intensive features are present when
68
+ feature_agg_types is provided.
69
+ """
70
+ if country_feature not in feature_names:
71
+ msg = (
72
+ f"Country feature {country_feature!r} not in "
73
+ f"feature_names: {feature_names}"
74
+ )
75
+ raise ValueError(msg)
76
+
77
+ flat_data, all_month_ids, all_pgids = _flatten_grid(
78
+ grid, pgids, time_steps, month_id_epoch, land_pgids,
79
+ )
80
+
81
+ country_idx = feature_names.index(country_feature)
82
+ country_ids = flat_data[:, country_idx].astype(np.int64)
83
+
84
+ # Exclude ocean cells (country_id <= 0)
85
+ land_mask = country_ids > 0
86
+ excluded_mask = ~land_mask
87
+ n_excluded = int(excluded_mask.sum())
88
+
89
+ if n_excluded > 0:
90
+ # Declared extensive features only (ADR-003/ADR-048, C-302):
91
+ # no name inference. Without the declaration the warning is
92
+ # skipped — the conservation check below is likewise a no-op
93
+ # for such callers (C-301).
94
+ event_indices = (
95
+ [
96
+ i for i, f in enumerate(feature_names)
97
+ if feature_agg_types.get(f) == "extensive"
98
+ ]
99
+ if feature_agg_types is not None
100
+ else []
101
+ )
102
+ if event_indices:
103
+ excluded_events = flat_data[excluded_mask][:, event_indices]
104
+ rows_with_events = np.nansum(excluded_events, axis=1) > 0
105
+ n_with_events = int(rows_with_events.sum())
106
+ if n_with_events > 0:
107
+ warnings.warn(
108
+ f"CM aggregation excluded {n_excluded} cell-months "
109
+ f"with country_id <= 0 (unmapped GAUL centroids). "
110
+ f"{n_with_events} have nonzero event values. "
111
+ f"See C-149 in the technical risk register.",
112
+ UserWarning,
113
+ stacklevel=2,
114
+ )
115
+
116
+ # ADR-040 Invariant 1: grid_total = land_total + excluded_total
117
+ assert_cm_conservation(
118
+ feature_names,
119
+ flat_data,
120
+ flat_data[land_mask],
121
+ flat_data[excluded_mask],
122
+ feature_agg_types=feature_agg_types,
123
+ )
124
+
125
+ flat_data = flat_data[land_mask]
126
+ all_month_ids = all_month_ids[land_mask]
127
+ country_ids = country_ids[land_mask]
128
+
129
+ # Drop the country feature column from the data
130
+ value_features = [
131
+ f for i, f in enumerate(feature_names) if i != country_idx
132
+ ]
133
+ value_data = np.delete(flat_data, country_idx, axis=1)
134
+
135
+ if feature_agg_types is not None:
136
+ intensive = [
137
+ f for f in value_features
138
+ if feature_agg_types.get(f) == "intensive"
139
+ ]
140
+ if intensive:
141
+ msg = (
142
+ f"Country-month aggregation cannot sum intensive "
143
+ f"features (ADR-048, ADR-011). Intensive features "
144
+ f"are indices, not counts — their sums across "
145
+ f"cells are not meaningful. Remove these features "
146
+ f"or use output_format='dataframe': {intensive}"
147
+ )
148
+ raise ValueError(msg)
149
+ # Exclude static features from aggregation
150
+ keep = [
151
+ i for i, f in enumerate(value_features)
152
+ if feature_agg_types.get(f) != "static"
153
+ ]
154
+ value_features = [value_features[i] for i in keep]
155
+ value_data = value_data[:, keep]
156
+
157
+ df = pd.DataFrame(
158
+ value_data,
159
+ columns=value_features,
160
+ )
161
+ df["month_id"] = all_month_ids
162
+ df["country_id"] = country_ids
163
+
164
+ result = (
165
+ df.groupby(["month_id", "country_id"], sort=True)
166
+ .sum()
167
+ )
168
+
169
+ return result