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,259 @@
1
+ """Zarr backend for the assembled grid (local or remote).
2
+
3
+ One responsibility: open a zarr store (with netrc auth for remote
4
+ HTTP), read the grid + source metadata attrs, and return the same
5
+ tuple shape as the npy backend. Split from dataset.py per ADR-050
6
+ screaming-architecture surgery (#346).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ import warnings
13
+ from pathlib import Path
14
+ from urllib.parse import urlparse
15
+
16
+ import numpy as np
17
+
18
+ from datafactory_query.temporal import parse_time_range, time_range_to_slice
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ def _is_remote(data_dir: Path | str) -> bool:
23
+ """Check if data_dir is a remote URL."""
24
+ if isinstance(data_dir, Path):
25
+ return False
26
+ return "://" in str(data_dir)
27
+
28
+
29
+ def _use_zarr_loader(data_dir: Path | str) -> bool:
30
+ """Check if data_dir should be loaded via the zarr backend.
31
+
32
+ True for local paths ending in .zarr or remote URLs with
33
+ .zarr in the path component.
34
+ """
35
+ s = str(data_dir)
36
+ if _is_remote(data_dir):
37
+ return ".zarr" in urlparse(s).path
38
+ return s.endswith(".zarr")
39
+
40
+
41
+
42
+ _REMOTE_TIMEOUT_SECONDS = 120
43
+
44
+
45
+ def _resolve_storage_options(
46
+ zarr_path: str,
47
+ ) -> dict | None:
48
+ """Build fsspec storage options for remote zarr access.
49
+
50
+ Reads credentials from ~/.netrc for HTTP URLs.
51
+ Configures aiohttp timeout for network resilience.
52
+ Returns None for local paths.
53
+ """
54
+ if not _is_remote(zarr_path):
55
+ return None
56
+
57
+ parsed = urlparse(zarr_path)
58
+ if parsed.scheme not in ("http", "https"):
59
+ return {}
60
+
61
+ import aiohttp
62
+
63
+ client_kwargs: dict = {
64
+ "timeout": aiohttp.ClientTimeout(
65
+ total=_REMOTE_TIMEOUT_SECONDS,
66
+ ),
67
+ }
68
+
69
+ # Try ~/.netrc for credentials
70
+ try:
71
+ from netrc import NetrcParseError, netrc
72
+
73
+ nrc = netrc(str(Path.home() / ".netrc"))
74
+ creds = nrc.authenticators(parsed.hostname or "")
75
+ if creds:
76
+ login, _, password = creds
77
+ client_kwargs["auth"] = aiohttp.BasicAuth(
78
+ login, password,
79
+ )
80
+ except (FileNotFoundError, KeyError, NetrcParseError) as exc:
81
+ logger.warning(
82
+ "No credentials for %s: %s. "
83
+ "Remote access may fail with 401.",
84
+ parsed.hostname,
85
+ exc,
86
+ )
87
+
88
+ return {"client_kwargs": client_kwargs}
89
+
90
+
91
+ def _load_grid_from_zarr(
92
+ zarr_path: str,
93
+ storage_options: dict | None = None,
94
+ *,
95
+ start: str | int | None = None,
96
+ end: str | int | None = None,
97
+ feature_sel: list[str] | None = None,
98
+ ) -> tuple[
99
+ np.ndarray, np.ndarray, np.ndarray, list[str],
100
+ int | None, dict[str, int],
101
+ dict[str, str] | None, dict[str, list[str]],
102
+ ]:
103
+ """Load assembled grid from a zarr store.
104
+
105
+ Opens the store once, computes time/feature subsets lazily on
106
+ the xarray Dataset, then materializes only the needed data.
107
+ For remote stores this avoids downloading the full grid.
108
+
109
+ Args:
110
+ zarr_path: Local path or URL to zarr store.
111
+ storage_options: fsspec options (auth, timeout, etc.).
112
+ start: Start of time range (passed to parse_time_range).
113
+ end: End of time range (passed to parse_time_range).
114
+ feature_sel: Optional feature names to load (skips others).
115
+
116
+ Returns:
117
+ (grid, pgids, time_steps, feature_names,
118
+ last_valid_month_id, first_valid_month_ids,
119
+ feature_agg_types, source_features)
120
+ """
121
+ import xarray as xr
122
+
123
+ kwargs: dict = {}
124
+ if storage_options is not None:
125
+ kwargs["storage_options"] = storage_options
126
+
127
+ try:
128
+ ds = xr.open_zarr(zarr_path, **kwargs)
129
+ except (FileNotFoundError, ValueError, KeyError) as exc:
130
+ msg = f"Zarr store not found or invalid at {zarr_path}"
131
+ raise FileNotFoundError(msg) from exc
132
+ except OSError as exc:
133
+ exc_msg = str(exc)
134
+ if "401" in exc_msg or "Unauthorized" in exc_msg:
135
+ msg = (
136
+ f"Authentication failed for {zarr_path}. "
137
+ f"Check ~/.netrc credentials."
138
+ )
139
+ raise PermissionError(msg) from exc
140
+ msg = (
141
+ f"Cannot open zarr store at {zarr_path}: "
142
+ f"{type(exc).__name__}: {exc_msg}"
143
+ )
144
+ raise FileNotFoundError(msg) from exc
145
+ except Exception as exc:
146
+ # aiohttp's ClientResponseError is NOT an OSError, so an HTTP 401
147
+ # from the remote store escaped the mapping above and consumers
148
+ # got a raw client error instead of the documented
149
+ # PermissionError (C-321). Map 401s here; anything else re-raises
150
+ # untouched.
151
+ exc_msg = str(exc)
152
+ if "401" in exc_msg or "Unauthorized" in exc_msg:
153
+ msg = (
154
+ f"Authentication failed for {zarr_path}. "
155
+ f"Check ~/.netrc credentials."
156
+ )
157
+ raise PermissionError(msg) from exc
158
+ raise
159
+
160
+ pgids = ds["pgid"].values # [H, W]
161
+ last_valid_month_id: int | None = ds.attrs.get(
162
+ "last_valid_month_id",
163
+ )
164
+ if last_valid_month_id is None:
165
+ warnings.warn(
166
+ f"Zarr store at {zarr_path} lacks 'last_valid_month_id' "
167
+ f"attribute. Zero-padding boundary unknown — consumer "
168
+ f"cannot distinguish observed zeros from padding. "
169
+ f"Re-export with export_zarr.py to fix.",
170
+ UserWarning,
171
+ stacklevel=2,
172
+ )
173
+
174
+ # Determine feature order before subsetting
175
+ attrs = ds.attrs
176
+ if "feature_order" in attrs:
177
+ feature_names = list(attrs["feature_order"])
178
+ else:
179
+ warnings.warn(
180
+ f"Zarr store at {zarr_path} lacks 'feature_order' "
181
+ f"attribute. Falling back to sorted(data_vars). "
182
+ f"Feature column order may differ from the npy "
183
+ f"backend. Re-export with export_zarr.py to fix.",
184
+ UserWarning,
185
+ stacklevel=2,
186
+ )
187
+ feature_names = sorted(ds.data_vars)
188
+
189
+ # Source metadata (C-300): mirrors the npy sidecars so the
190
+ # pre-coverage warning and type-aware aggregation work on the
191
+ # zarr path too. Keyed exactly like provenance.json.
192
+ first_valid_month_ids: dict[str, int] = {}
193
+ source_features: dict[str, list[str]] = {}
194
+ feature_agg_types: dict[str, str] | None = None
195
+ if "source_features" in attrs:
196
+ source_features = {
197
+ k: list(v)
198
+ for k, v in attrs["source_features"].items()
199
+ }
200
+ first_valid_month_ids = {
201
+ k: int(v)
202
+ for k, v in attrs.get(
203
+ "first_valid_month_ids", {},
204
+ ).items()
205
+ }
206
+ agg_list = attrs.get("feature_agg_types")
207
+ if agg_list is not None:
208
+ feature_agg_types = dict(
209
+ zip(feature_names, list(agg_list), strict=True),
210
+ )
211
+ else:
212
+ warnings.warn(
213
+ f"Zarr store at {zarr_path} lacks source metadata "
214
+ f"attributes (source_features / first_valid_month_ids "
215
+ f"/ feature_agg_types). Pre-coverage warnings and "
216
+ f"type-aware aggregation are unavailable on this "
217
+ f"store. Re-export with export_zarr.py to fix.",
218
+ UserWarning,
219
+ stacklevel=2,
220
+ )
221
+
222
+ # Apply feature subsetting (lazy — no data fetched yet)
223
+ if feature_sel is not None:
224
+ available = set(feature_names)
225
+ missing = [f for f in feature_sel if f not in available]
226
+ if missing:
227
+ msg = (
228
+ f"Unknown feature(s) {missing}. "
229
+ f"Available: {feature_names}"
230
+ )
231
+ raise ValueError(msg)
232
+ feature_names = [
233
+ f for f in feature_names if f in set(feature_sel)
234
+ ]
235
+
236
+ # Apply time subsetting (lazy — reduces chunk fetches)
237
+ all_time = ds["time"].values.astype("datetime64[M]")
238
+ if start is not None or end is not None:
239
+ start_dt, end_dt = parse_time_range(
240
+ start, end, time_steps=all_time,
241
+ )
242
+ t_slice = time_range_to_slice(
243
+ all_time, start_dt, end_dt,
244
+ )
245
+ ds = ds.isel(time=t_slice)
246
+
247
+ time_steps = ds["time"].values.astype("datetime64[M]")
248
+
249
+ # Materialize only the selected features and time range
250
+ grid = np.stack(
251
+ [ds[f].values for f in feature_names], axis=-1,
252
+ ).astype(np.float32)
253
+
254
+ ds.close()
255
+ return (
256
+ grid, pgids, time_steps, feature_names,
257
+ last_valid_month_id, first_valid_month_ids,
258
+ feature_agg_types, source_features,
259
+ )
@@ -0,0 +1,64 @@
1
+ """Pre-coverage consumer warnings (ADR-047, ADR-048, C-156).
2
+
3
+ One responsibility: warn when a query's time range starts before a
4
+ source's first valid month, using declared source-feature lists
5
+ (never name inference — ADR-003). Split from dataset.py per
6
+ ADR-050 screaming-architecture surgery (#346).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import warnings
12
+
13
+ _SOURCE_DISPLAY_NAMES: dict[str, str] = {
14
+ "acled": "ACLED",
15
+ "ghspop": "GHS-POP",
16
+ "ghsbuilts": "GHS-BUILT-S",
17
+ "vdem": "V-Dem",
18
+ "shdi": "SHDI",
19
+ }
20
+
21
+
22
+ def _warn_pre_coverage(
23
+ query_start_mid: int,
24
+ first_valid_month_ids: dict[str, int],
25
+ requested_features: set[str],
26
+ source_features: dict[str, list[str]],
27
+ ) -> None:
28
+ """Emit UserWarning for each source whose data starts after
29
+ the query's start month, when the query includes features
30
+ from that source (ADR-047, ADR-048, C-156).
31
+
32
+ Uses declared source-feature lists from provenance instead
33
+ of prefix inference (ADR-003 compliance).
34
+ """
35
+ for key, first_mid in first_valid_month_ids.items():
36
+ if query_start_mid >= first_mid:
37
+ continue
38
+ source_key = (
39
+ key.removeprefix("first_valid_")
40
+ .removesuffix("_month_id")
41
+ )
42
+ features_key = f"{source_key}_features"
43
+ src_feats = source_features.get(features_key)
44
+ if src_feats is None:
45
+ continue
46
+ src_set = set(src_feats)
47
+ affected = [
48
+ f for f in requested_features if f in src_set
49
+ ]
50
+ if not affected:
51
+ continue
52
+ source_name = _SOURCE_DISPLAY_NAMES.get(
53
+ source_key, source_key,
54
+ )
55
+ warnings.warn(
56
+ f"{source_name} data begins at month_id "
57
+ f"{first_mid}, but query starts at "
58
+ f"{query_start_mid}. Months "
59
+ f"{query_start_mid}–{first_mid - 1} contain "
60
+ f"zero-fill, not observed data. Affected "
61
+ f"features: {affected}",
62
+ UserWarning,
63
+ stacklevel=3,
64
+ )
@@ -0,0 +1,263 @@
1
+ """Unified dataset loading — the primary consumer entry point.
2
+
3
+ Loads a subset of the assembled grid by region, time range,
4
+ and features, returning the requested output format.
5
+
6
+ Supports both local npy directories and zarr stores (local or
7
+ remote via HTTP). Pass a Path for npy, or a string ending in
8
+ .zarr (local path or URL) for zarr access.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ import warnings
15
+ from pathlib import Path
16
+
17
+ import numpy as np
18
+ import pandas as pd
19
+
20
+ from datafactory_adapters import (
21
+ FeatureFrame,
22
+ grid_to_country_month,
23
+ grid_to_dataframe,
24
+ grid_to_feature_frame,
25
+ )
26
+ from datafactory_query.backends_npy import _load_grid_from_npy
27
+ from datafactory_query.backends_zarr import (
28
+ _load_grid_from_zarr,
29
+ _resolve_storage_options,
30
+ _use_zarr_loader,
31
+ )
32
+ from datafactory_query.coverage import _warn_pre_coverage
33
+ from datafactory_query.output_format import OutputFormat
34
+ from datafactory_query.regions import load_region_pgids
35
+ from datafactory_query.temporal import parse_time_range, time_range_to_slice
36
+
37
+ __all__ = ["load_dataset"]
38
+
39
+ logger = logging.getLogger(__name__)
40
+
41
+ # Internal alias — the public contract is OutputFormat (ADR-050).
42
+ _VALID_FORMATS = tuple(f.value for f in OutputFormat)
43
+
44
+
45
+ def _load_grid(
46
+ data_dir: Path | str,
47
+ *,
48
+ start: str | int | None = None,
49
+ end: str | int | None = None,
50
+ feature_sel: list[str] | None = None,
51
+ ) -> tuple[
52
+ np.ndarray, np.ndarray, np.ndarray, list[str],
53
+ int | None, dict[str, int],
54
+ dict[str, str] | None, dict[str, list[str]],
55
+ ]:
56
+ """Load assembled grid from npy directory or zarr store.
57
+
58
+ For zarr stores, start/end and feature_sel are applied lazily
59
+ before materializing — avoiding full-grid downloads for remote
60
+ stores when only a subset is needed.
61
+
62
+ Returns:
63
+ (grid, pgids, time_steps, feature_names,
64
+ last_valid_month_id, first_valid_month_ids,
65
+ feature_agg_types, source_features)
66
+ """
67
+ if _use_zarr_loader(data_dir):
68
+ storage_options = _resolve_storage_options(str(data_dir))
69
+ return _load_grid_from_zarr(
70
+ str(data_dir),
71
+ storage_options,
72
+ start=start,
73
+ end=end,
74
+ feature_sel=feature_sel,
75
+ )
76
+ return _load_grid_from_npy(Path(data_dir))
77
+
78
+
79
+ def _resolve_feature_indices(
80
+ feature_names: list[str],
81
+ features: list[str],
82
+ ) -> list[int]:
83
+ """Map requested feature names to indices in the grid."""
84
+ name_to_idx = {n: i for i, n in enumerate(feature_names)}
85
+ indices = []
86
+ for f in features:
87
+ if f not in name_to_idx:
88
+ msg = (
89
+ f"Unknown feature {f!r}. "
90
+ f"Available: {feature_names}"
91
+ )
92
+ raise ValueError(msg)
93
+ indices.append(name_to_idx[f])
94
+ return indices
95
+
96
+
97
+ def load_dataset(
98
+ *,
99
+ region: str = "land",
100
+ start: str | int | None = None,
101
+ end: str | int | None = None,
102
+ features: list[str] | None = None,
103
+ output_format: str = "feature_frame",
104
+ data_dir: Path | str = Path("data/assembled"),
105
+ gaul_dir: Path = Path("data/raw/gaul_admin"),
106
+ month_id_epoch: int = 1980,
107
+ ) -> FeatureFrame | pd.DataFrame:
108
+ """Load a subset of the assembled grid.
109
+
110
+ This is the primary consumer entry point. Handles temporal
111
+ subsetting, geographic filtering, feature selection, and
112
+ format conversion.
113
+
114
+ Args:
115
+ region: Geographic filter. Predefined regions ("africa_me",
116
+ "americas", "europe", "asia_oceania"), special values
117
+ ("global", "land"), or a GAUL country name ("Ethiopia").
118
+ start: Start of time range (inclusive). Accepts "2020",
119
+ "2020-01", "2020-01-15", VIEWS month_id (int), or
120
+ None (dataset start).
121
+ end: End of time range (inclusive). Same formats, or None
122
+ (dataset end).
123
+ features: List of feature names to include. None = all.
124
+ output_format: Output format: "feature_frame", "dataframe",
125
+ or "country_month" (sums grid cells per country).
126
+ data_dir: Path to assembled grid directory (npy), or string
127
+ path/URL to a zarr store.
128
+ gaul_dir: Path to GAUL admin Parquet files.
129
+ month_id_epoch: Epoch for month_id encoding (default 1980
130
+ = VIEWS convention).
131
+
132
+ Returns:
133
+ FeatureFrame or DataFrame depending on output_format.
134
+
135
+ Raises:
136
+ ValueError: For invalid region, time range, features, or format.
137
+ FileNotFoundError: If data files are not found.
138
+ """
139
+ if output_format not in _VALID_FORMATS:
140
+ msg = (
141
+ f"Unknown format {output_format!r}. "
142
+ f"Valid: {list(_VALID_FORMATS)}"
143
+ )
144
+ raise ValueError(msg)
145
+
146
+ # Auto-include gaul0_code for country_month aggregation
147
+ _country_feature = "gaul0_code"
148
+ feature_sel = features
149
+ if (
150
+ output_format == "country_month"
151
+ and features is not None
152
+ and _country_feature not in features
153
+ ):
154
+ feature_sel = [*features, _country_feature]
155
+
156
+ # Load grid. For zarr: time/feature subsetting applied lazily
157
+ # inside _load_grid_from_zarr (single open, no probe).
158
+ # For npy: full grid loaded via mmap, subsetted after.
159
+ is_zarr = _use_zarr_loader(data_dir)
160
+ (
161
+ grid, pgids, time_steps, all_features,
162
+ last_valid_month_id, first_valid_month_ids,
163
+ feature_agg_types, source_features,
164
+ ) = _load_grid(
165
+ data_dir,
166
+ start=start if is_zarr else None,
167
+ end=end if is_zarr else None,
168
+ feature_sel=feature_sel if is_zarr else None,
169
+ )
170
+
171
+ # For npy (or zarr with no time args): post-slice
172
+ if not is_zarr:
173
+ start_dt, end_dt = parse_time_range(
174
+ start, end, time_steps=time_steps,
175
+ )
176
+ t_slice = time_range_to_slice(
177
+ time_steps, start_dt, end_dt,
178
+ )
179
+ grid = grid[t_slice]
180
+ time_steps = time_steps[t_slice]
181
+
182
+ # Warn if loaded data extends beyond observed UCDP data
183
+ if last_valid_month_id is not None and len(time_steps) > 0:
184
+ from datafactory_priogrid import to_views_month_id
185
+
186
+ effective_end_mid = int(to_views_month_id(time_steps[-1]))
187
+ if effective_end_mid > last_valid_month_id:
188
+ warnings.warn(
189
+ f"Loaded data through month {effective_end_mid} "
190
+ f"exceeds last observed data month "
191
+ f"({last_valid_month_id}). Months "
192
+ f"{last_valid_month_id + 1}–{effective_end_mid} "
193
+ f"contain zeros, not observed data.",
194
+ stacklevel=2,
195
+ )
196
+
197
+ # Warn if loaded data starts before a source's coverage
198
+ if first_valid_month_ids and len(time_steps) > 0:
199
+ from datafactory_priogrid import to_views_month_id
200
+
201
+ effective_start_mid = int(
202
+ to_views_month_id(time_steps[0])
203
+ )
204
+ requested = set(feature_sel or all_features)
205
+ _warn_pre_coverage(
206
+ effective_start_mid,
207
+ first_valid_month_ids,
208
+ requested,
209
+ source_features,
210
+ )
211
+
212
+ # Feature subsetting (npy path — zarr already subsetted)
213
+ if feature_sel is not None and not is_zarr:
214
+ f_indices = _resolve_feature_indices(all_features, feature_sel)
215
+ grid = grid[:, :, :, f_indices]
216
+ all_features = [all_features[i] for i in f_indices]
217
+
218
+ # Geographic subsetting → land_pgids for adapters
219
+ region_pgids = load_region_pgids(region, gaul_dir=gaul_dir)
220
+
221
+ logger.info(
222
+ "Loading: region=%s (%d cells), time=%s..%s (%d months), "
223
+ "features=%d, format=%s",
224
+ region,
225
+ len(region_pgids),
226
+ time_steps[0],
227
+ time_steps[-1],
228
+ len(time_steps),
229
+ len(all_features),
230
+ output_format,
231
+ )
232
+
233
+ # Convert to requested format
234
+ if output_format == "feature_frame":
235
+ return grid_to_feature_frame(
236
+ grid,
237
+ pgids,
238
+ time_steps,
239
+ all_features,
240
+ land_pgids=region_pgids,
241
+ month_id_epoch=month_id_epoch,
242
+ )
243
+
244
+ if output_format == "country_month":
245
+ return grid_to_country_month(
246
+ grid,
247
+ pgids,
248
+ time_steps,
249
+ all_features,
250
+ land_pgids=region_pgids,
251
+ month_id_epoch=month_id_epoch,
252
+ feature_agg_types=feature_agg_types,
253
+ )
254
+
255
+ # output_format == "dataframe"
256
+ return grid_to_dataframe(
257
+ grid,
258
+ pgids,
259
+ time_steps,
260
+ all_features,
261
+ land_pgids=region_pgids,
262
+ month_id_epoch=month_id_epoch,
263
+ )
@@ -0,0 +1,101 @@
1
+ """Remote server defaults for the VIEWS data factory.
2
+
3
+ Centralizes the server address so consumers import a constant
4
+ instead of hardcoding the IP. Follows the GridConfig pattern
5
+ from datafactory_priogrid.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import base64
11
+ import json
12
+ import logging
13
+ import urllib.request
14
+ from dataclasses import dataclass
15
+ from netrc import NetrcParseError, netrc
16
+ from pathlib import Path
17
+ from types import MappingProxyType
18
+ from urllib.error import HTTPError, URLError
19
+ from urllib.parse import urlparse
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class RemoteConfig:
26
+ """Remote server configuration.
27
+
28
+ Frozen dataclass — construct a custom instance to override
29
+ any field (e.g., ``RemoteConfig(scheme="https")``).
30
+ """
31
+
32
+ server: str = "204.168.219.108"
33
+ zarr_path: str = "/grid.zarr"
34
+ scheme: str = "http"
35
+
36
+ @property
37
+ def zarr_url(self) -> str:
38
+ return f"{self.scheme}://{self.server}{self.zarr_path}"
39
+
40
+ @property
41
+ def parquet_url(self) -> str:
42
+ return f"{self.scheme}://{self.server}/dataframe.parquet"
43
+
44
+
45
+ DEFAULT_REMOTE = RemoteConfig()
46
+
47
+
48
+ def get_last_valid_month_id(
49
+ zarr_url: str | None = None,
50
+ ) -> int | None:
51
+ """Read last_valid_month_id from the zarr store's .zattrs.
52
+
53
+ Returns None if the attribute is not present (store was
54
+ exported before this metadata was added).
55
+ """
56
+ url = zarr_url or DEFAULT_REMOTE.zarr_url
57
+ attrs_url = f"{url}/.zattrs"
58
+
59
+ parsed = urlparse(attrs_url)
60
+ req = urllib.request.Request(attrs_url)
61
+
62
+ try:
63
+ nrc = netrc(str(Path.home() / ".netrc"))
64
+ creds = nrc.authenticators(parsed.hostname or "")
65
+ if creds:
66
+ login, _, password = creds
67
+ encoded = base64.b64encode(
68
+ f"{login}:{password}".encode(),
69
+ ).decode()
70
+ req.add_header("Authorization", f"Basic {encoded}")
71
+ except (FileNotFoundError, NetrcParseError, KeyError):
72
+ pass
73
+
74
+ try:
75
+ with urllib.request.urlopen(req, timeout=10) as resp:
76
+ raw = resp.read()
77
+ except (URLError, HTTPError, TimeoutError) as exc:
78
+ logger.error(
79
+ "Failed to read .zattrs from %s: %s",
80
+ attrs_url, exc,
81
+ )
82
+ raise
83
+
84
+ attrs = json.loads(raw)
85
+ val = attrs.get("last_valid_month_id")
86
+ return int(val) if val is not None else None
87
+
88
+
89
+ # VIEWS operational calendar — single source of truth for partition
90
+ # boundaries used by consumer scripts, examples, and tests.
91
+ # Forecasting is excluded (computed dynamically from current date).
92
+ _partitions_raw: dict[str, dict[str, tuple[int, int]]] = {
93
+ "calibration": {"train": (121, 456), "test": (457, 504)},
94
+ "validation": {"train": (121, 504), "test": (505, 552)},
95
+ }
96
+ PARTITIONS: MappingProxyType[
97
+ str, MappingProxyType[str, tuple[int, int]]
98
+ ] = MappingProxyType(
99
+ {k: MappingProxyType(v) for k, v in _partitions_raw.items()}
100
+ )
101
+ del _partitions_raw