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,291 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2001-2026 JCMwave GmbH
3
+
4
+ """Header-specific helpers for internal `xarray` exports."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from collections.abc import Mapping, Sequence
9
+ from typing import cast
10
+
11
+ import numpy as np
12
+
13
+ from jcmsuite.exceptions import InvalidConfigurationError
14
+ from jcmsuite.results.internal.export.pandas.payload import is_numeric_key_mapping
15
+ from jcmsuite.results.internal.export.xarray.types import XarrayDataset
16
+
17
+ from .runtime import _XarrayModule
18
+ from .shared import _field_key_sort_key, _tabular_column_dtype_for_padding
19
+
20
+
21
+ def _header_payload_to_dataset(
22
+ payload: Mapping[object, object],
23
+ *,
24
+ xarray_module: _XarrayModule,
25
+ ) -> XarrayDataset:
26
+ """Convert one header mapping into a root dataset."""
27
+
28
+ flattened_fields: dict[str, object] = {}
29
+ _flatten_header_fields(
30
+ payload,
31
+ flattened_fields=flattened_fields,
32
+ field_prefix="",
33
+ )
34
+ data_vars: dict[str, object] = {}
35
+ coords: dict[str, object] = {}
36
+ attrs: dict[str, object] = {}
37
+ field_name: str
38
+ field_value: object
39
+ for field_name, field_value in flattened_fields.items():
40
+ if isinstance(field_value, str):
41
+ attrs[field_name] = field_value
42
+ continue
43
+ _append_header_data_variable(
44
+ data_vars=data_vars,
45
+ coords=coords,
46
+ field_name=field_name,
47
+ field_value=field_value,
48
+ )
49
+ return xarray_module.Dataset(
50
+ data_vars=data_vars,
51
+ coords=coords or None,
52
+ attrs=attrs or None,
53
+ )
54
+
55
+
56
+ def _flatten_header_fields(
57
+ payload: Mapping[object, object],
58
+ *,
59
+ flattened_fields: dict[str, object],
60
+ field_prefix: str,
61
+ ) -> None:
62
+ """Flatten non-numeric nested header mappings into dotted field names."""
63
+
64
+ field_key: object
65
+ field_value: object
66
+ for field_key, field_value in payload.items():
67
+ field_name: str = (
68
+ f"{field_prefix}.{field_key}" if field_prefix else str(field_key)
69
+ )
70
+ if isinstance(field_value, Mapping) and not is_numeric_key_mapping(field_value):
71
+ _flatten_header_fields(
72
+ field_value,
73
+ flattened_fields=flattened_fields,
74
+ field_prefix=field_name,
75
+ )
76
+ continue
77
+ flattened_fields[field_name] = field_value
78
+
79
+
80
+ def _append_header_data_variable(
81
+ *,
82
+ data_vars: dict[str, object],
83
+ coords: dict[str, object],
84
+ field_name: str,
85
+ field_value: object,
86
+ ) -> None:
87
+ """Append one single-header header data variable."""
88
+
89
+ if isinstance(field_value, Mapping):
90
+ if not is_numeric_key_mapping(field_value):
91
+ raise InvalidConfigurationError(
92
+ f"Header field {field_name!r} is not supported by to_xarray()."
93
+ )
94
+ field_keys: list[object] = sorted(field_value, key=_field_key_sort_key)
95
+ arrays: list[np.ndarray] = [
96
+ _header_value_to_ndarray(field_value[field_key]) for field_key in field_keys
97
+ ]
98
+ first_shape: tuple[int, ...] = tuple(int(axis) for axis in arrays[0].shape)
99
+ array_value: np.ndarray
100
+ for array_value in arrays[1:]:
101
+ if tuple(int(axis) for axis in array_value.shape) != first_shape:
102
+ raise InvalidConfigurationError(
103
+ f"Header field {field_name!r} has inconsistent grouped value shapes for to_xarray()."
104
+ )
105
+ stacked_array: np.ndarray = np.stack(arrays, axis=0)
106
+ field_index_dim: str = f"{field_name}_field_index"
107
+ coords[field_index_dim] = list(field_keys)
108
+ dims: tuple[str, ...] = (field_index_dim,) + _header_value_dims(
109
+ field_name=field_name,
110
+ value_shape=first_shape,
111
+ )
112
+ data_vars[field_name] = (dims, stacked_array)
113
+ return
114
+
115
+ value_array: np.ndarray = _header_value_to_ndarray(field_value)
116
+ dims = _header_value_dims(
117
+ field_name=field_name,
118
+ value_shape=tuple(int(axis) for axis in value_array.shape),
119
+ )
120
+ if value_array.ndim == 0:
121
+ data_vars[field_name] = ((), value_array[()])
122
+ return
123
+ data_vars[field_name] = (dims, value_array)
124
+
125
+
126
+ def _append_stacked_header_data_variable(
127
+ *,
128
+ data_vars: dict[str, object],
129
+ coords: dict[str, object],
130
+ field_name: str,
131
+ values: Sequence[object | None],
132
+ ) -> None:
133
+ """Append one batch-stacked header data variable."""
134
+
135
+ present_values: list[object] = [value for value in values if value is not None]
136
+ first_value: object = present_values[0]
137
+ if isinstance(first_value, Mapping):
138
+ if not is_numeric_key_mapping(first_value):
139
+ raise InvalidConfigurationError(
140
+ f"Header field {field_name!r} is not supported by to_xarray()."
141
+ )
142
+ field_keys: list[object] = sorted(first_value, key=_field_key_sort_key)
143
+ present_mapping: object
144
+ for present_mapping in present_values[1:]:
145
+ if not isinstance(present_mapping, Mapping) or not is_numeric_key_mapping(
146
+ present_mapping
147
+ ):
148
+ raise InvalidConfigurationError(
149
+ f"Header field {field_name!r} mixes incompatible grouped/non-grouped shapes for to_xarray()."
150
+ )
151
+ if tuple(sorted(present_mapping, key=_field_key_sort_key)) != tuple(
152
+ field_keys
153
+ ):
154
+ raise InvalidConfigurationError(
155
+ f"Header field {field_name!r} mixes incompatible grouped field-index keys for to_xarray()."
156
+ )
157
+ arrays: list[np.ndarray] = [
158
+ _header_value_to_ndarray(
159
+ cast(Mapping[object, object], first_value)[field_key]
160
+ )
161
+ for field_key in field_keys
162
+ ]
163
+ first_shape: tuple[int, ...] = tuple(int(axis) for axis in arrays[0].shape)
164
+ field_key: object
165
+ for field_key in field_keys:
166
+ present_mapping_value: object
167
+ for present_mapping_value in present_values:
168
+ candidate_array: np.ndarray = _header_value_to_ndarray(
169
+ cast(Mapping[object, object], present_mapping_value)[field_key]
170
+ )
171
+ if tuple(int(axis) for axis in candidate_array.shape) != first_shape:
172
+ raise InvalidConfigurationError(
173
+ f"Header field {field_name!r} has inconsistent grouped value shapes for to_xarray()."
174
+ )
175
+ requires_padding: bool = any(value is None for value in values)
176
+ value_dtype: np.dtype[np.generic] = _tabular_column_dtype_for_padding(
177
+ arrays,
178
+ requires_padding=requires_padding,
179
+ )
180
+ stacked_shape: tuple[int, ...] = (len(values), len(field_keys)) + first_shape
181
+ grouped_stacked_array: np.ndarray
182
+ if requires_padding:
183
+ grouped_stacked_array = np.full(
184
+ stacked_shape,
185
+ np.nan,
186
+ dtype=value_dtype,
187
+ )
188
+ else:
189
+ grouped_stacked_array = np.empty(stacked_shape, dtype=value_dtype)
190
+ entry_position: int
191
+ for entry_position, grouped_entry_value in enumerate(values):
192
+ if grouped_entry_value is None:
193
+ continue
194
+ field_position: int
195
+ for field_position, field_key in enumerate(field_keys):
196
+ candidate_array = _header_value_to_ndarray(
197
+ cast(Mapping[object, object], grouped_entry_value)[field_key]
198
+ )
199
+ grouped_stacked_array[entry_position, field_position, ...] = (
200
+ candidate_array.astype(value_dtype, copy=False)
201
+ )
202
+ field_index_dim: str = f"{field_name}_field_index"
203
+ coords[field_index_dim] = list(field_keys)
204
+ dims: tuple[str, ...] = ("index", field_index_dim) + _header_value_dims(
205
+ field_name=field_name,
206
+ value_shape=first_shape,
207
+ )
208
+ data_vars[field_name] = (dims, grouped_stacked_array)
209
+ return
210
+
211
+ first_array: np.ndarray = _header_value_to_ndarray(first_value)
212
+ first_shape = tuple(int(axis) for axis in first_array.shape)
213
+ present_value: object
214
+ for present_value in present_values[1:]:
215
+ candidate_shape: tuple[int, ...] = tuple(
216
+ int(axis) for axis in _header_value_to_ndarray(present_value).shape
217
+ )
218
+ if candidate_shape != first_shape:
219
+ raise InvalidConfigurationError(
220
+ f"Header field {field_name!r} has inconsistent value shapes for to_xarray()."
221
+ )
222
+ requires_padding = any(value is None for value in values)
223
+ value_dtype = _tabular_column_dtype_for_padding(
224
+ [first_array],
225
+ requires_padding=requires_padding,
226
+ )
227
+ stacked_shape = (len(values),) + first_shape
228
+ scalar_or_tensor_stacked_array: np.ndarray
229
+ if requires_padding:
230
+ scalar_or_tensor_stacked_array = np.full(
231
+ stacked_shape,
232
+ np.nan,
233
+ dtype=value_dtype,
234
+ )
235
+ else:
236
+ scalar_or_tensor_stacked_array = np.empty(stacked_shape, dtype=value_dtype)
237
+ entry_position = 0
238
+ scalar_entry_value: object | None
239
+ for entry_position, scalar_entry_value in enumerate(values):
240
+ if scalar_entry_value is None:
241
+ continue
242
+ candidate_array = _header_value_to_ndarray(scalar_entry_value)
243
+ if candidate_array.ndim == 0:
244
+ scalar_or_tensor_stacked_array[entry_position] = candidate_array.astype(
245
+ value_dtype,
246
+ copy=False,
247
+ )
248
+ continue
249
+ scalar_or_tensor_stacked_array[entry_position, ...] = candidate_array.astype(
250
+ value_dtype,
251
+ copy=False,
252
+ )
253
+ dims = ("index",) + _header_value_dims(
254
+ field_name=field_name,
255
+ value_shape=first_shape,
256
+ )
257
+ if first_array.ndim == 0:
258
+ data_vars[field_name] = (("index",), scalar_or_tensor_stacked_array)
259
+ return
260
+ data_vars[field_name] = (dims, scalar_or_tensor_stacked_array)
261
+
262
+
263
+ def _header_value_to_ndarray(value: object) -> np.ndarray:
264
+ """Normalize one header value into an ndarray for xarray export."""
265
+
266
+ if isinstance(value, np.ndarray):
267
+ return value
268
+ if isinstance(value, (int, float, complex, bool, np.generic, str)):
269
+ return np.asarray(value)
270
+ raise InvalidConfigurationError(
271
+ f"Header value {value!r} is not supported by to_xarray()."
272
+ )
273
+
274
+
275
+ def _header_value_dims(
276
+ *,
277
+ field_name: str,
278
+ value_shape: tuple[int, ...],
279
+ ) -> tuple[str, ...]:
280
+ """Return dimension names for one header value shape."""
281
+
282
+ value_ndim: int = len(value_shape)
283
+ if value_ndim == 0:
284
+ return ()
285
+ if value_ndim == 1:
286
+ return ("component",)
287
+ if value_ndim == 2:
288
+ return ("row", "col")
289
+ return tuple(
290
+ f"{field_name}_dim_{dimension_index}" for dimension_index in range(value_ndim)
291
+ )
@@ -0,0 +1,99 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2001-2026 JCMwave GmbH
3
+
4
+ """Lazy runtime loading helpers for internal `xarray` exports."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from collections.abc import Mapping
9
+ from typing import Protocol, cast
10
+
11
+ from jcmsuite.exceptions import InvalidConfigurationError
12
+ from jcmsuite.results.internal.export.xarray.types import XarrayDataset, XarrayDataTree
13
+
14
+
15
+ class _DatasetFactory(Protocol):
16
+ def __call__(
17
+ self,
18
+ data_vars: Mapping[str, object],
19
+ coords: Mapping[str, object] | None = None,
20
+ attrs: Mapping[str, object] | None = None,
21
+ ) -> XarrayDataset: ...
22
+
23
+
24
+ class _XarrayModule(Protocol):
25
+ Dataset: _DatasetFactory
26
+
27
+
28
+ class _DataTreeFactory(Protocol):
29
+ def __call__(self, *args: object, **kwargs: object) -> XarrayDataTree: ...
30
+
31
+
32
+ class _DataTreeModule(Protocol):
33
+ DataTree: _DataTreeFactory
34
+
35
+
36
+ def _load_xarray_module() -> _XarrayModule:
37
+ """Load `xarray` lazily for internal dataset construction."""
38
+
39
+ try:
40
+ import xarray as xarray_module # pyright: ignore[reportMissingImports]
41
+ except ModuleNotFoundError as exc:
42
+ raise InvalidConfigurationError(
43
+ "xarray integration requires `xarray` to be installed."
44
+ ) from exc
45
+ return cast(_XarrayModule, xarray_module)
46
+
47
+
48
+ def _load_datatree_module() -> _DataTreeModule:
49
+ """Load `xarray.DataTree` lazily for public tree exports."""
50
+
51
+ try:
52
+ import xarray as xarray_module # pyright: ignore[reportMissingImports]
53
+ except ModuleNotFoundError as exc:
54
+ raise InvalidConfigurationError(
55
+ "xarray DataTree integration requires `xarray` to be installed."
56
+ ) from exc
57
+ if not hasattr(xarray_module, "DataTree"):
58
+ raise InvalidConfigurationError(
59
+ "xarray DataTree integration requires an xarray version that provides `DataTree`."
60
+ )
61
+ return cast(_DataTreeModule, xarray_module)
62
+
63
+
64
+ def _create_data_tree(
65
+ *,
66
+ datatree_module: _DataTreeModule,
67
+ dataset: XarrayDataset | None,
68
+ children: Mapping[str, XarrayDataTree] | None = None,
69
+ name: str | None = None,
70
+ ) -> XarrayDataTree:
71
+ """Build a `DataTree` across xarray constructor variants.
72
+
73
+ Older environments accept `data=` while newer ones accept `dataset=`.
74
+ Preserve both without forcing callers to branch on the installed xarray API.
75
+ """
76
+
77
+ normalized_children: Mapping[str, XarrayDataTree] | None = children or None
78
+
79
+ try:
80
+ return datatree_module.DataTree(
81
+ data=dataset,
82
+ children=normalized_children,
83
+ name=name,
84
+ )
85
+ except TypeError as exc:
86
+ if "unexpected keyword argument 'data'" not in str(exc):
87
+ raise
88
+
89
+ try:
90
+ return datatree_module.DataTree(
91
+ dataset=dataset,
92
+ children=normalized_children,
93
+ name=name,
94
+ )
95
+ except TypeError as exc:
96
+ if "unexpected keyword argument 'dataset'" not in str(exc):
97
+ raise
98
+
99
+ return datatree_module.DataTree(dataset, normalized_children, name)
@@ -0,0 +1,246 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2001-2026 JCMwave GmbH
3
+
4
+ """Shared low-level helpers for internal `xarray` exports."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from collections.abc import Sequence
9
+ from typing import cast
10
+
11
+ import numpy as np
12
+
13
+ from jcmsuite.exceptions import InvalidConfigurationError
14
+
15
+
16
+ def _ordered_union(sequences: Sequence[tuple[object, ...]]) -> tuple[object, ...]:
17
+ """Return a stable first-seen union of label tuples."""
18
+
19
+ seen: set[object] = set()
20
+ ordered: list[object] = []
21
+ sequence: tuple[object, ...]
22
+ label: object
23
+ for sequence in sequences:
24
+ for label in sequence:
25
+ if label in seen:
26
+ continue
27
+ seen.add(label)
28
+ ordered.append(label)
29
+ return tuple(ordered)
30
+
31
+
32
+ def _normalize_scalar_coord_value(value: object) -> object | None:
33
+ """Return a coordinate-safe scalar value or `None` when unsupported."""
34
+
35
+ if isinstance(value, np.ndarray):
36
+ if value.ndim == 0:
37
+ return cast(object, value[()])
38
+ return None
39
+ if isinstance(value, (str, bytes, bytearray, int, float, complex, bool)):
40
+ return value
41
+ return None
42
+
43
+
44
+ def _normalize_rectangular_coord_array_value(value: object) -> np.ndarray | None:
45
+ """Return a non-scalar ndarray for rectangular coord exports or `None`."""
46
+
47
+ if isinstance(value, (str, bytes, bytearray)):
48
+ return None
49
+ try:
50
+ array_value: np.ndarray = np.asarray(value)
51
+ except ValueError:
52
+ return None
53
+ if array_value.ndim == 0:
54
+ return None
55
+ return array_value
56
+
57
+
58
+ def _build_batch_coord_variable(
59
+ key_name: str,
60
+ values: Sequence[object],
61
+ ) -> tuple[tuple[str, ...], np.ndarray] | None:
62
+ """Build one batch coord variable from scalar or rectangular entry values."""
63
+
64
+ normalized_scalars: list[object] = []
65
+ value: object
66
+ for value in values:
67
+ normalized_scalar: object | None = _normalize_scalar_coord_value(value)
68
+ if normalized_scalar is None:
69
+ break
70
+ normalized_scalars.append(normalized_scalar)
71
+ else:
72
+ return ("index",), np.asarray(normalized_scalars)
73
+
74
+ rectangular_arrays: list[np.ndarray] = []
75
+ reference_shape: tuple[int, ...] | None = None
76
+ for value in values:
77
+ normalized_array: np.ndarray | None = _normalize_rectangular_coord_array_value(
78
+ value
79
+ )
80
+ if normalized_array is None:
81
+ return None
82
+ current_shape: tuple[int, ...] = tuple(
83
+ int(axis) for axis in normalized_array.shape
84
+ )
85
+ if reference_shape is None:
86
+ reference_shape = current_shape
87
+ elif current_shape != reference_shape:
88
+ return None
89
+ rectangular_arrays.append(normalized_array)
90
+ if reference_shape is None:
91
+ return None
92
+ try:
93
+ stacked_array: np.ndarray = np.stack(rectangular_arrays, axis=0)
94
+ except ValueError:
95
+ return None
96
+ coord_dims: tuple[str, ...] = ("index",) + tuple(
97
+ f"{key_name}_dim_{dimension_index}"
98
+ for dimension_index in range(stacked_array.ndim - 1)
99
+ )
100
+ return coord_dims, stacked_array
101
+
102
+
103
+ def _ensure_generated_companion_dim_coords(
104
+ coords: dict[str, object],
105
+ *,
106
+ coord_dims: tuple[str, ...],
107
+ coord_array: np.ndarray,
108
+ ) -> None:
109
+ """Populate coordinate labels for generated trailing companion dimensions."""
110
+
111
+ trailing_dim_name: str
112
+ trailing_dim_size: int
113
+ for trailing_dim_name, trailing_dim_size in zip(
114
+ coord_dims[1:],
115
+ coord_array.shape[1:],
116
+ ):
117
+ coords.setdefault(trailing_dim_name, list(range(int(trailing_dim_size))))
118
+
119
+
120
+ def _ensure_generated_value_dim_coords(
121
+ coords: dict[str, object],
122
+ *,
123
+ value_dims: tuple[str, ...],
124
+ value_array: np.ndarray,
125
+ ) -> None:
126
+ """Populate coordinate labels for generated grouped-value trailing dims."""
127
+
128
+ trailing_dim_name: str
129
+ trailing_dim_size: int
130
+ for trailing_dim_name, trailing_dim_size in zip(
131
+ value_dims[2:],
132
+ value_array.shape[2:],
133
+ ):
134
+ coords.setdefault(trailing_dim_name, list(range(int(trailing_dim_size))))
135
+
136
+
137
+ def _stack_sample_coordinate_arrays(
138
+ arrays: Sequence[np.ndarray],
139
+ *,
140
+ sample_count: int,
141
+ ) -> np.ndarray:
142
+ """Stack sample-aligned coordinate arrays along the batch axis."""
143
+
144
+ requires_padding: bool = any(
145
+ int(array.shape[0]) != sample_count for array in arrays
146
+ )
147
+ trailing_shape: tuple[int, ...] = tuple(int(axis) for axis in arrays[0].shape[1:])
148
+ array_value: np.ndarray
149
+ for array_value in arrays[1:]:
150
+ if tuple(int(axis) for axis in array_value.shape[1:]) != trailing_shape:
151
+ raise InvalidConfigurationError(
152
+ "Sample-aligned companion coordinates must share trailing dimensions for batch to_xarray() export."
153
+ )
154
+ dtype: np.dtype[np.generic] = _coordinate_dtype_for_padding(
155
+ arrays,
156
+ requires_padding=requires_padding,
157
+ )
158
+ stacked: np.ndarray
159
+ if requires_padding:
160
+ fill_value: object = np.nan if dtype != np.dtype(object) else None
161
+ stacked = np.full(
162
+ (len(arrays), sample_count) + trailing_shape,
163
+ fill_value,
164
+ dtype=dtype,
165
+ )
166
+ else:
167
+ stacked = np.empty((len(arrays), sample_count) + trailing_shape, dtype=dtype)
168
+ array_position: int
169
+ for array_position, array_value in enumerate(arrays):
170
+ local_count: int = int(array_value.shape[0])
171
+ stacked[array_position, :local_count, ...] = array_value.astype(
172
+ dtype,
173
+ copy=False,
174
+ )
175
+ return stacked
176
+
177
+
178
+ def _coordinate_dtype_for_padding(
179
+ arrays: Sequence[np.ndarray],
180
+ *,
181
+ requires_padding: bool,
182
+ ) -> np.dtype[np.generic]:
183
+ """Return a coordinate dtype that can represent optional padded values."""
184
+
185
+ candidate_dtype: np.dtype[np.generic] = np.result_type(*arrays)
186
+ if not requires_padding:
187
+ return candidate_dtype
188
+ if np.issubdtype(candidate_dtype, np.complexfloating):
189
+ return cast(np.dtype[np.generic], np.dtype(np.complex128))
190
+ if np.issubdtype(candidate_dtype, np.floating):
191
+ return candidate_dtype
192
+ if np.issubdtype(candidate_dtype, np.integer) or np.issubdtype(
193
+ candidate_dtype,
194
+ np.bool_,
195
+ ):
196
+ return cast(np.dtype[np.generic], np.dtype(np.float64))
197
+ return cast(np.dtype[np.generic], np.dtype(object))
198
+
199
+
200
+ def _field_key_sort_key(field_key: object) -> int | str:
201
+ """Sort field indices deterministically while preserving numeric order."""
202
+
203
+ if isinstance(field_key, int) and not isinstance(field_key, bool):
204
+ return field_key
205
+ if isinstance(field_key, str) and field_key.isdigit():
206
+ return int(field_key)
207
+ return str(field_key)
208
+
209
+
210
+ def _array_dtype_for_padding(
211
+ arrays: Sequence[np.ndarray],
212
+ *,
213
+ requires_padding: bool,
214
+ ) -> np.dtype[np.generic]:
215
+ """Return a dtype that can represent actual values and optional padding."""
216
+
217
+ candidate_dtype: np.dtype[np.generic] = np.result_type(*arrays)
218
+ if not requires_padding:
219
+ return candidate_dtype
220
+ if np.issubdtype(candidate_dtype, np.complexfloating):
221
+ return cast(np.dtype[np.generic], np.dtype(np.complex128))
222
+ if np.issubdtype(candidate_dtype, np.floating):
223
+ return candidate_dtype
224
+ return cast(np.dtype[np.generic], np.dtype(np.float64))
225
+
226
+
227
+ def _tabular_column_dtype_for_padding(
228
+ arrays: Sequence[np.ndarray],
229
+ *,
230
+ requires_padding: bool,
231
+ ) -> np.dtype[np.generic]:
232
+ """Return a dtype that can represent tabular values plus optional padding."""
233
+
234
+ candidate_dtype: np.dtype[np.generic] = np.result_type(*arrays)
235
+ if not requires_padding:
236
+ return candidate_dtype
237
+ if np.issubdtype(candidate_dtype, np.complexfloating):
238
+ return cast(np.dtype[np.generic], np.dtype(np.complex128))
239
+ if np.issubdtype(candidate_dtype, np.floating):
240
+ return candidate_dtype
241
+ if np.issubdtype(candidate_dtype, np.integer) or np.issubdtype(
242
+ candidate_dtype,
243
+ np.bool_,
244
+ ):
245
+ return cast(np.dtype[np.generic], np.dtype(np.float64))
246
+ return cast(np.dtype[np.generic], np.dtype(object))
@@ -0,0 +1,71 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2001-2026 JCMwave GmbH
3
+
4
+ """Xarray conversion for single-result metadata and value tables."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from collections.abc import Mapping
9
+ from pathlib import Path
10
+
11
+ from jcmsuite.results.internal.export.xarray.types import XarrayDataTree
12
+
13
+ from .runtime import _create_data_tree, _load_datatree_module, _load_xarray_module
14
+ from .tabular import tabular_payload_to_xarray_table, tabular_table_to_xarray_dataset
15
+
16
+
17
+ def computational_costs_to_xarray_dataset(
18
+ table: Mapping[object, object],
19
+ ) -> XarrayDataTree:
20
+ """Convert computational-cost values and title into a root-only tree."""
21
+
22
+ xarray_module = _load_xarray_module()
23
+ datatree_module = _load_datatree_module()
24
+ normalized_mapping: dict[object, object] = dict(table)
25
+ title_object: object | None = normalized_mapping.pop("title", None)
26
+ normalized_mapping.pop("header", None)
27
+ tabular_table = tabular_payload_to_xarray_table(
28
+ normalized_mapping,
29
+ payload_name="Computational-cost payload",
30
+ )
31
+ dataset = tabular_table_to_xarray_dataset(
32
+ tabular_table,
33
+ xarray_module=xarray_module,
34
+ )
35
+ if isinstance(title_object, str):
36
+ dataset.attrs["title"] = title_object
37
+ return _create_data_tree(datatree_module=datatree_module, dataset=dataset)
38
+
39
+
40
+ def solve_keys_to_xarray_dataset(
41
+ values: Mapping[str, object],
42
+ *,
43
+ source: Path | None,
44
+ ) -> XarrayDataTree:
45
+ """Convert representable project keys into root attributes."""
46
+
47
+ xarray_module = _load_xarray_module()
48
+ data: dict[str, object] = {}
49
+ key: str
50
+ value: object
51
+ for key, value in values.items():
52
+ if isinstance(value, (str, int, float, bool)) or value is None:
53
+ data[key] = value
54
+ elif isinstance(value, (list, tuple)) and all(
55
+ isinstance(item, (str, int, float, bool)) or item is None for item in value
56
+ ):
57
+ data[key] = value
58
+ else:
59
+ raise ValueError(
60
+ f"Solve key {key!r} has a value that cannot be represented honestly in xarray."
61
+ )
62
+ dataset = xarray_module.Dataset(
63
+ data_vars={},
64
+ attrs={"source": str(source) if source else ""},
65
+ )
66
+ for key, value in data.items():
67
+ dataset.attrs[key] = value
68
+ return _create_data_tree(
69
+ datatree_module=_load_datatree_module(),
70
+ dataset=dataset,
71
+ )