jcmsuite-xarray 1.0.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.
@@ -0,0 +1,245 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2001-2026 JCMwave GmbH
3
+
4
+ """Field-specific xarray tree construction."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from collections.abc import Mapping
9
+ from typing import TYPE_CHECKING, Protocol
10
+
11
+ import numpy as np
12
+
13
+ from jcmsuite.results.field_payloads import _CoordinateTopology
14
+ from jcmsuite.results.internal.export.xarray.types import XarrayDataset, XarrayDataTree
15
+
16
+ from . import runtime as _runtime
17
+ from .runtime import _DataTreeModule, _load_xarray_module
18
+
19
+ if TYPE_CHECKING:
20
+ from jcmsuite.results.field_payloads import _NormalizedFieldData
21
+
22
+
23
+ class _FieldExportView(Protocol):
24
+ """Core field-navigation operations consumed by the xarray adapter."""
25
+
26
+ @property
27
+ def indices(self) -> tuple[int, ...]: ...
28
+
29
+ @property
30
+ def _selected_index(self) -> int | None: ...
31
+
32
+ @property
33
+ def _view(self) -> str: ...
34
+
35
+ def to_dict(self) -> Mapping[object, object]: ...
36
+
37
+ def _field_entries(
38
+ self, mapping: Mapping[object, object]
39
+ ) -> tuple[object, ...]: ...
40
+
41
+ def _title(self, mapping: Mapping[object, object]) -> str | None: ...
42
+
43
+ def _export_field_values(self, field: np.ndarray) -> np.ndarray: ...
44
+
45
+ def _derivative_payloads(self) -> dict[str, Mapping[object, object]]: ...
46
+
47
+ def _project_mapping(
48
+ self, mapping: Mapping[object, object]
49
+ ) -> dict[object, object]: ...
50
+
51
+
52
+ def field_export_to_tree(view: _FieldExportView) -> XarrayDataTree:
53
+ """Convert a selected core field view into an xarray tree."""
54
+
55
+ if view._view in {"complete", "base", "derivative"}:
56
+ mapping: Mapping[object, object] = view.to_dict()
57
+ if not view._field_entries(mapping):
58
+ raise ValueError("Field export contains no field entries.")
59
+ return _field_mapping_to_tree(
60
+ view,
61
+ mapping,
62
+ include_derivatives=view._view == "complete",
63
+ )
64
+
65
+ derivative_items: list[tuple[str, Mapping[object, object]]] = [
66
+ (name, view._project_mapping(mapping))
67
+ for name, mapping in view._derivative_payloads().items()
68
+ ]
69
+ if not derivative_items:
70
+ raise ValueError("Field export contains no derivative branches.")
71
+ for _, mapping in derivative_items:
72
+ if not view._field_entries(mapping):
73
+ raise ValueError("Field export contains no field entries.")
74
+ root_name, root_mapping = derivative_items[0]
75
+ root: XarrayDataTree = _field_mapping_to_tree(
76
+ view, root_mapping, include_derivatives=False
77
+ )
78
+ children: dict[str, XarrayDataTree] = {
79
+ child_name: _field_mapping_to_tree(
80
+ view, child_mapping, include_derivatives=False
81
+ )
82
+ for child_name, child_mapping in derivative_items[1:]
83
+ }
84
+ if not children:
85
+ return root
86
+ return _runtime._create_data_tree(
87
+ datatree_module=_runtime._load_datatree_module(),
88
+ dataset=getattr(root, "ds", None),
89
+ children=children,
90
+ name=root_name,
91
+ )
92
+
93
+
94
+ def _field_mapping_to_tree(
95
+ view: _FieldExportView,
96
+ mapping: Mapping[object, object],
97
+ *,
98
+ include_derivatives: bool,
99
+ ) -> XarrayDataTree:
100
+ """Construct one selected field mapping, including derivative children."""
101
+
102
+ from jcmsuite.results.field_payloads import _build_field_data
103
+
104
+ entries: tuple[object, ...] = view._field_entries(mapping)
105
+ if not entries:
106
+ raise ValueError("Field export contains no field entries.")
107
+ fields: list[np.ndarray] = []
108
+ first_data: _NormalizedFieldData | None = None
109
+ for position in range(len(entries)):
110
+ data: _NormalizedFieldData = _build_field_data(
111
+ mapping,
112
+ field_index=position,
113
+ title=view._title(mapping),
114
+ include_derivatives=False,
115
+ )
116
+ if first_data is None:
117
+ first_data = data
118
+ fields.append(view._export_field_values(np.asarray(data.field)))
119
+ assert first_data is not None
120
+ has_selected_field: bool = view._selected_index is not None
121
+ field_values: np.ndarray = (
122
+ fields[0] if has_selected_field else np.stack(fields, axis=0)
123
+ )
124
+ grid_value: object = mapping.get("grid")
125
+ grid_mapping: Mapping[object, object] | None = (
126
+ grid_value if isinstance(grid_value, Mapping) else None
127
+ )
128
+ tree: XarrayDataTree = field_data_to_tree(
129
+ coordinates=first_data.coordinates,
130
+ field=field_values,
131
+ component_labels=first_data.component_labels,
132
+ title=first_data.title,
133
+ field_indices=view.indices,
134
+ include_field_index=not has_selected_field,
135
+ datatree_module=_runtime._load_datatree_module(),
136
+ grid=grid_mapping,
137
+ )
138
+ if not include_derivatives:
139
+ return tree
140
+ children: dict[str, XarrayDataTree] = {
141
+ name: _field_mapping_to_tree(
142
+ view,
143
+ view._project_mapping(child_mapping),
144
+ include_derivatives=False,
145
+ )
146
+ for name, child_mapping in view._derivative_payloads().items()
147
+ }
148
+ if not children:
149
+ return tree
150
+ return _runtime._create_data_tree(
151
+ datatree_module=_runtime._load_datatree_module(),
152
+ dataset=getattr(tree, "ds", None),
153
+ children=children,
154
+ )
155
+
156
+
157
+ def field_data_to_tree(
158
+ *,
159
+ coordinates: _CoordinateTopology,
160
+ field: np.ndarray,
161
+ component_labels: tuple[str, ...],
162
+ title: str | None,
163
+ field_indices: tuple[int, ...],
164
+ include_field_index: bool,
165
+ datatree_module: _DataTreeModule,
166
+ grid: Mapping[object, object] | None = None,
167
+ ) -> XarrayDataTree:
168
+ """Build an xarray tree with the source coordinate names."""
169
+
170
+ grid_dims: tuple[str, ...] = tuple(
171
+ f"grid_dim_{axis_index}" for axis_index in range(len(coordinates.grid_shape))
172
+ )
173
+ field_dims: tuple[str, ...] = (
174
+ ("field_index",) if include_field_index else ()
175
+ ) + grid_dims
176
+ has_component_axis: bool = field.ndim == len(field_dims) + 1
177
+ data_vars: dict[str, object] = {
178
+ "field": (
179
+ field_dims + (("component",) if has_component_axis else ()),
180
+ field,
181
+ )
182
+ }
183
+ if grid is not None:
184
+ data_vars.update(_grid_data_vars(grid))
185
+ coords: dict[str, object] = {}
186
+ for coordinate_index, (coordinate_name, coordinate_value) in enumerate(
187
+ zip(coordinates.names, coordinates.values, strict=True)
188
+ ):
189
+ if coordinate_value.ndim == 0:
190
+ coords[coordinate_name] = coordinate_value
191
+ elif coordinate_value.ndim == 1 and len(coordinates.names) > 1:
192
+ matching_dimensions: tuple[int, ...] = tuple(
193
+ dimension_index
194
+ for dimension_index, dimension_size in enumerate(coordinates.grid_shape)
195
+ if dimension_size == coordinate_value.size
196
+ )
197
+ dimension_index: int = (
198
+ matching_dimensions[0]
199
+ if len(matching_dimensions) == 1
200
+ else coordinate_index
201
+ )
202
+ coords[coordinate_name] = (
203
+ (grid_dims[dimension_index],),
204
+ coordinate_value,
205
+ )
206
+ else:
207
+ coords[coordinate_name] = (grid_dims, coordinate_value)
208
+ if include_field_index:
209
+ coords["field_index"] = ("field_index", list(field_indices))
210
+ if has_component_axis:
211
+ coords["component"] = ("component", list(component_labels))
212
+ attrs: dict[str, object] = {"coordinate_names": coordinates.names}
213
+ if coordinates.names:
214
+ attrs["x_label"] = coordinates.names[0]
215
+ if len(coordinates.names) > 1:
216
+ attrs["y_label"] = coordinates.names[1]
217
+ if title is not None:
218
+ attrs["title"] = title
219
+ if has_component_axis:
220
+ attrs["component_labels"] = component_labels
221
+ dataset: XarrayDataset = _load_xarray_module().Dataset(
222
+ data_vars=data_vars,
223
+ coords=coords,
224
+ attrs=attrs,
225
+ )
226
+ return _runtime._create_data_tree(
227
+ datatree_module=datatree_module,
228
+ dataset=dataset,
229
+ )
230
+
231
+
232
+ def _grid_data_vars(grid: Mapping[object, object]) -> dict[str, object]:
233
+ """Return grid mapping entries as xarray data variables."""
234
+
235
+ data_vars: dict[str, object] = {}
236
+ for raw_name, raw_value in grid.items():
237
+ if not isinstance(raw_name, str):
238
+ continue
239
+ value: np.ndarray = np.asarray(raw_value)
240
+ dimensions: tuple[str, ...] = tuple(
241
+ "grid_point" if axis_index == 0 else f"grid_point_dim_{axis_index}"
242
+ for axis_index in range(value.ndim)
243
+ )
244
+ data_vars[raw_name] = (dimensions, value)
245
+ return data_vars