jcmsuite 7.4.2__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.
Potentially problematic release.
This version of jcmsuite might be problematic. Click here for more details.
- jcmsuite/__init__.py +22 -0
- jcmsuite/_build_info.py +4 -0
- jcmsuite/context/__init__.py +44 -0
- jcmsuite/context/interface_metadata.py +158 -0
- jcmsuite/context/models.py +213 -0
- jcmsuite/context/scope.py +210 -0
- jcmsuite/context/solver_context.py +569 -0
- jcmsuite/context/subprocess_tools.py +172 -0
- jcmsuite/contract.py +47 -0
- jcmsuite/daemon/__init__.py +19 -0
- jcmsuite/daemon/handler.py +925 -0
- jcmsuite/daemon/internal/__init__.py +4 -0
- jcmsuite/daemon/internal/bundle_protocol.py +64 -0
- jcmsuite/daemon/internal/handler_helpers.py +368 -0
- jcmsuite/daemon/internal/handler_resource_jobs.py +227 -0
- jcmsuite/daemon/internal/handler_wait.py +564 -0
- jcmsuite/daemon/models.py +349 -0
- jcmsuite/daemon/namespaces.py +250 -0
- jcmsuite/daemon/protocol.py +801 -0
- jcmsuite/daemon/resources.py +407 -0
- jcmsuite/daemon/scope.py +53 -0
- jcmsuite/daemon/transport.py +223 -0
- jcmsuite/editing/__init__.py +10 -0
- jcmsuite/editing/editor.py +274 -0
- jcmsuite/exceptions/__init__.py +32 -0
- jcmsuite/exceptions/errors.py +173 -0
- jcmsuite/geo/__init__.py +10 -0
- jcmsuite/geo/mesh.py +302 -0
- jcmsuite/info/__init__.py +10 -0
- jcmsuite/info/runtime_info.py +45 -0
- jcmsuite/internal/__init__.py +2 -0
- jcmsuite/internal/diagnostics.py +74 -0
- jcmsuite/internal/progress.py +80 -0
- jcmsuite/loaders/__init__.py +18 -0
- jcmsuite/loaders/blob_header.py +315 -0
- jcmsuite/loaders/cartesian_field_reader.py +249 -0
- jcmsuite/loaders/cartesian_fields.py +324 -0
- jcmsuite/loaders/nested_mapping.py +69 -0
- jcmsuite/loaders/powerflux.py +136 -0
- jcmsuite/loaders/table.py +637 -0
- jcmsuite/logging/__init__.py +22 -0
- jcmsuite/logging/runtime.py +210 -0
- jcmsuite/results/__init__.py +126 -0
- jcmsuite/results/artifacts.py +806 -0
- jcmsuite/results/discovery.py +82 -0
- jcmsuite/results/field_exports.py +1062 -0
- jcmsuite/results/field_payloads.py +453 -0
- jcmsuite/results/internal/__init__.py +4 -0
- jcmsuite/results/internal/export/__init__.py +4 -0
- jcmsuite/results/internal/export/common.py +56 -0
- jcmsuite/results/internal/export/pandas/__init__.py +4 -0
- jcmsuite/results/internal/export/pandas/common.py +165 -0
- jcmsuite/results/internal/export/pandas/payload.py +480 -0
- jcmsuite/results/internal/export/pandas/rows.py +484 -0
- jcmsuite/results/internal/export/preview.py +178 -0
- jcmsuite/results/internal/export/xarray/__init__.py +4 -0
- jcmsuite/results/internal/export/xarray/export.py +688 -0
- jcmsuite/results/internal/export/xarray/grouped.py +608 -0
- jcmsuite/results/internal/export/xarray/headers.py +290 -0
- jcmsuite/results/internal/export/xarray/runtime.py +99 -0
- jcmsuite/results/internal/export/xarray/shared.py +246 -0
- jcmsuite/results/internal/export/xarray/tabular.py +304 -0
- jcmsuite/results/internal/export/xarray/types.py +28 -0
- jcmsuite/results/internal/models/__init__.py +4 -0
- jcmsuite/results/internal/models/batch.py +1081 -0
- jcmsuite/results/internal/models/batch_postprocess.py +1728 -0
- jcmsuite/results/internal/models/bundle.py +343 -0
- jcmsuite/results/internal/models/core.py +556 -0
- jcmsuite/results/internal/models/submission.py +1157 -0
- jcmsuite/results/internal/resultbag/__init__.py +4 -0
- jcmsuite/results/internal/resultbag/access.py +489 -0
- jcmsuite/results/internal/resultbag/iteration.py +199 -0
- jcmsuite/results/internal/resultbag/query.py +226 -0
- jcmsuite/results/internal/resultbag/raw.py +407 -0
- jcmsuite/results/internal/resultbag/source_files.py +142 -0
- jcmsuite/results/internal/resultbag/store.py +881 -0
- jcmsuite/results/internal/resultbag/utils.py +258 -0
- jcmsuite/results/models.py +76 -0
- jcmsuite/results/opening.py +55 -0
- jcmsuite/results/pandas_export.py +325 -0
- jcmsuite/results/payloads.py +478 -0
- jcmsuite/results/postprocess.py +97 -0
- jcmsuite/results/postprocess_payloads.py +757 -0
- jcmsuite/results/postprocess_record.py +418 -0
- jcmsuite/results/resultbag.py +279 -0
- jcmsuite/results/resultbag_management.py +433 -0
- jcmsuite/results/structured_derivatives.py +387 -0
- jcmsuite/solve/__init__.py +10 -0
- jcmsuite/solve/daemon_bundle_staging.py +100 -0
- jcmsuite/solve/daemon_bundle_wait.py +89 -0
- jcmsuite/solve/orchestration.py +1576 -0
- jcmsuite/solve/orchestration_execution.py +180 -0
- jcmsuite/solve/orchestration_routing.py +128 -0
- jcmsuite/solve/orchestration_support.py +323 -0
- jcmsuite/solve/path_resolution.py +98 -0
- jcmsuite/solve/progress.py +20 -0
- jcmsuite/solve/solver.py +709 -0
- jcmsuite/solve/staging.py +264 -0
- jcmsuite/solve/types.py +25 -0
- jcmsuite/solve/working_dirs.py +227 -0
- jcmsuite/templates/__init__.py +11 -0
- jcmsuite/templates/converter.py +71 -0
- jcmsuite/templates/formatting.py +335 -0
- jcmsuite/templates/formatting_cli.py +47 -0
- jcmsuite/templates/rendering.py +666 -0
- jcmsuite/torch/__init__.py +25 -0
- jcmsuite/torch/autograd.py +488 -0
- jcmsuite/torch/coordinate_policy.py +82 -0
- jcmsuite/torch/core.py +312 -0
- jcmsuite/torch/results/__init__.py +51 -0
- jcmsuite/torch/types.py +84 -0
- jcmsuite/torch/validation.py +208 -0
- jcmsuite/torch/wrappers.py +4332 -0
- jcmsuite/view/__init__.py +10 -0
- jcmsuite/view/viewer.py +122 -0
- jcmsuite-7.4.2.dist-info/METADATA +180 -0
- jcmsuite-7.4.2.dist-info/RECORD +119 -0
- jcmsuite-7.4.2.dist-info/WHEEL +4 -0
- jcmsuite-7.4.2.dist-info/entry_points.txt +3 -0
|
@@ -0,0 +1,1062 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# Copyright (c) 2001-2026 JCMwave GmbH
|
|
3
|
+
|
|
4
|
+
"""Complete field export payloads and their navigation namespaces."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from collections.abc import Iterator, Mapping
|
|
9
|
+
from typing import Literal, Self, cast, overload
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
from ..exceptions import InvalidConfigurationError, UnsupportedExportError
|
|
14
|
+
from .field_payloads import _CoordinateTopology, resolve_coordinates
|
|
15
|
+
from .internal.export.xarray.runtime import (
|
|
16
|
+
_create_data_tree,
|
|
17
|
+
_load_datatree_module,
|
|
18
|
+
_load_xarray_module,
|
|
19
|
+
)
|
|
20
|
+
from .internal.export.xarray.types import XarrayDataset, XarrayDataTree
|
|
21
|
+
from .payloads import FieldExportPayload as FieldExportPayloadCapability
|
|
22
|
+
from .payloads import Source
|
|
23
|
+
|
|
24
|
+
_FieldView = Literal["complete", "base", "derivatives", "derivative"]
|
|
25
|
+
_FieldTransform = Literal["abs", "real", "imag", "phase"]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class FieldExportView(FieldExportPayloadCapability):
|
|
29
|
+
"""Select and export field data.
|
|
30
|
+
|
|
31
|
+
Parameters
|
|
32
|
+
----------
|
|
33
|
+
mapping : Mapping[object, object]
|
|
34
|
+
Dictionary that contains field values and grid coordinates.
|
|
35
|
+
source : str | Path | None, optional
|
|
36
|
+
Source file or storage origin associated with the field export.
|
|
37
|
+
derivative_name : str | None, optional
|
|
38
|
+
Name of the selected derivative.
|
|
39
|
+
selected_index : int | None, optional
|
|
40
|
+
Position of the selected field. If omitted, include all fields.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(
|
|
44
|
+
self,
|
|
45
|
+
mapping: Mapping[object, object],
|
|
46
|
+
*,
|
|
47
|
+
source: Source = None,
|
|
48
|
+
derivative_name: str | None = None,
|
|
49
|
+
selected_index: int | None = None,
|
|
50
|
+
) -> None:
|
|
51
|
+
from .field_payloads import is_field_export_payload
|
|
52
|
+
|
|
53
|
+
if not is_field_export_payload(mapping):
|
|
54
|
+
raise ValueError(
|
|
55
|
+
"Field payload must provide 'field' with Cartesian or polar grid keys."
|
|
56
|
+
)
|
|
57
|
+
self._mapping: Mapping[object, object] = mapping
|
|
58
|
+
self._source: Source = source
|
|
59
|
+
self._view: _FieldView = "complete"
|
|
60
|
+
self._derivative_name: str | None = derivative_name
|
|
61
|
+
self._selected_index: int | None = selected_index
|
|
62
|
+
self._derivative_pairs: Mapping[str, Mapping[str, str]] = (
|
|
63
|
+
_infer_field_derivative_pairs(mapping)
|
|
64
|
+
)
|
|
65
|
+
self._pair_source: Mapping[object, object] = mapping
|
|
66
|
+
|
|
67
|
+
def _projected(
|
|
68
|
+
self,
|
|
69
|
+
mapping: Mapping[object, object],
|
|
70
|
+
*,
|
|
71
|
+
source: Source,
|
|
72
|
+
view: _FieldView,
|
|
73
|
+
derivative_name: str | None = None,
|
|
74
|
+
selected_index: int | None = None,
|
|
75
|
+
) -> Self:
|
|
76
|
+
"""Construct a payload with private projection state."""
|
|
77
|
+
|
|
78
|
+
payload: Self = type(self)(
|
|
79
|
+
mapping,
|
|
80
|
+
source=source,
|
|
81
|
+
derivative_name=derivative_name,
|
|
82
|
+
selected_index=selected_index,
|
|
83
|
+
)
|
|
84
|
+
payload._view = view
|
|
85
|
+
payload._derivative_pairs = self._derivative_pairs
|
|
86
|
+
payload._pair_source = self._pair_source
|
|
87
|
+
return payload
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def source(self) -> Source:
|
|
91
|
+
"""Return the source file or storage origin.
|
|
92
|
+
|
|
93
|
+
Returns
|
|
94
|
+
-------
|
|
95
|
+
Source
|
|
96
|
+
Source file, storage origin, or `None` if unknown.
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
return self._source
|
|
100
|
+
|
|
101
|
+
def __iter__(self) -> Iterator[object]:
|
|
102
|
+
"""Iterate field-data names in the complete public view.
|
|
103
|
+
|
|
104
|
+
Returns
|
|
105
|
+
-------
|
|
106
|
+
Iterator[object]
|
|
107
|
+
Field-data names in the complete public view.
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
return iter(self.to_dict())
|
|
111
|
+
|
|
112
|
+
def __contains__(self, key: object) -> bool:
|
|
113
|
+
"""Return whether the complete public view contains ``key``.
|
|
114
|
+
|
|
115
|
+
Parameters
|
|
116
|
+
----------
|
|
117
|
+
key : object
|
|
118
|
+
Field-data name to find in the complete public view.
|
|
119
|
+
|
|
120
|
+
Returns
|
|
121
|
+
-------
|
|
122
|
+
bool
|
|
123
|
+
`True` if the key is available; otherwise, `False`.
|
|
124
|
+
"""
|
|
125
|
+
|
|
126
|
+
return key in self.to_dict()
|
|
127
|
+
|
|
128
|
+
def __len__(self) -> int:
|
|
129
|
+
"""Return the number of field-data names in the complete public view.
|
|
130
|
+
|
|
131
|
+
Returns
|
|
132
|
+
-------
|
|
133
|
+
int
|
|
134
|
+
Number of field-data names in the complete public view.
|
|
135
|
+
"""
|
|
136
|
+
|
|
137
|
+
return len(self.to_dict())
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def base(self) -> Self:
|
|
141
|
+
"""Return only the base fields.
|
|
142
|
+
|
|
143
|
+
Returns
|
|
144
|
+
-------
|
|
145
|
+
FieldExportPayload
|
|
146
|
+
New field selection that excludes derivatives.
|
|
147
|
+
"""
|
|
148
|
+
|
|
149
|
+
return self._projected(
|
|
150
|
+
self._mapping,
|
|
151
|
+
source=self._source,
|
|
152
|
+
view="base",
|
|
153
|
+
selected_index=self._selected_index,
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
@property
|
|
157
|
+
def derivatives(self) -> Self:
|
|
158
|
+
"""Return all available field derivatives.
|
|
159
|
+
|
|
160
|
+
Returns
|
|
161
|
+
-------
|
|
162
|
+
FieldExportPayload
|
|
163
|
+
New selection that contains the available derivatives.
|
|
164
|
+
|
|
165
|
+
Raises
|
|
166
|
+
------
|
|
167
|
+
UnsupportedExportError
|
|
168
|
+
If the current view applies a field transformation or represents
|
|
169
|
+
field intensity.
|
|
170
|
+
"""
|
|
171
|
+
|
|
172
|
+
self._ensure_derivative_access()
|
|
173
|
+
return self._projected(
|
|
174
|
+
self._mapping,
|
|
175
|
+
source=self._source,
|
|
176
|
+
view="derivatives",
|
|
177
|
+
derivative_name=self._derivative_name,
|
|
178
|
+
selected_index=self._selected_index,
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
def _ensure_derivative_access(self) -> None:
|
|
182
|
+
"""Validate derivative access for the current field view."""
|
|
183
|
+
|
|
184
|
+
return None
|
|
185
|
+
|
|
186
|
+
def keys(self) -> tuple[str, ...]:
|
|
187
|
+
"""Return the solver parameter names available for derivative selection.
|
|
188
|
+
|
|
189
|
+
On the field's derivative collection, the names select first
|
|
190
|
+
derivatives. After selecting a first derivative, call its
|
|
191
|
+
``derivatives.keys()`` to list available second-derivative directions.
|
|
192
|
+
These are solver parameter names, not Torch project keys.
|
|
193
|
+
|
|
194
|
+
Returns
|
|
195
|
+
-------
|
|
196
|
+
tuple[str, ...]
|
|
197
|
+
Available derivative names in source-file order, or an empty tuple
|
|
198
|
+
if the current selection provides no derivative lookup.
|
|
199
|
+
"""
|
|
200
|
+
|
|
201
|
+
if self._view not in {"derivatives", "complete"}:
|
|
202
|
+
return ()
|
|
203
|
+
if self._view == "derivatives" and self._derivative_name is not None:
|
|
204
|
+
return tuple(self._derivative_pairs.get(self._derivative_name, {}))
|
|
205
|
+
if self._view == "complete" and self._derivative_pairs:
|
|
206
|
+
return tuple(self._derivative_payloads())
|
|
207
|
+
return tuple(self._derivative_payloads())
|
|
208
|
+
|
|
209
|
+
@overload
|
|
210
|
+
def __getitem__(self, key: str) -> Self: ...
|
|
211
|
+
|
|
212
|
+
@overload
|
|
213
|
+
def __getitem__(self, key: object) -> object: ...
|
|
214
|
+
|
|
215
|
+
def __getitem__(self, key: object) -> object:
|
|
216
|
+
"""Select a derivative or read one dictionary value.
|
|
217
|
+
|
|
218
|
+
If this object came from `.derivatives`, a string selects one derivative.
|
|
219
|
+
Otherwise, `key` selects a value from the field dictionary.
|
|
220
|
+
|
|
221
|
+
Parameters
|
|
222
|
+
----------
|
|
223
|
+
key : object
|
|
224
|
+
Derivative name or dictionary key.
|
|
225
|
+
|
|
226
|
+
Returns
|
|
227
|
+
-------
|
|
228
|
+
FieldExportPayload | object
|
|
229
|
+
Selected derivative, or the value for the dictionary key.
|
|
230
|
+
|
|
231
|
+
Raises
|
|
232
|
+
------
|
|
233
|
+
TypeError
|
|
234
|
+
If a derivative selection does not use a string name.
|
|
235
|
+
KeyError
|
|
236
|
+
If the derivative name or dictionary key is not available.
|
|
237
|
+
"""
|
|
238
|
+
|
|
239
|
+
if self._view != "derivatives":
|
|
240
|
+
return self.to_dict()[key]
|
|
241
|
+
if not isinstance(key, str):
|
|
242
|
+
raise TypeError("Derivative names must be strings.")
|
|
243
|
+
if key not in self.keys():
|
|
244
|
+
# Keep direct selection of legacy flat raw branches available.
|
|
245
|
+
if self._derivative_name is None:
|
|
246
|
+
raw_branches: dict[str, Mapping[object, object]] = (
|
|
247
|
+
self._raw_derivative_payloads()
|
|
248
|
+
)
|
|
249
|
+
if key in raw_branches:
|
|
250
|
+
payload: Self = cast(
|
|
251
|
+
Self,
|
|
252
|
+
self._projected(
|
|
253
|
+
raw_branches[key],
|
|
254
|
+
source=self._source,
|
|
255
|
+
view="derivative",
|
|
256
|
+
derivative_name=key,
|
|
257
|
+
selected_index=self._selected_index,
|
|
258
|
+
),
|
|
259
|
+
)
|
|
260
|
+
if f"dd_field_{key}" in self._pair_source:
|
|
261
|
+
payload._derivative_pairs = {}
|
|
262
|
+
return payload
|
|
263
|
+
# Second-order branches are addressed relative to their first
|
|
264
|
+
# direction. Labels are matched as complete names, not split on
|
|
265
|
+
# underscores.
|
|
266
|
+
requested_path: str = (
|
|
267
|
+
key
|
|
268
|
+
if self._derivative_name is None
|
|
269
|
+
else f"{self._derivative_name}.{key}"
|
|
270
|
+
)
|
|
271
|
+
raise KeyError(f"Derivative path {requested_path!r} is unavailable.")
|
|
272
|
+
if self._derivative_name is not None:
|
|
273
|
+
pair_key: str = self._derivative_pairs[self._derivative_name][key]
|
|
274
|
+
raw: object = self._pair_source.get(pair_key)
|
|
275
|
+
if not isinstance(raw, Mapping):
|
|
276
|
+
raise KeyError(
|
|
277
|
+
f"Derivative path {self._derivative_name!r}.{key!r} is unavailable."
|
|
278
|
+
)
|
|
279
|
+
current_fields: tuple[object, ...] = self._field_entries(self._mapping)
|
|
280
|
+
second_fields: tuple[object, ...] = self._field_entries(raw)
|
|
281
|
+
if len(current_fields) != len(second_fields) or any(
|
|
282
|
+
np.asarray(first).shape != np.asarray(second).shape
|
|
283
|
+
for first, second in zip(current_fields, second_fields)
|
|
284
|
+
):
|
|
285
|
+
raise InvalidConfigurationError(
|
|
286
|
+
"Incompatible field shapes for derivative pair "
|
|
287
|
+
f"{self._derivative_name!r}, {key!r}."
|
|
288
|
+
)
|
|
289
|
+
payload = cast(
|
|
290
|
+
Self,
|
|
291
|
+
self._projected(
|
|
292
|
+
raw,
|
|
293
|
+
source=self._source,
|
|
294
|
+
view="derivative",
|
|
295
|
+
derivative_name=key,
|
|
296
|
+
selected_index=self._selected_index,
|
|
297
|
+
),
|
|
298
|
+
)
|
|
299
|
+
# A selected second-order value has no further ordinary derivative
|
|
300
|
+
# navigation level. Do not leak the root pair map.
|
|
301
|
+
payload._derivative_pairs = {}
|
|
302
|
+
return payload
|
|
303
|
+
return self._projected(
|
|
304
|
+
self._derivative_mapping(key),
|
|
305
|
+
source=self._source,
|
|
306
|
+
view="derivative",
|
|
307
|
+
derivative_name=key,
|
|
308
|
+
selected_index=self._selected_index,
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
@property
|
|
312
|
+
def indices(self) -> tuple[int, ...]:
|
|
313
|
+
"""Return the positions of the selected fields in source-file order.
|
|
314
|
+
|
|
315
|
+
Returns
|
|
316
|
+
-------
|
|
317
|
+
tuple[int, ...]
|
|
318
|
+
Selected field positions.
|
|
319
|
+
"""
|
|
320
|
+
|
|
321
|
+
count: int = len(self._field_entries(self._active_mapping()))
|
|
322
|
+
available: tuple[int, ...] = tuple(range(count))
|
|
323
|
+
if self._selected_index is None:
|
|
324
|
+
return available
|
|
325
|
+
return (self._selected_index,)
|
|
326
|
+
|
|
327
|
+
def select(self, index: int | None = None) -> Self:
|
|
328
|
+
"""Select one field by position.
|
|
329
|
+
|
|
330
|
+
Parameters
|
|
331
|
+
----------
|
|
332
|
+
index : int | None, optional
|
|
333
|
+
Field position to select. If omitted, select all fields.
|
|
334
|
+
|
|
335
|
+
Returns
|
|
336
|
+
-------
|
|
337
|
+
FieldExportPayload
|
|
338
|
+
New field selection. The original object does not change.
|
|
339
|
+
|
|
340
|
+
Raises
|
|
341
|
+
------
|
|
342
|
+
IndexError
|
|
343
|
+
If the selected position is not available.
|
|
344
|
+
"""
|
|
345
|
+
|
|
346
|
+
if index is None:
|
|
347
|
+
selected_index: int | None = None
|
|
348
|
+
else:
|
|
349
|
+
if index < 0 or index not in self.indices:
|
|
350
|
+
raise IndexError(
|
|
351
|
+
f"Field index {index} is not available: {self.indices}."
|
|
352
|
+
)
|
|
353
|
+
selected_index = index
|
|
354
|
+
return self._projected(
|
|
355
|
+
self._mapping,
|
|
356
|
+
source=self._source,
|
|
357
|
+
view=self._view,
|
|
358
|
+
derivative_name=self._derivative_name,
|
|
359
|
+
selected_index=selected_index,
|
|
360
|
+
)
|
|
361
|
+
|
|
362
|
+
def to_dict(self) -> Mapping[object, object]:
|
|
363
|
+
"""Return the selected field data as a dictionary.
|
|
364
|
+
|
|
365
|
+
Returns
|
|
366
|
+
-------
|
|
367
|
+
Mapping[object, object]
|
|
368
|
+
Selected coordinates, field values, and derivatives.
|
|
369
|
+
"""
|
|
370
|
+
|
|
371
|
+
if self._view == "complete":
|
|
372
|
+
return self._project_mapping(self._mapping)
|
|
373
|
+
if self._view == "base":
|
|
374
|
+
base_mapping: dict[object, object] = {
|
|
375
|
+
key: value
|
|
376
|
+
for key, value in self._mapping.items()
|
|
377
|
+
if not _is_derivative_key(key) and key != "derivatives"
|
|
378
|
+
}
|
|
379
|
+
return self._project_mapping(base_mapping)
|
|
380
|
+
if self._view == "derivatives":
|
|
381
|
+
derivatives: dict[str, object] = {
|
|
382
|
+
name: self._project_mapping(value)
|
|
383
|
+
for name, value in self._derivative_payloads().items()
|
|
384
|
+
}
|
|
385
|
+
result: dict[object, object] = {
|
|
386
|
+
key: value
|
|
387
|
+
for key, value in self._mapping.items()
|
|
388
|
+
if key not in {"field", "derivatives"} and not _is_derivative_key(key)
|
|
389
|
+
}
|
|
390
|
+
result["derivatives"] = derivatives
|
|
391
|
+
return result
|
|
392
|
+
if self._view == "derivative" and self._derivative_name is not None:
|
|
393
|
+
return self._project_mapping(self._mapping)
|
|
394
|
+
return dict(self._mapping)
|
|
395
|
+
|
|
396
|
+
def _preview(self) -> str:
|
|
397
|
+
"""Return internal field-navigation state without field values."""
|
|
398
|
+
|
|
399
|
+
active_mapping: Mapping[object, object] = self._active_mapping()
|
|
400
|
+
entries: tuple[object, ...] = self._field_entries(active_mapping)
|
|
401
|
+
field_shape: tuple[int, ...] = (
|
|
402
|
+
()
|
|
403
|
+
if not entries
|
|
404
|
+
else tuple(int(size) for size in np.asarray(entries[0]).shape)
|
|
405
|
+
)
|
|
406
|
+
coordinate_text: str = _field_coordinate_preview(active_mapping)
|
|
407
|
+
derivative_names: tuple[str, ...] = self.keys()
|
|
408
|
+
return "\n".join(
|
|
409
|
+
(
|
|
410
|
+
f" view: {self._view}",
|
|
411
|
+
f" indices: {self.indices}",
|
|
412
|
+
f" coordinates: {coordinate_text}",
|
|
413
|
+
f" field_shape: {field_shape}",
|
|
414
|
+
f" derivatives: {derivative_names}",
|
|
415
|
+
self._representation_preview(),
|
|
416
|
+
)
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
def __repr__(self) -> str:
|
|
420
|
+
"""Return field-navigation state without numerical field values."""
|
|
421
|
+
|
|
422
|
+
return f"FieldExportPayload(\n{self._preview()}\n)"
|
|
423
|
+
|
|
424
|
+
def to_xarray(self) -> XarrayDataTree:
|
|
425
|
+
"""Return the selected field data as an xarray `DataTree`.
|
|
426
|
+
|
|
427
|
+
The root node contains the selected base field or derivative. Other
|
|
428
|
+
derivatives are in child nodes. If the field export has an explicit
|
|
429
|
+
selection, the xarray export has no ``field_index`` dimension or
|
|
430
|
+
coordinate. If the field export is unselected, the xarray export
|
|
431
|
+
retains ``field_index`` for all available fields.
|
|
432
|
+
|
|
433
|
+
Returns
|
|
434
|
+
-------
|
|
435
|
+
xarray.DataTree
|
|
436
|
+
Selected field data and coordinates.
|
|
437
|
+
|
|
438
|
+
Raises
|
|
439
|
+
------
|
|
440
|
+
ValueError
|
|
441
|
+
If the selection contains no field data.
|
|
442
|
+
"""
|
|
443
|
+
|
|
444
|
+
if self._view in {"complete", "base", "derivative"}:
|
|
445
|
+
field_mapping: Mapping[object, object] = self.to_dict()
|
|
446
|
+
return self._indexed_tree(
|
|
447
|
+
field_mapping,
|
|
448
|
+
include_derivatives=self._view == "complete",
|
|
449
|
+
)
|
|
450
|
+
|
|
451
|
+
derivative_items: list[tuple[str, Mapping[object, object]]] = list(
|
|
452
|
+
(name, self._project_mapping(mapping))
|
|
453
|
+
for name, mapping in self._derivative_payloads().items()
|
|
454
|
+
)
|
|
455
|
+
if not derivative_items:
|
|
456
|
+
raise ValueError("Field export contains no derivative branches.")
|
|
457
|
+
root_name, root_mapping = derivative_items[0]
|
|
458
|
+
root = self._indexed_tree(root_mapping, include_derivatives=False)
|
|
459
|
+
children: dict[str, XarrayDataTree] = {}
|
|
460
|
+
for child_name, child_mapping in derivative_items[1:]:
|
|
461
|
+
children[child_name] = self._indexed_tree(
|
|
462
|
+
child_mapping,
|
|
463
|
+
include_derivatives=False,
|
|
464
|
+
)
|
|
465
|
+
if not children:
|
|
466
|
+
return root
|
|
467
|
+
root_dataset = getattr(root, "ds", None)
|
|
468
|
+
return _create_data_tree(
|
|
469
|
+
datatree_module=_load_datatree_module(),
|
|
470
|
+
dataset=root_dataset,
|
|
471
|
+
children=children,
|
|
472
|
+
name=root_name,
|
|
473
|
+
)
|
|
474
|
+
|
|
475
|
+
def _derivative_payloads(self) -> dict[str, Mapping[object, object]]:
|
|
476
|
+
if self._view == "derivatives" and self._derivative_name is not None:
|
|
477
|
+
selected_pairs: dict[str, Mapping[object, object]] = {}
|
|
478
|
+
for direction, branch in self._derivative_pairs.get(
|
|
479
|
+
self._derivative_name, {}
|
|
480
|
+
).items():
|
|
481
|
+
payload: object = self._pair_source.get(branch)
|
|
482
|
+
if isinstance(payload, Mapping):
|
|
483
|
+
selected_pairs[direction] = payload
|
|
484
|
+
return selected_pairs
|
|
485
|
+
if self._view == "derivatives" and self._derivative_pairs:
|
|
486
|
+
first_order: dict[str, Mapping[object, object]] = {}
|
|
487
|
+
for key, value in self._mapping.items():
|
|
488
|
+
if (
|
|
489
|
+
isinstance(key, str)
|
|
490
|
+
and key.startswith("d_field_")
|
|
491
|
+
and isinstance(value, Mapping)
|
|
492
|
+
):
|
|
493
|
+
first_order[key.removeprefix("d_field_")] = value
|
|
494
|
+
return first_order
|
|
495
|
+
return self._raw_derivative_payloads()
|
|
496
|
+
|
|
497
|
+
def _raw_derivative_payloads(self) -> dict[str, Mapping[object, object]]:
|
|
498
|
+
"""Collect source branches without immediate-direction filtering."""
|
|
499
|
+
|
|
500
|
+
explicit_derivatives: object = self._mapping.get("derivatives")
|
|
501
|
+
if isinstance(explicit_derivatives, Mapping):
|
|
502
|
+
return {
|
|
503
|
+
name: value
|
|
504
|
+
for name, value in explicit_derivatives.items()
|
|
505
|
+
if isinstance(name, str) and isinstance(value, Mapping)
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
from .field_payloads import _collect_derivative_payloads
|
|
509
|
+
|
|
510
|
+
return _collect_derivative_payloads(self._mapping)
|
|
511
|
+
|
|
512
|
+
def _derivative_mapping(self, name: str) -> Mapping[object, object]:
|
|
513
|
+
return self._derivative_payloads()[name]
|
|
514
|
+
|
|
515
|
+
def _active_mapping(self) -> Mapping[object, object]:
|
|
516
|
+
if self._view == "derivative" and self._derivative_name is not None:
|
|
517
|
+
return self._mapping
|
|
518
|
+
if self._view == "derivatives":
|
|
519
|
+
derivative_items: tuple[Mapping[object, object], ...] = tuple(
|
|
520
|
+
self._derivative_payloads().values()
|
|
521
|
+
)
|
|
522
|
+
return derivative_items[0] if derivative_items else {}
|
|
523
|
+
return self._mapping
|
|
524
|
+
|
|
525
|
+
def _project_mapping(
|
|
526
|
+
self, mapping: Mapping[object, object]
|
|
527
|
+
) -> dict[object, object]:
|
|
528
|
+
projected: dict[object, object] = dict(mapping)
|
|
529
|
+
if self._selected_index is None:
|
|
530
|
+
return projected
|
|
531
|
+
if self._selected_index is not None:
|
|
532
|
+
field_entries: tuple[object, ...] = self._field_entries(mapping)
|
|
533
|
+
position: int = self._selected_index
|
|
534
|
+
projected["field"] = field_entries[position]
|
|
535
|
+
if "derivatives" in projected and isinstance(projected["derivatives"], Mapping):
|
|
536
|
+
projected["derivatives"] = {
|
|
537
|
+
name: (
|
|
538
|
+
self._project_mapping(value)
|
|
539
|
+
if isinstance(value, Mapping)
|
|
540
|
+
else value
|
|
541
|
+
)
|
|
542
|
+
for name, value in projected["derivatives"].items()
|
|
543
|
+
}
|
|
544
|
+
for key, value in tuple(projected.items()):
|
|
545
|
+
if _is_derivative_key(key) and isinstance(value, Mapping):
|
|
546
|
+
projected[key] = self._project_mapping(value)
|
|
547
|
+
return projected
|
|
548
|
+
|
|
549
|
+
def _representation_preview(self) -> str:
|
|
550
|
+
"""Return the derived-representation state for previews."""
|
|
551
|
+
|
|
552
|
+
return " representation: field"
|
|
553
|
+
|
|
554
|
+
def _indexed_tree(
|
|
555
|
+
self,
|
|
556
|
+
mapping: Mapping[object, object],
|
|
557
|
+
*,
|
|
558
|
+
include_derivatives: bool,
|
|
559
|
+
) -> XarrayDataTree:
|
|
560
|
+
from .field_payloads import _build_field_data
|
|
561
|
+
|
|
562
|
+
entries: tuple[object, ...] = self._field_entries(mapping)
|
|
563
|
+
if not entries:
|
|
564
|
+
raise ValueError("Field export contains no field entries.")
|
|
565
|
+
visible_indices: tuple[int, ...] = self.indices
|
|
566
|
+
fields: list[np.ndarray] = []
|
|
567
|
+
first_data = None
|
|
568
|
+
for position in range(len(entries)):
|
|
569
|
+
data = _build_field_data(
|
|
570
|
+
mapping,
|
|
571
|
+
field_index=position,
|
|
572
|
+
title=self._title(mapping),
|
|
573
|
+
include_derivatives=False,
|
|
574
|
+
)
|
|
575
|
+
if first_data is None:
|
|
576
|
+
first_data = data
|
|
577
|
+
fields.append(self._export_field_values(np.asarray(data.field)))
|
|
578
|
+
assert first_data is not None
|
|
579
|
+
has_selected_field: bool = self._selected_index is not None
|
|
580
|
+
field_values: np.ndarray = (
|
|
581
|
+
fields[0] if has_selected_field else np.stack(fields, axis=0)
|
|
582
|
+
)
|
|
583
|
+
grid_value: object = mapping.get("grid")
|
|
584
|
+
grid_mapping: Mapping[object, object] | None = (
|
|
585
|
+
grid_value if isinstance(grid_value, Mapping) else None
|
|
586
|
+
)
|
|
587
|
+
tree: XarrayDataTree = _field_data_to_tree(
|
|
588
|
+
coordinates=first_data.coordinates,
|
|
589
|
+
field=field_values,
|
|
590
|
+
component_labels=first_data.component_labels,
|
|
591
|
+
title=first_data.title,
|
|
592
|
+
field_indices=visible_indices,
|
|
593
|
+
include_field_index=not has_selected_field,
|
|
594
|
+
grid=grid_mapping,
|
|
595
|
+
)
|
|
596
|
+
if not include_derivatives:
|
|
597
|
+
return tree
|
|
598
|
+
children: dict[str, XarrayDataTree] = {}
|
|
599
|
+
for name, child_mapping in self._derivative_payloads().items():
|
|
600
|
+
children[name] = self._indexed_tree(
|
|
601
|
+
self._project_mapping(child_mapping),
|
|
602
|
+
include_derivatives=False,
|
|
603
|
+
)
|
|
604
|
+
if not children:
|
|
605
|
+
return tree
|
|
606
|
+
return _create_data_tree(
|
|
607
|
+
datatree_module=_load_datatree_module(),
|
|
608
|
+
dataset=getattr(tree, "ds", None),
|
|
609
|
+
children=children,
|
|
610
|
+
)
|
|
611
|
+
|
|
612
|
+
def _export_field_values(self, field: np.ndarray) -> np.ndarray:
|
|
613
|
+
"""Return field values in the active representation."""
|
|
614
|
+
|
|
615
|
+
return field
|
|
616
|
+
|
|
617
|
+
@staticmethod
|
|
618
|
+
def _field_entries(mapping: Mapping[object, object]) -> tuple[object, ...]:
|
|
619
|
+
field_value: object = mapping.get("field")
|
|
620
|
+
if isinstance(field_value, (list, tuple)):
|
|
621
|
+
return tuple(field_value)
|
|
622
|
+
if isinstance(field_value, np.ndarray):
|
|
623
|
+
return (field_value,)
|
|
624
|
+
return ()
|
|
625
|
+
|
|
626
|
+
@staticmethod
|
|
627
|
+
def _title(mapping: Mapping[object, object]) -> str | None:
|
|
628
|
+
title: object | None = mapping.get("title")
|
|
629
|
+
return title if isinstance(title, str) else None
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
class FieldExportPayload(FieldExportView):
|
|
633
|
+
"""Select, transform, and export field data.
|
|
634
|
+
|
|
635
|
+
Parameters
|
|
636
|
+
----------
|
|
637
|
+
mapping : Mapping[object, object]
|
|
638
|
+
Dictionary that contains field values and grid coordinates.
|
|
639
|
+
source : Source, optional
|
|
640
|
+
Source file or storage origin associated with the field export.
|
|
641
|
+
derivative_name : str | None, optional
|
|
642
|
+
Name of the selected field derivative.
|
|
643
|
+
selected_index : int | None, optional
|
|
644
|
+
Position of the selected field. If omitted, include all fields.
|
|
645
|
+
transforms : tuple[str, ...], optional
|
|
646
|
+
Mathematical changes to apply to field values. Use `transform(...)`
|
|
647
|
+
instead of setting this option.
|
|
648
|
+
"""
|
|
649
|
+
|
|
650
|
+
def __init__(
|
|
651
|
+
self,
|
|
652
|
+
mapping: Mapping[object, object],
|
|
653
|
+
*,
|
|
654
|
+
source: Source = None,
|
|
655
|
+
derivative_name: str | None = None,
|
|
656
|
+
selected_index: int | None = None,
|
|
657
|
+
transforms: tuple[_FieldTransform, ...] = (),
|
|
658
|
+
) -> None:
|
|
659
|
+
super().__init__(
|
|
660
|
+
mapping,
|
|
661
|
+
source=source,
|
|
662
|
+
derivative_name=derivative_name,
|
|
663
|
+
selected_index=selected_index,
|
|
664
|
+
)
|
|
665
|
+
self._transforms: tuple[_FieldTransform, ...] = transforms
|
|
666
|
+
|
|
667
|
+
def _projected(
|
|
668
|
+
self,
|
|
669
|
+
mapping: Mapping[object, object],
|
|
670
|
+
*,
|
|
671
|
+
source: Source,
|
|
672
|
+
view: _FieldView,
|
|
673
|
+
derivative_name: str | None = None,
|
|
674
|
+
selected_index: int | None = None,
|
|
675
|
+
) -> Self:
|
|
676
|
+
"""Construct a transformable payload with retained transforms."""
|
|
677
|
+
|
|
678
|
+
payload: Self = type(self)(
|
|
679
|
+
mapping,
|
|
680
|
+
source=source,
|
|
681
|
+
derivative_name=derivative_name,
|
|
682
|
+
selected_index=selected_index,
|
|
683
|
+
transforms=self._transforms,
|
|
684
|
+
)
|
|
685
|
+
payload._view = view
|
|
686
|
+
payload._derivative_pairs = self._derivative_pairs
|
|
687
|
+
payload._pair_source = self._pair_source
|
|
688
|
+
return payload
|
|
689
|
+
|
|
690
|
+
@property
|
|
691
|
+
def intensity(self) -> "IntensityFieldExportPayload":
|
|
692
|
+
"""Return the squared-norm intensity field view.
|
|
693
|
+
|
|
694
|
+
Returns
|
|
695
|
+
-------
|
|
696
|
+
IntensityFieldExportPayload
|
|
697
|
+
Non-transformable view with real scalar field values.
|
|
698
|
+
"""
|
|
699
|
+
|
|
700
|
+
return IntensityFieldExportPayload._from_view(self)
|
|
701
|
+
|
|
702
|
+
def transform(self, name: str) -> Self:
|
|
703
|
+
"""Apply a mathematical change to the field values.
|
|
704
|
+
|
|
705
|
+
Parameters
|
|
706
|
+
----------
|
|
707
|
+
name : {"abs", "real", "imag", "phase"}
|
|
708
|
+
Change to apply. `"abs"` gives the magnitude. `"real"` and
|
|
709
|
+
`"imag"` give the real and imaginary parts. `"phase"` gives the
|
|
710
|
+
phase angle in radians.
|
|
711
|
+
|
|
712
|
+
Returns
|
|
713
|
+
-------
|
|
714
|
+
FieldExportPayload
|
|
715
|
+
New field data with the change applied. The original object does
|
|
716
|
+
not change.
|
|
717
|
+
|
|
718
|
+
Notes
|
|
719
|
+
-----
|
|
720
|
+
The transformed view does not expose ``derivatives``. The available
|
|
721
|
+
solver derivatives describe the bare field, not the transformed field.
|
|
722
|
+
"""
|
|
723
|
+
|
|
724
|
+
if name not in {"abs", "real", "imag", "phase"}:
|
|
725
|
+
raise ValueError(
|
|
726
|
+
"transform must be one of 'abs', 'real', 'imag', or 'phase'"
|
|
727
|
+
)
|
|
728
|
+
transform_name: _FieldTransform = cast(_FieldTransform, name)
|
|
729
|
+
payload: Self = self._projected(
|
|
730
|
+
self._mapping,
|
|
731
|
+
source=self._source,
|
|
732
|
+
view=self._view,
|
|
733
|
+
derivative_name=self._derivative_name,
|
|
734
|
+
selected_index=self._selected_index,
|
|
735
|
+
)
|
|
736
|
+
payload._transforms = (*self._transforms, transform_name)
|
|
737
|
+
return payload
|
|
738
|
+
|
|
739
|
+
def _ensure_derivative_access(self) -> None:
|
|
740
|
+
"""Reject derivatives after a field transform."""
|
|
741
|
+
|
|
742
|
+
if self._transforms:
|
|
743
|
+
raise UnsupportedExportError(
|
|
744
|
+
"Derivatives are not available for transformed field views."
|
|
745
|
+
)
|
|
746
|
+
|
|
747
|
+
def _project_mapping(
|
|
748
|
+
self, mapping: Mapping[object, object]
|
|
749
|
+
) -> dict[object, object]:
|
|
750
|
+
projected: dict[object, object] = super()._project_mapping(mapping)
|
|
751
|
+
if not self._transforms:
|
|
752
|
+
return projected
|
|
753
|
+
projected["field"] = self._transform_field_value(projected["field"])
|
|
754
|
+
for key, value in tuple(projected.items()):
|
|
755
|
+
if _is_derivative_key(key) and isinstance(value, Mapping):
|
|
756
|
+
projected[key] = self._project_mapping(value)
|
|
757
|
+
derivatives: object | None = projected.get("derivatives")
|
|
758
|
+
if isinstance(derivatives, Mapping):
|
|
759
|
+
projected["derivatives"] = {
|
|
760
|
+
name: (
|
|
761
|
+
self._project_mapping(value)
|
|
762
|
+
if isinstance(value, Mapping)
|
|
763
|
+
else value
|
|
764
|
+
)
|
|
765
|
+
for name, value in derivatives.items()
|
|
766
|
+
}
|
|
767
|
+
return projected
|
|
768
|
+
|
|
769
|
+
def _transform_field_value(self, value: object) -> object:
|
|
770
|
+
if isinstance(value, (list, tuple)):
|
|
771
|
+
return [self._transform_array(entry) for entry in value]
|
|
772
|
+
return self._transform_array(value)
|
|
773
|
+
|
|
774
|
+
def _transform_array(self, value: object) -> np.ndarray:
|
|
775
|
+
transformed: np.ndarray = np.asarray(value)
|
|
776
|
+
for transform_name in self._transforms:
|
|
777
|
+
if transform_name == "abs":
|
|
778
|
+
transformed = np.asarray(np.abs(transformed))
|
|
779
|
+
elif transform_name == "real":
|
|
780
|
+
transformed = np.asarray(np.real(transformed))
|
|
781
|
+
elif transform_name == "imag":
|
|
782
|
+
transformed = np.asarray(np.imag(transformed))
|
|
783
|
+
else:
|
|
784
|
+
transformed = np.asarray(np.angle(transformed))
|
|
785
|
+
return transformed
|
|
786
|
+
|
|
787
|
+
def _representation_preview(self) -> str:
|
|
788
|
+
"""Return transform state for previews."""
|
|
789
|
+
|
|
790
|
+
return f" transforms: {self._transforms}"
|
|
791
|
+
|
|
792
|
+
|
|
793
|
+
class IntensityFieldExportPayload(FieldExportView):
|
|
794
|
+
"""Navigate and export squared-norm field intensity.
|
|
795
|
+
|
|
796
|
+
Access this view through `FieldExportPayload.intensity`. For a scalar
|
|
797
|
+
field, the view exports the squared absolute value. For a vector field,
|
|
798
|
+
the view exports the sum of squared absolute component values. The xarray
|
|
799
|
+
export is real-valued and has no `component` dimension.
|
|
800
|
+
|
|
801
|
+
The view supports base-field and field selection. It does not support
|
|
802
|
+
`transform(...)` or `derivatives` because its values are transformed field data.
|
|
803
|
+
"""
|
|
804
|
+
|
|
805
|
+
@classmethod
|
|
806
|
+
def _from_view(cls, field: FieldExportView) -> "IntensityFieldExportPayload":
|
|
807
|
+
"""Create an intensity view from an existing field view."""
|
|
808
|
+
|
|
809
|
+
payload = cls(
|
|
810
|
+
field._mapping,
|
|
811
|
+
source=field._source,
|
|
812
|
+
derivative_name=field._derivative_name,
|
|
813
|
+
selected_index=field._selected_index,
|
|
814
|
+
)
|
|
815
|
+
payload._view = field._view
|
|
816
|
+
return payload
|
|
817
|
+
|
|
818
|
+
def _project_mapping(
|
|
819
|
+
self, mapping: Mapping[object, object]
|
|
820
|
+
) -> dict[object, object]:
|
|
821
|
+
projected: dict[object, object] = super()._project_mapping(mapping)
|
|
822
|
+
grid_rank: int = len(resolve_coordinates(mapping).grid_shape)
|
|
823
|
+
projected["field"] = self._intensity_field_value(
|
|
824
|
+
projected["field"], grid_rank=grid_rank
|
|
825
|
+
)
|
|
826
|
+
for key, value in tuple(projected.items()):
|
|
827
|
+
if _is_derivative_key(key) and isinstance(value, Mapping):
|
|
828
|
+
projected[key] = self._project_mapping(value)
|
|
829
|
+
derivatives: object | None = projected.get("derivatives")
|
|
830
|
+
if isinstance(derivatives, Mapping):
|
|
831
|
+
projected["derivatives"] = {
|
|
832
|
+
name: (
|
|
833
|
+
self._project_mapping(value)
|
|
834
|
+
if isinstance(value, Mapping)
|
|
835
|
+
else value
|
|
836
|
+
)
|
|
837
|
+
for name, value in derivatives.items()
|
|
838
|
+
}
|
|
839
|
+
return projected
|
|
840
|
+
|
|
841
|
+
@staticmethod
|
|
842
|
+
def _intensity_field_value(value: object, *, grid_rank: int) -> object:
|
|
843
|
+
if isinstance(value, (list, tuple)):
|
|
844
|
+
return [
|
|
845
|
+
IntensityFieldExportPayload._intensity_array(entry, grid_rank=grid_rank)
|
|
846
|
+
for entry in value
|
|
847
|
+
]
|
|
848
|
+
return IntensityFieldExportPayload._intensity_array(value, grid_rank=grid_rank)
|
|
849
|
+
|
|
850
|
+
@staticmethod
|
|
851
|
+
def _intensity_array(value: object, *, grid_rank: int) -> np.ndarray:
|
|
852
|
+
field: np.ndarray = np.asarray(value)
|
|
853
|
+
if field.ndim == grid_rank + 1:
|
|
854
|
+
return np.asarray(np.sum(np.abs(field) ** 2, axis=-1))
|
|
855
|
+
return np.asarray(np.abs(field) ** 2)
|
|
856
|
+
|
|
857
|
+
def _representation_preview(self) -> str:
|
|
858
|
+
"""Return intensity state for previews."""
|
|
859
|
+
|
|
860
|
+
return " representation: intensity"
|
|
861
|
+
|
|
862
|
+
def _ensure_derivative_access(self) -> None:
|
|
863
|
+
"""Reject derivatives for intensity views."""
|
|
864
|
+
|
|
865
|
+
raise UnsupportedExportError(
|
|
866
|
+
"Derivatives are not available for intensity field views."
|
|
867
|
+
)
|
|
868
|
+
|
|
869
|
+
|
|
870
|
+
def _is_derivative_key(key: object) -> bool:
|
|
871
|
+
return isinstance(key, str) and (
|
|
872
|
+
key.startswith("d_")
|
|
873
|
+
or key.startswith("dd_")
|
|
874
|
+
or key.startswith("d_field_")
|
|
875
|
+
or key.startswith("dd_field_")
|
|
876
|
+
)
|
|
877
|
+
|
|
878
|
+
|
|
879
|
+
def _infer_field_derivative_pairs(
|
|
880
|
+
mapping: Mapping[object, object],
|
|
881
|
+
) -> dict[str, dict[str, str]]:
|
|
882
|
+
"""Resolve serialized pair labels against declared first-order branches.
|
|
883
|
+
|
|
884
|
+
Matching complete labels avoids guessing where underscores divide the two
|
|
885
|
+
solver parameter names. More than one exact match is invalid metadata.
|
|
886
|
+
"""
|
|
887
|
+
|
|
888
|
+
parameter_names: tuple[str, ...] = tuple(
|
|
889
|
+
key.removeprefix("d_field_")
|
|
890
|
+
for key, value in mapping.items()
|
|
891
|
+
if isinstance(key, str)
|
|
892
|
+
and key.startswith("d_field_")
|
|
893
|
+
and isinstance(value, Mapping)
|
|
894
|
+
)
|
|
895
|
+
pairs: dict[str, dict[str, str]] = {}
|
|
896
|
+
second_order_keys: tuple[str, ...] = tuple(
|
|
897
|
+
key
|
|
898
|
+
for key, value in mapping.items()
|
|
899
|
+
if isinstance(key, str)
|
|
900
|
+
and key.startswith("dd_field_")
|
|
901
|
+
and isinstance(value, Mapping)
|
|
902
|
+
)
|
|
903
|
+
pair_branches: dict[tuple[str, str], list[str]] = {}
|
|
904
|
+
for branch in second_order_keys:
|
|
905
|
+
suffix: str = branch.removeprefix("dd_field_")
|
|
906
|
+
candidates: set[tuple[str, str]] = {
|
|
907
|
+
(first, second) if first <= second else (second, first)
|
|
908
|
+
for first in parameter_names
|
|
909
|
+
for second in parameter_names
|
|
910
|
+
if f"{first}_{second}" == suffix
|
|
911
|
+
}
|
|
912
|
+
if len(candidates) > 1:
|
|
913
|
+
raise InvalidConfigurationError(
|
|
914
|
+
f"Ambiguous second-order field branch identity {branch!r}."
|
|
915
|
+
)
|
|
916
|
+
if not candidates:
|
|
917
|
+
continue
|
|
918
|
+
pair: tuple[str, str] = next(iter(candidates))
|
|
919
|
+
pair_branches.setdefault(pair, []).append(branch)
|
|
920
|
+
|
|
921
|
+
for pair, branches in pair_branches.items():
|
|
922
|
+
selected_branch: str = min(branches)
|
|
923
|
+
if len(branches) > 1:
|
|
924
|
+
reference_entries: tuple[object, ...] = FieldExportView._field_entries(
|
|
925
|
+
cast(Mapping[object, object], mapping[selected_branch])
|
|
926
|
+
)
|
|
927
|
+
for branch in branches:
|
|
928
|
+
branch_payload: object = mapping[branch]
|
|
929
|
+
if not isinstance(branch_payload, Mapping):
|
|
930
|
+
raise InvalidConfigurationError(
|
|
931
|
+
f"Incompatible symmetric second-order field branches for {pair!r}."
|
|
932
|
+
)
|
|
933
|
+
branch_entries: tuple[object, ...] = FieldExportView._field_entries(
|
|
934
|
+
branch_payload
|
|
935
|
+
)
|
|
936
|
+
if len(reference_entries) != len(branch_entries) or any(
|
|
937
|
+
np.asarray(reference).shape != np.asarray(candidate).shape
|
|
938
|
+
for reference, candidate in zip(reference_entries, branch_entries)
|
|
939
|
+
):
|
|
940
|
+
raise InvalidConfigurationError(
|
|
941
|
+
f"Incompatible symmetric second-order field branches for {pair!r}."
|
|
942
|
+
)
|
|
943
|
+
if any(
|
|
944
|
+
not np.array_equal(
|
|
945
|
+
np.asarray(reference), np.asarray(candidate), equal_nan=True
|
|
946
|
+
)
|
|
947
|
+
for reference, candidate in zip(reference_entries, branch_entries)
|
|
948
|
+
):
|
|
949
|
+
raise InvalidConfigurationError(
|
|
950
|
+
f"Conflicting symmetric second-order field branches for {pair!r}."
|
|
951
|
+
)
|
|
952
|
+
first, second = pair
|
|
953
|
+
pairs.setdefault(first, {})[second] = selected_branch
|
|
954
|
+
pairs.setdefault(second, {})[first] = selected_branch
|
|
955
|
+
return pairs
|
|
956
|
+
|
|
957
|
+
|
|
958
|
+
def _field_coordinate_preview(mapping: Mapping[object, object]) -> str:
|
|
959
|
+
"""Return coordinate names and dimensions without materializing values."""
|
|
960
|
+
|
|
961
|
+
coordinate_names: tuple[str, ...] = tuple(
|
|
962
|
+
name for name in ("X", "Y", "Z", "R", "Theta", "Phi") if name in mapping
|
|
963
|
+
)
|
|
964
|
+
if not coordinate_names:
|
|
965
|
+
return "<unknown>"
|
|
966
|
+
return ", ".join(
|
|
967
|
+
f"{name}={tuple(int(size) for size in np.asarray(mapping[name]).shape)}"
|
|
968
|
+
for name in coordinate_names
|
|
969
|
+
)
|
|
970
|
+
|
|
971
|
+
|
|
972
|
+
def _field_data_to_tree(
|
|
973
|
+
*,
|
|
974
|
+
coordinates: _CoordinateTopology,
|
|
975
|
+
field: np.ndarray,
|
|
976
|
+
component_labels: tuple[str, ...],
|
|
977
|
+
title: str | None,
|
|
978
|
+
field_indices: tuple[int, ...],
|
|
979
|
+
include_field_index: bool,
|
|
980
|
+
grid: Mapping[object, object] | None = None,
|
|
981
|
+
) -> XarrayDataTree:
|
|
982
|
+
"""Build an xarray tree with the source coordinate names."""
|
|
983
|
+
|
|
984
|
+
grid_dims: tuple[str, ...] = tuple(
|
|
985
|
+
f"grid_dim_{axis_index}" for axis_index in range(len(coordinates.grid_shape))
|
|
986
|
+
)
|
|
987
|
+
field_dims: tuple[str, ...] = (
|
|
988
|
+
("field_index",) if include_field_index else ()
|
|
989
|
+
) + grid_dims
|
|
990
|
+
has_component_axis: bool = field.ndim == len(field_dims) + 1
|
|
991
|
+
data_vars: dict[str, object] = {
|
|
992
|
+
"field": (
|
|
993
|
+
field_dims + (("component",) if has_component_axis else ()),
|
|
994
|
+
field,
|
|
995
|
+
)
|
|
996
|
+
}
|
|
997
|
+
if grid is not None:
|
|
998
|
+
data_vars.update(_grid_data_vars(grid))
|
|
999
|
+
coords: dict[str, object] = {}
|
|
1000
|
+
coordinate_index: int
|
|
1001
|
+
coordinate_name: str
|
|
1002
|
+
coordinate_value: np.ndarray
|
|
1003
|
+
for coordinate_index, (coordinate_name, coordinate_value) in enumerate(
|
|
1004
|
+
zip(coordinates.names, coordinates.values, strict=True)
|
|
1005
|
+
):
|
|
1006
|
+
if coordinate_value.ndim == 0:
|
|
1007
|
+
coords[coordinate_name] = coordinate_value
|
|
1008
|
+
elif coordinate_value.ndim == 1 and len(coordinates.names) > 1:
|
|
1009
|
+
matching_dimensions: tuple[int, ...] = tuple(
|
|
1010
|
+
dimension_index
|
|
1011
|
+
for dimension_index, dimension_size in enumerate(coordinates.grid_shape)
|
|
1012
|
+
if dimension_size == coordinate_value.size
|
|
1013
|
+
)
|
|
1014
|
+
dimension_index = (
|
|
1015
|
+
matching_dimensions[0]
|
|
1016
|
+
if len(matching_dimensions) == 1
|
|
1017
|
+
else coordinate_index
|
|
1018
|
+
)
|
|
1019
|
+
coords[coordinate_name] = (
|
|
1020
|
+
(grid_dims[dimension_index],),
|
|
1021
|
+
coordinate_value,
|
|
1022
|
+
)
|
|
1023
|
+
else:
|
|
1024
|
+
coords[coordinate_name] = (grid_dims, coordinate_value)
|
|
1025
|
+
if include_field_index:
|
|
1026
|
+
coords["field_index"] = ("field_index", list(field_indices))
|
|
1027
|
+
if has_component_axis:
|
|
1028
|
+
coords["component"] = ("component", list(component_labels))
|
|
1029
|
+
attrs: dict[str, object] = {"coordinate_names": coordinates.names}
|
|
1030
|
+
if coordinates.names:
|
|
1031
|
+
attrs["x_label"] = coordinates.names[0]
|
|
1032
|
+
if len(coordinates.names) > 1:
|
|
1033
|
+
attrs["y_label"] = coordinates.names[1]
|
|
1034
|
+
if title is not None:
|
|
1035
|
+
attrs["title"] = title
|
|
1036
|
+
if has_component_axis:
|
|
1037
|
+
attrs["component_labels"] = component_labels
|
|
1038
|
+
dataset: XarrayDataset = _load_xarray_module().Dataset(
|
|
1039
|
+
data_vars=data_vars,
|
|
1040
|
+
coords=coords,
|
|
1041
|
+
attrs=attrs,
|
|
1042
|
+
)
|
|
1043
|
+
return _create_data_tree(
|
|
1044
|
+
datatree_module=_load_datatree_module(),
|
|
1045
|
+
dataset=dataset,
|
|
1046
|
+
)
|
|
1047
|
+
|
|
1048
|
+
|
|
1049
|
+
def _grid_data_vars(grid: Mapping[object, object]) -> dict[str, object]:
|
|
1050
|
+
"""Return grid mapping entries as xarray data variables."""
|
|
1051
|
+
|
|
1052
|
+
data_vars: dict[str, object] = {}
|
|
1053
|
+
for raw_name, raw_value in grid.items():
|
|
1054
|
+
if not isinstance(raw_name, str):
|
|
1055
|
+
continue
|
|
1056
|
+
value: np.ndarray = np.asarray(raw_value)
|
|
1057
|
+
dimensions: tuple[str, ...] = tuple(
|
|
1058
|
+
"grid_point" if axis_index == 0 else f"grid_point_dim_{axis_index}"
|
|
1059
|
+
for axis_index in range(value.ndim)
|
|
1060
|
+
)
|
|
1061
|
+
data_vars[raw_name] = (dimensions, value)
|
|
1062
|
+
return data_vars
|