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,4332 @@
|
|
|
1
|
+
"""Torch-aware façades for solve results and submissions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from collections.abc import Callable, Coroutine, Iterator, Mapping, Sequence
|
|
7
|
+
from dataclasses import dataclass, replace
|
|
8
|
+
from enum import IntEnum
|
|
9
|
+
from typing import Generic, Literal, Protocol, Self, TypeVar, cast, overload
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
from ..exceptions import UnsupportedExportError
|
|
14
|
+
from ..results import (
|
|
15
|
+
BatchSolveResult,
|
|
16
|
+
BatchSolveSubmission,
|
|
17
|
+
BundledBatchSolveResult,
|
|
18
|
+
BundledBatchSolveSubmission,
|
|
19
|
+
BundledSolveResult,
|
|
20
|
+
BundledSolveSubmission,
|
|
21
|
+
SolveResult,
|
|
22
|
+
SolveSubmission,
|
|
23
|
+
TableCollectionPayload,
|
|
24
|
+
TablePayload,
|
|
25
|
+
)
|
|
26
|
+
from ..results.field_exports import FieldExportPayload
|
|
27
|
+
from ..results.field_payloads import resolve_coordinates
|
|
28
|
+
from ..results.postprocess_payloads import (
|
|
29
|
+
TableCollectionDerivativeCollection,
|
|
30
|
+
TableCollectionDerivativeView,
|
|
31
|
+
TableDerivativeCollection,
|
|
32
|
+
TableDerivativeView,
|
|
33
|
+
)
|
|
34
|
+
from ..results.structured_derivatives import StructuredDerivativeCollection
|
|
35
|
+
from .autograd import connect_value, convert_mapping, numeric_tensor
|
|
36
|
+
from .coordinate_policy import (
|
|
37
|
+
binding_labels,
|
|
38
|
+
coordinate_labels,
|
|
39
|
+
missing_pair,
|
|
40
|
+
missing_pairs,
|
|
41
|
+
)
|
|
42
|
+
from .types import (
|
|
43
|
+
BindingContext,
|
|
44
|
+
BindingMap,
|
|
45
|
+
ComplexDerivative,
|
|
46
|
+
DerivativeBinding,
|
|
47
|
+
InputContext,
|
|
48
|
+
RealDerivative,
|
|
49
|
+
TorchTensor,
|
|
50
|
+
)
|
|
51
|
+
from .validation import is_tensor
|
|
52
|
+
|
|
53
|
+
_TransformName = Literal["abs", "real", "imag", "phase", "intensity"]
|
|
54
|
+
_TRANSFORM_NAMES: frozenset[str] = frozenset(("abs", "real", "imag", "phase"))
|
|
55
|
+
_TorchResultType = TypeVar("_TorchResultType", covariant=True)
|
|
56
|
+
_OMIT_STRUCTURED_VALUE = object()
|
|
57
|
+
_STRUCTURED_ROOT_METADATA_KEYS: frozenset[str] = frozenset(
|
|
58
|
+
{"coordinates", "header", "metadata", "title"}
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _project_numeric_component(
|
|
63
|
+
value: object,
|
|
64
|
+
component: Literal["real", "imag"] | None,
|
|
65
|
+
backend: object,
|
|
66
|
+
real_projection: Literal["project", "preserve", "zero"] = "project",
|
|
67
|
+
) -> object:
|
|
68
|
+
if (
|
|
69
|
+
real_projection != "project"
|
|
70
|
+
and component == "imag"
|
|
71
|
+
and not (
|
|
72
|
+
np.iscomplexobj(value)
|
|
73
|
+
if isinstance(value, (np.ndarray, np.number, int, float, complex))
|
|
74
|
+
else _is_complex_tensor(value, backend)
|
|
75
|
+
)
|
|
76
|
+
):
|
|
77
|
+
if real_projection == "preserve":
|
|
78
|
+
return value
|
|
79
|
+
return getattr(backend, "zeros_like")(value)
|
|
80
|
+
return value if component is None else getattr(backend, component)(value)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _pack_numeric_directions(
|
|
84
|
+
first: object,
|
|
85
|
+
second: object,
|
|
86
|
+
component: Literal["real", "imag"] | None,
|
|
87
|
+
backend: object,
|
|
88
|
+
real_projection: Literal["project", "preserve"] = "project",
|
|
89
|
+
) -> object:
|
|
90
|
+
left, right = (
|
|
91
|
+
_project_numeric_component(value, component, backend, real_projection)
|
|
92
|
+
for value in (first, second)
|
|
93
|
+
)
|
|
94
|
+
return (
|
|
95
|
+
getattr(backend, "complex")(left, right)
|
|
96
|
+
if real_projection == "preserve"
|
|
97
|
+
else getattr(left, "__add__")(getattr(right, "__rmul__")(1j))
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class _OrdinaryDerivativeCollection(Protocol):
|
|
102
|
+
"""Expose only name selection for an unwrapped ordinary collection."""
|
|
103
|
+
|
|
104
|
+
def __getitem__(self, name: str) -> object: ...
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _is_structured_metadata_key(key: object, *, root: bool) -> bool:
|
|
108
|
+
"""Classify root-level schema metadata without hiding nested quantities."""
|
|
109
|
+
return (
|
|
110
|
+
root and isinstance(key, str) and key.lower() in _STRUCTURED_ROOT_METADATA_KEYS
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _without_structured_root_metadata(
|
|
115
|
+
mapping: Mapping[object, object],
|
|
116
|
+
) -> Mapping[object, object]:
|
|
117
|
+
"""Remove root metadata before solver bindings are applied to numeric leaves."""
|
|
118
|
+
return {
|
|
119
|
+
key: value
|
|
120
|
+
for key, value in mapping.items()
|
|
121
|
+
if not _is_structured_metadata_key(key, root=True)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _contains_complex_structure(value: object, torch_module: object) -> bool:
|
|
126
|
+
if isinstance(value, Mapping):
|
|
127
|
+
return any(
|
|
128
|
+
_contains_complex_structure(child, torch_module) for child in value.values()
|
|
129
|
+
)
|
|
130
|
+
tensor: TorchTensor | None = numeric_tensor(value, torch_module, device="cpu")
|
|
131
|
+
return tensor is not None and _is_complex_tensor(tensor, torch_module)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _same_structured_value(left: object, right: object, torch_module: object) -> bool:
|
|
135
|
+
left_tensor: TorchTensor | None = numeric_tensor(left, torch_module, device="cpu")
|
|
136
|
+
right_tensor: TorchTensor | None = numeric_tensor(right, torch_module, device="cpu")
|
|
137
|
+
if left_tensor is not None and right_tensor is not None:
|
|
138
|
+
left_array: np.ndarray = cast(
|
|
139
|
+
np.ndarray, getattr(left_tensor, "detach")().cpu().numpy()
|
|
140
|
+
)
|
|
141
|
+
right_array: np.ndarray = cast(
|
|
142
|
+
np.ndarray, getattr(right_tensor, "detach")().cpu().numpy()
|
|
143
|
+
)
|
|
144
|
+
return bool(np.array_equal(left_array, right_array, equal_nan=True))
|
|
145
|
+
try:
|
|
146
|
+
return bool(np.array_equal(np.asarray(left), np.asarray(right), equal_nan=True))
|
|
147
|
+
except (TypeError, ValueError):
|
|
148
|
+
return left == right
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _project_structured_component(
|
|
152
|
+
base: object,
|
|
153
|
+
values: object,
|
|
154
|
+
component: Literal["real", "imag"],
|
|
155
|
+
torch_module: object,
|
|
156
|
+
*,
|
|
157
|
+
path: str = "payload",
|
|
158
|
+
root: bool = True,
|
|
159
|
+
) -> object:
|
|
160
|
+
if isinstance(base, Mapping) and isinstance(values, Mapping):
|
|
161
|
+
projected: dict[object, object] = {}
|
|
162
|
+
for key, base_value in base.items():
|
|
163
|
+
if key not in values:
|
|
164
|
+
continue
|
|
165
|
+
if _is_structured_metadata_key(key, root=root):
|
|
166
|
+
projected[key] = base_value
|
|
167
|
+
continue
|
|
168
|
+
child: object = _project_structured_component(
|
|
169
|
+
base_value,
|
|
170
|
+
values[key],
|
|
171
|
+
component,
|
|
172
|
+
torch_module,
|
|
173
|
+
path=f"{path}.{key}",
|
|
174
|
+
root=False,
|
|
175
|
+
)
|
|
176
|
+
if child is not _OMIT_STRUCTURED_VALUE:
|
|
177
|
+
projected[key] = child
|
|
178
|
+
return projected
|
|
179
|
+
base_tensor: TorchTensor | None = numeric_tensor(base, torch_module, device="cpu")
|
|
180
|
+
value_tensor: TorchTensor | None = numeric_tensor(
|
|
181
|
+
values, torch_module, device="cpu"
|
|
182
|
+
)
|
|
183
|
+
if base_tensor is None or value_tensor is None:
|
|
184
|
+
return values
|
|
185
|
+
if component == "imag" and (
|
|
186
|
+
not _is_complex_tensor(base_tensor, torch_module)
|
|
187
|
+
or not _is_complex_tensor(value_tensor, torch_module)
|
|
188
|
+
):
|
|
189
|
+
return _OMIT_STRUCTURED_VALUE
|
|
190
|
+
return _project_numeric_component(value_tensor, component, torch_module)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _pack_structured_components(
|
|
194
|
+
base: object,
|
|
195
|
+
first: object,
|
|
196
|
+
second: object,
|
|
197
|
+
component: Literal["real", "imag"],
|
|
198
|
+
torch_module: object,
|
|
199
|
+
*,
|
|
200
|
+
path: str = "payload",
|
|
201
|
+
root: bool = True,
|
|
202
|
+
) -> object:
|
|
203
|
+
if isinstance(base, Mapping):
|
|
204
|
+
if not isinstance(first, Mapping) or not isinstance(second, Mapping):
|
|
205
|
+
if first is _OMIT_STRUCTURED_VALUE and second is _OMIT_STRUCTURED_VALUE:
|
|
206
|
+
return _OMIT_STRUCTURED_VALUE
|
|
207
|
+
raise ValueError(
|
|
208
|
+
f"Structured derivative coordinate data is incomplete for quantity {path!r}."
|
|
209
|
+
)
|
|
210
|
+
packed: dict[object, object] = {}
|
|
211
|
+
for key, base_value in base.items():
|
|
212
|
+
if _is_structured_metadata_key(key, root=root):
|
|
213
|
+
packed[key] = base_value
|
|
214
|
+
continue
|
|
215
|
+
first_value: object = first.get(key, _OMIT_STRUCTURED_VALUE)
|
|
216
|
+
second_value: object = second.get(key, _OMIT_STRUCTURED_VALUE)
|
|
217
|
+
child: object = _pack_structured_components(
|
|
218
|
+
base_value,
|
|
219
|
+
first_value,
|
|
220
|
+
second_value,
|
|
221
|
+
component,
|
|
222
|
+
torch_module,
|
|
223
|
+
path=f"{path}.{key}",
|
|
224
|
+
root=False,
|
|
225
|
+
)
|
|
226
|
+
if child is not _OMIT_STRUCTURED_VALUE:
|
|
227
|
+
packed[key] = child
|
|
228
|
+
return packed
|
|
229
|
+
if first is _OMIT_STRUCTURED_VALUE and second is _OMIT_STRUCTURED_VALUE:
|
|
230
|
+
return _OMIT_STRUCTURED_VALUE
|
|
231
|
+
if first is _OMIT_STRUCTURED_VALUE or second is _OMIT_STRUCTURED_VALUE:
|
|
232
|
+
raise ValueError(
|
|
233
|
+
f"Structured derivative coordinate data is incomplete for quantity {path!r}."
|
|
234
|
+
)
|
|
235
|
+
base_tensor: TorchTensor | None = numeric_tensor(base, torch_module, device="cpu")
|
|
236
|
+
first_tensor: TorchTensor | None = numeric_tensor(first, torch_module, device="cpu")
|
|
237
|
+
second_tensor: TorchTensor | None = numeric_tensor(
|
|
238
|
+
second, torch_module, device="cpu"
|
|
239
|
+
)
|
|
240
|
+
if base_tensor is None or first_tensor is None or second_tensor is None:
|
|
241
|
+
return (
|
|
242
|
+
first
|
|
243
|
+
if _same_structured_value(first, second, torch_module)
|
|
244
|
+
else _OMIT_STRUCTURED_VALUE
|
|
245
|
+
)
|
|
246
|
+
if component == "imag" and not _is_complex_tensor(base_tensor, torch_module):
|
|
247
|
+
return _OMIT_STRUCTURED_VALUE
|
|
248
|
+
return _pack_numeric_directions(
|
|
249
|
+
first_tensor,
|
|
250
|
+
second_tensor,
|
|
251
|
+
component,
|
|
252
|
+
torch_module,
|
|
253
|
+
real_projection="preserve",
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class _TorchRecordData:
|
|
258
|
+
"""Convert ordinary postprocess or field data into Torch tensors."""
|
|
259
|
+
|
|
260
|
+
def __init__(
|
|
261
|
+
self,
|
|
262
|
+
record: object,
|
|
263
|
+
bindings: BindingMap,
|
|
264
|
+
inputs: tuple[TorchTensor, ...],
|
|
265
|
+
torch_module: object,
|
|
266
|
+
transforms: tuple[_TransformName, ...] = (),
|
|
267
|
+
) -> None:
|
|
268
|
+
self._record, self._bindings, self._inputs, self._torch = (
|
|
269
|
+
record,
|
|
270
|
+
bindings,
|
|
271
|
+
inputs,
|
|
272
|
+
torch_module,
|
|
273
|
+
)
|
|
274
|
+
self._transforms = transforms
|
|
275
|
+
|
|
276
|
+
def __getattr__(self, name: str) -> object:
|
|
277
|
+
return getattr(self._record, name)
|
|
278
|
+
|
|
279
|
+
def to_dict(self) -> Mapping[object, object]:
|
|
280
|
+
"""Return the payload as a mapping with Torch numeric leaves.
|
|
281
|
+
|
|
282
|
+
Returns
|
|
283
|
+
-------
|
|
284
|
+
Mapping[object, object]
|
|
285
|
+
The ordinary mapping with numeric leaves converted to Torch tensors.
|
|
286
|
+
Leaves with solver derivative data remain connected to the bound
|
|
287
|
+
inputs; numeric leaves without derivative data are detached.
|
|
288
|
+
"""
|
|
289
|
+
raw: Mapping[object, object] = self._raw_mapping()
|
|
290
|
+
payload: object = getattr(self._record, "payload", None)
|
|
291
|
+
if isinstance(payload, TableCollectionPayload):
|
|
292
|
+
return self._table_collection_to_dict(payload)
|
|
293
|
+
root: object = getattr(self._record, "_mapping", None)
|
|
294
|
+
projected: bool = (
|
|
295
|
+
isinstance(root, Mapping)
|
|
296
|
+
and "derivatives" in root
|
|
297
|
+
and "derivatives" not in raw
|
|
298
|
+
)
|
|
299
|
+
if projected:
|
|
300
|
+
raw = dict(raw)
|
|
301
|
+
raw["derivatives"] = root["derivatives"] # type: ignore[index]
|
|
302
|
+
derivative_raw: object = raw.get("derivatives")
|
|
303
|
+
branches: Mapping[str, object] = (
|
|
304
|
+
cast(Mapping[str, object], derivative_raw)
|
|
305
|
+
if isinstance(derivative_raw, Mapping)
|
|
306
|
+
else {}
|
|
307
|
+
)
|
|
308
|
+
required: set[str] = set(coordinate_labels(self._bindings))
|
|
309
|
+
if not branches:
|
|
310
|
+
flat_branches: dict[str, object] = {}
|
|
311
|
+
for label in required:
|
|
312
|
+
field_key: str = f"d_field_{label}"
|
|
313
|
+
table_key: str = f"d_{label}"
|
|
314
|
+
if field_key in raw:
|
|
315
|
+
flat_branches[label] = {"field": raw[field_key]}
|
|
316
|
+
elif table_key in raw:
|
|
317
|
+
flat_branches[label] = raw[table_key]
|
|
318
|
+
branches = flat_branches
|
|
319
|
+
if required:
|
|
320
|
+
missing: set[str] = required - set(branches)
|
|
321
|
+
if missing:
|
|
322
|
+
raise ValueError(
|
|
323
|
+
"Solver derivative labels are unavailable in the result: "
|
|
324
|
+
f"{sorted(missing)!r}."
|
|
325
|
+
)
|
|
326
|
+
converted: Mapping[object, object] = cast(
|
|
327
|
+
Mapping[object, object],
|
|
328
|
+
convert_mapping(
|
|
329
|
+
raw,
|
|
330
|
+
bindings=self._bindings,
|
|
331
|
+
inputs=self._inputs,
|
|
332
|
+
torch_module=self._torch,
|
|
333
|
+
derivative_mapping=branches,
|
|
334
|
+
second_derivative_mapping=(
|
|
335
|
+
self._field_second_derivatives()
|
|
336
|
+
or self._structured_second_derivatives()
|
|
337
|
+
or self._table_second_derivatives()
|
|
338
|
+
),
|
|
339
|
+
),
|
|
340
|
+
)
|
|
341
|
+
if projected:
|
|
342
|
+
converted = dict(converted)
|
|
343
|
+
converted.pop("derivatives", None)
|
|
344
|
+
if not self._transforms:
|
|
345
|
+
return converted
|
|
346
|
+
return _transform_mapping(
|
|
347
|
+
converted,
|
|
348
|
+
self._transforms,
|
|
349
|
+
self._torch,
|
|
350
|
+
grid_rank=_field_grid_rank(raw),
|
|
351
|
+
)
|
|
352
|
+
|
|
353
|
+
def _table_collection_to_dict(
|
|
354
|
+
self, payload: TableCollectionPayload
|
|
355
|
+
) -> Mapping[object, object]:
|
|
356
|
+
"""Convert identifiable collection members without sharing their derivatives."""
|
|
357
|
+
raw_collection: Mapping[object, object] = payload.to_dict()
|
|
358
|
+
ordinary_derivatives: object = payload.derivatives
|
|
359
|
+
labels: tuple[str, ...] = coordinate_labels(self._bindings)
|
|
360
|
+
converted: dict[object, object] = {}
|
|
361
|
+
for member, raw_member in raw_collection.items():
|
|
362
|
+
if not isinstance(raw_member, Mapping):
|
|
363
|
+
converted[member] = raw_member
|
|
364
|
+
continue
|
|
365
|
+
branches: dict[str, object] = {}
|
|
366
|
+
first_views: dict[str, object] = {}
|
|
367
|
+
for label in labels:
|
|
368
|
+
try:
|
|
369
|
+
first_view: object = ordinary_derivatives[label] # type: ignore[index]
|
|
370
|
+
except KeyError:
|
|
371
|
+
continue
|
|
372
|
+
first_views[label] = first_view
|
|
373
|
+
first_values: object = getattr(first_view, "to_dict")()
|
|
374
|
+
if isinstance(first_values, Mapping):
|
|
375
|
+
member_branch: object = first_values.get(member)
|
|
376
|
+
if isinstance(member_branch, Mapping):
|
|
377
|
+
branches[label] = member_branch
|
|
378
|
+
bound_labels: set[str] = set(labels)
|
|
379
|
+
present_labels: set[str] = set(branches)
|
|
380
|
+
if present_labels and present_labels != bound_labels:
|
|
381
|
+
raise ValueError(
|
|
382
|
+
f"Incomplete table-collection first derivatives for member {member!r}: missing "
|
|
383
|
+
f"{sorted(bound_labels - present_labels)!r}."
|
|
384
|
+
)
|
|
385
|
+
active_bindings: BindingMap = {
|
|
386
|
+
key: binding
|
|
387
|
+
for key, binding in self._bindings.items()
|
|
388
|
+
if all(label in branches for label in (binding_labels(binding)))
|
|
389
|
+
}
|
|
390
|
+
active_inputs: tuple[TorchTensor, ...] = tuple(
|
|
391
|
+
self._inputs[index]
|
|
392
|
+
for index, key in enumerate(self._bindings)
|
|
393
|
+
if key in active_bindings
|
|
394
|
+
)
|
|
395
|
+
pair_map: dict[str, dict[str, object]] = {}
|
|
396
|
+
for first in branches:
|
|
397
|
+
nested_derivatives: object = getattr(first_views[first], "derivatives")
|
|
398
|
+
for second in labels:
|
|
399
|
+
try:
|
|
400
|
+
pair_view: object = nested_derivatives[second] # type: ignore[index]
|
|
401
|
+
except KeyError:
|
|
402
|
+
continue
|
|
403
|
+
pair_values: object = getattr(pair_view, "to_dict")()
|
|
404
|
+
if isinstance(pair_values, Mapping):
|
|
405
|
+
member_pair: object = pair_values.get(member)
|
|
406
|
+
if isinstance(member_pair, Mapping):
|
|
407
|
+
pair_map.setdefault(first, {})[second] = member_pair
|
|
408
|
+
converted[member] = convert_mapping(
|
|
409
|
+
raw_member,
|
|
410
|
+
bindings=active_bindings,
|
|
411
|
+
inputs=active_inputs,
|
|
412
|
+
torch_module=self._torch,
|
|
413
|
+
derivative_mapping=branches or None,
|
|
414
|
+
second_derivative_mapping=pair_map or None,
|
|
415
|
+
)
|
|
416
|
+
return converted
|
|
417
|
+
|
|
418
|
+
def _field_second_derivatives(self) -> Mapping[str, Mapping[str, object]]:
|
|
419
|
+
"""Read pair data through ordinary field derivative navigation."""
|
|
420
|
+
if not isinstance(self._record, FieldExportPayload):
|
|
421
|
+
return {}
|
|
422
|
+
raw_mapping: Mapping[object, object] = cast(
|
|
423
|
+
Mapping[object, object], getattr(self._record, "to_dict")()
|
|
424
|
+
)
|
|
425
|
+
if not any(
|
|
426
|
+
isinstance(key, str) and key.startswith("dd_field_") for key in raw_mapping
|
|
427
|
+
):
|
|
428
|
+
return {}
|
|
429
|
+
bound_labels: tuple[str, ...] = coordinate_labels(self._bindings)
|
|
430
|
+
result: dict[str, dict[str, object]] = {}
|
|
431
|
+
collection: object = self._record.derivatives
|
|
432
|
+
for first_label in bound_labels:
|
|
433
|
+
try:
|
|
434
|
+
first_view: object = collection[first_label] # type: ignore[index]
|
|
435
|
+
except KeyError:
|
|
436
|
+
continue
|
|
437
|
+
second_collection: object = getattr(first_view, "derivatives")
|
|
438
|
+
for second_label in bound_labels:
|
|
439
|
+
try:
|
|
440
|
+
pair_view: object = second_collection[second_label] # type: ignore[index]
|
|
441
|
+
except KeyError:
|
|
442
|
+
continue
|
|
443
|
+
pair_mapping: object = getattr(pair_view, "to_dict")()
|
|
444
|
+
if isinstance(pair_mapping, Mapping):
|
|
445
|
+
result.setdefault(first_label, {})[second_label] = pair_mapping
|
|
446
|
+
return result
|
|
447
|
+
|
|
448
|
+
def _table_second_derivatives(self) -> Mapping[str, Mapping[str, object]]:
|
|
449
|
+
"""Collect table pair payloads through ordinary derivative selection."""
|
|
450
|
+
payload: object = getattr(self._record, "payload", self._record)
|
|
451
|
+
if not isinstance(payload, TablePayload):
|
|
452
|
+
return {}
|
|
453
|
+
labels: tuple[str, ...] = coordinate_labels(self._bindings)
|
|
454
|
+
result: dict[str, dict[str, object]] = {}
|
|
455
|
+
ordinary: TableDerivativeCollection = payload.derivatives
|
|
456
|
+
for first in labels:
|
|
457
|
+
try:
|
|
458
|
+
first_view: TableDerivativeView = ordinary[first]
|
|
459
|
+
except KeyError:
|
|
460
|
+
continue
|
|
461
|
+
second_collection: TableDerivativeCollection = first_view.derivatives
|
|
462
|
+
pairs: dict[str, object] = {}
|
|
463
|
+
for second in labels:
|
|
464
|
+
try:
|
|
465
|
+
pair_view: TableDerivativeView = second_collection[second]
|
|
466
|
+
except KeyError:
|
|
467
|
+
continue
|
|
468
|
+
pairs[second] = pair_view.to_dict()
|
|
469
|
+
if pairs:
|
|
470
|
+
result[first] = pairs
|
|
471
|
+
return result
|
|
472
|
+
|
|
473
|
+
def _structured_second_derivatives(self) -> Mapping[str, Mapping[str, object]]:
|
|
474
|
+
"""Read structured numeric pairs through the ordinary derivative views."""
|
|
475
|
+
try:
|
|
476
|
+
collection: object = getattr(self._record, "derivatives")
|
|
477
|
+
except AttributeError:
|
|
478
|
+
return {}
|
|
479
|
+
if not isinstance(collection, StructuredDerivativeCollection):
|
|
480
|
+
return {}
|
|
481
|
+
labels: tuple[str, ...] = coordinate_labels(self._bindings)
|
|
482
|
+
select: Callable[[str], object] = cast(
|
|
483
|
+
Callable[[str], object], getattr(collection, "__getitem__")
|
|
484
|
+
)
|
|
485
|
+
pairs: dict[str, dict[str, object]] = {}
|
|
486
|
+
for first in labels:
|
|
487
|
+
try:
|
|
488
|
+
first_view: object = select(first)
|
|
489
|
+
nested: object = getattr(first_view, "derivatives")
|
|
490
|
+
select_second: Callable[[str], object] = cast(
|
|
491
|
+
Callable[[str], object], getattr(nested, "__getitem__")
|
|
492
|
+
)
|
|
493
|
+
except (AttributeError, KeyError):
|
|
494
|
+
continue
|
|
495
|
+
for second in labels:
|
|
496
|
+
try:
|
|
497
|
+
pair_view: object = select_second(second)
|
|
498
|
+
pair_mapping: object = getattr(pair_view, "to_dict")()
|
|
499
|
+
except (AttributeError, KeyError):
|
|
500
|
+
continue
|
|
501
|
+
if isinstance(pair_mapping, Mapping):
|
|
502
|
+
pairs.setdefault(first, {})[second] = pair_mapping
|
|
503
|
+
return pairs
|
|
504
|
+
|
|
505
|
+
def _raw_mapping(self) -> Mapping[object, object]:
|
|
506
|
+
records: object = getattr(self._record, "records", None)
|
|
507
|
+
if isinstance(records, tuple):
|
|
508
|
+
values: dict[object, object] = {}
|
|
509
|
+
for record in records:
|
|
510
|
+
payload: object = getattr(record, "payload", None)
|
|
511
|
+
if payload is None:
|
|
512
|
+
continue
|
|
513
|
+
projected: object = getattr(payload, "to_dict")()
|
|
514
|
+
root: object = getattr(payload, "_mapping", None)
|
|
515
|
+
if isinstance(projected, Mapping) and isinstance(root, Mapping):
|
|
516
|
+
result: dict[object, object] = dict(projected)
|
|
517
|
+
if "derivatives" in root and "derivatives" not in result:
|
|
518
|
+
result["derivatives"] = root["derivatives"]
|
|
519
|
+
values[getattr(record, "index")] = result
|
|
520
|
+
else:
|
|
521
|
+
values[getattr(record, "index")] = projected
|
|
522
|
+
if values:
|
|
523
|
+
return values
|
|
524
|
+
return cast(Mapping[object, object], getattr(self._record, "to_dict")())
|
|
525
|
+
|
|
526
|
+
def _base_mapping(self) -> Mapping[object, object]:
|
|
527
|
+
raw: Mapping[object, object] = self._raw_mapping()
|
|
528
|
+
return {
|
|
529
|
+
key: value
|
|
530
|
+
for key, value in raw.items()
|
|
531
|
+
if key != "derivatives"
|
|
532
|
+
and not (isinstance(key, str) and key.startswith("d_"))
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
def _derivative_branch(self, binding: RealDerivative) -> Mapping[object, object]:
|
|
536
|
+
raw: Mapping[object, object] = self._raw_mapping()
|
|
537
|
+
derivatives: object = raw.get("derivatives")
|
|
538
|
+
if isinstance(derivatives, Mapping) and binding.label in derivatives:
|
|
539
|
+
branch: object = derivatives[binding.label]
|
|
540
|
+
if isinstance(branch, Mapping):
|
|
541
|
+
return branch
|
|
542
|
+
field_key: str = f"d_field_{binding.label}"
|
|
543
|
+
table_key: str = f"d_{binding.label}"
|
|
544
|
+
if field_key in raw:
|
|
545
|
+
return {"field": raw[field_key]}
|
|
546
|
+
if table_key in raw and isinstance(raw[table_key], Mapping):
|
|
547
|
+
return cast(Mapping[object, object], raw[table_key])
|
|
548
|
+
raise ValueError(
|
|
549
|
+
f"Solver derivative label {binding.label!r} is unavailable in the result."
|
|
550
|
+
)
|
|
551
|
+
|
|
552
|
+
def to_df(self, orient: str | None = None) -> object:
|
|
553
|
+
"""Raise because Torch tensor payloads do not support DataFrame export.
|
|
554
|
+
|
|
555
|
+
Parameters
|
|
556
|
+
----------
|
|
557
|
+
orient : str | None, optional
|
|
558
|
+
DataFrame orientation. The value does not change the error.
|
|
559
|
+
|
|
560
|
+
Returns
|
|
561
|
+
-------
|
|
562
|
+
object
|
|
563
|
+
This method does not return.
|
|
564
|
+
|
|
565
|
+
Raises
|
|
566
|
+
------
|
|
567
|
+
UnsupportedExportError
|
|
568
|
+
Always. Use the ordinary solve result for DataFrame export.
|
|
569
|
+
"""
|
|
570
|
+
raise UnsupportedExportError(
|
|
571
|
+
"to_df is not supported for Torch-bound results; use untorch() for ordinary DataFrame exports."
|
|
572
|
+
)
|
|
573
|
+
|
|
574
|
+
def to_xarray(self) -> object:
|
|
575
|
+
"""Raise because Torch tensor payloads do not support xarray export.
|
|
576
|
+
|
|
577
|
+
Returns
|
|
578
|
+
-------
|
|
579
|
+
object
|
|
580
|
+
This method does not return.
|
|
581
|
+
|
|
582
|
+
Raises
|
|
583
|
+
------
|
|
584
|
+
UnsupportedExportError
|
|
585
|
+
Always. Use the ordinary solve result for xarray export.
|
|
586
|
+
"""
|
|
587
|
+
raise UnsupportedExportError(
|
|
588
|
+
"to_xarray is not supported for Torch-bound results."
|
|
589
|
+
)
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
class TorchPostprocessRecord(_TorchRecordData):
|
|
593
|
+
"""Wrap one ordinary postprocess record with Torch-aware exports.
|
|
594
|
+
|
|
595
|
+
Use :attr:`fields` to get the field-export interface when the postprocess
|
|
596
|
+
contains field data. Other postprocess data is available through
|
|
597
|
+
:meth:`to_dict`. The class is returned by
|
|
598
|
+
:class:`TorchPostprocessCollection`; do not construct it directly.
|
|
599
|
+
"""
|
|
600
|
+
|
|
601
|
+
@property
|
|
602
|
+
def fields(self) -> TorchFieldExportPayload:
|
|
603
|
+
"""Return the field-export view for this postprocess.
|
|
604
|
+
|
|
605
|
+
Returns
|
|
606
|
+
-------
|
|
607
|
+
TorchFieldExportPayload
|
|
608
|
+
Torch-aware field navigation and export.
|
|
609
|
+
"""
|
|
610
|
+
return TorchFieldExportPayload(
|
|
611
|
+
getattr(self._record, "fields"),
|
|
612
|
+
self._bindings,
|
|
613
|
+
self._inputs,
|
|
614
|
+
self._torch,
|
|
615
|
+
)
|
|
616
|
+
|
|
617
|
+
@property
|
|
618
|
+
def derivatives(
|
|
619
|
+
self,
|
|
620
|
+
) -> (
|
|
621
|
+
TorchTableDerivativeCollection
|
|
622
|
+
| TorchStructuredDerivativeCollection
|
|
623
|
+
| _OrdinaryDerivativeCollection
|
|
624
|
+
):
|
|
625
|
+
"""Return derivative navigation for this postprocess result."""
|
|
626
|
+
payload: object = getattr(self._record, "payload", None)
|
|
627
|
+
if isinstance(payload, (TablePayload, TableCollectionPayload)):
|
|
628
|
+
return TorchTableDerivativeCollection(self, payload.derivatives, depth=0)
|
|
629
|
+
ordinary: object = getattr(self._record, "derivatives")
|
|
630
|
+
if isinstance(ordinary, StructuredDerivativeCollection):
|
|
631
|
+
return TorchStructuredDerivativeCollection(self, ordinary)
|
|
632
|
+
# The ordinary fallback intentionally preserves identity and behavior.
|
|
633
|
+
# Its source collection is dynamically supplied by the payload adapter.
|
|
634
|
+
return cast(_OrdinaryDerivativeCollection, ordinary)
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
@dataclass(frozen=True, slots=True)
|
|
638
|
+
class _TorchStructuredSelection:
|
|
639
|
+
"""Selection state shared by structured Torch derivative navigation."""
|
|
640
|
+
|
|
641
|
+
order: Literal[0, 1, 2] = 0
|
|
642
|
+
output_component: Literal["real", "imag"] | None = None
|
|
643
|
+
coordinate_component: Literal["real", "imag"] | None = None
|
|
644
|
+
packing: Literal["single", "coordinates"] = "single"
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
class TorchStructuredDerivativeCollection:
|
|
648
|
+
"""Select structured numeric sensitivities using bound Project Key names."""
|
|
649
|
+
|
|
650
|
+
def __init__(
|
|
651
|
+
self,
|
|
652
|
+
owner: TorchPostprocessRecord,
|
|
653
|
+
collection: object | tuple[object, ...] | None = None,
|
|
654
|
+
*,
|
|
655
|
+
output_component: Literal["real", "imag"] | None = None,
|
|
656
|
+
inspection_only: bool = False,
|
|
657
|
+
) -> None:
|
|
658
|
+
self._owner = owner
|
|
659
|
+
self._collection = (
|
|
660
|
+
getattr(owner._record, "derivatives") if collection is None else collection
|
|
661
|
+
)
|
|
662
|
+
self._selection = _TorchStructuredSelection(
|
|
663
|
+
order=2 if inspection_only else 0,
|
|
664
|
+
output_component=output_component,
|
|
665
|
+
)
|
|
666
|
+
|
|
667
|
+
def keys(self) -> tuple[str, ...]:
|
|
668
|
+
return tuple(
|
|
669
|
+
name
|
|
670
|
+
for name, value in zip(self._owner._bindings, self._owner._inputs)
|
|
671
|
+
if getattr(value, "requires_grad", False)
|
|
672
|
+
)
|
|
673
|
+
|
|
674
|
+
def __getitem__(
|
|
675
|
+
self, name: str
|
|
676
|
+
) -> "TorchStructuredDerivativeView | TorchStructuredComplexDerivativePayload":
|
|
677
|
+
if name not in self.keys():
|
|
678
|
+
raise KeyError(name)
|
|
679
|
+
if self._selection.order == 2:
|
|
680
|
+
raise RuntimeError(
|
|
681
|
+
"Third-order structured solver derivatives are unavailable."
|
|
682
|
+
)
|
|
683
|
+
binding = self._owner._bindings[name]
|
|
684
|
+
labels = binding_labels(binding)
|
|
685
|
+
collections: tuple[object, ...] = (
|
|
686
|
+
self._collection
|
|
687
|
+
if isinstance(self._collection, tuple)
|
|
688
|
+
else (self._collection,)
|
|
689
|
+
)
|
|
690
|
+
selected_views: list[object] = []
|
|
691
|
+
for collection in collections:
|
|
692
|
+
select: Callable[[str], object] = cast(
|
|
693
|
+
Callable[[str], object], getattr(collection, "__getitem__")
|
|
694
|
+
)
|
|
695
|
+
for label in labels:
|
|
696
|
+
try:
|
|
697
|
+
selected_views.append(select(label))
|
|
698
|
+
except KeyError as error:
|
|
699
|
+
raise ValueError(
|
|
700
|
+
f"Structured derivative for Project Key {name!r} is unavailable."
|
|
701
|
+
) from error
|
|
702
|
+
nested: bool = any(
|
|
703
|
+
getattr(collection, "_derivative_order", 0) >= 1
|
|
704
|
+
for collection in collections
|
|
705
|
+
)
|
|
706
|
+
view = TorchStructuredDerivativeView(
|
|
707
|
+
self._owner,
|
|
708
|
+
name,
|
|
709
|
+
tuple(selected_views),
|
|
710
|
+
labels,
|
|
711
|
+
output_component=self._selection.output_component,
|
|
712
|
+
pack_coordinates=(len(collections) > 1 or len(labels) > 1),
|
|
713
|
+
inspection_only=nested,
|
|
714
|
+
)
|
|
715
|
+
if isinstance(binding, RealDerivative):
|
|
716
|
+
if self._selection.output_component is not None:
|
|
717
|
+
return view
|
|
718
|
+
if _contains_complex_structure(
|
|
719
|
+
self._owner._base_mapping(), self._owner._torch
|
|
720
|
+
):
|
|
721
|
+
return TorchStructuredComplexDerivativePayload(
|
|
722
|
+
real=view.with_component("real"),
|
|
723
|
+
imag=(
|
|
724
|
+
view.with_component("imag")
|
|
725
|
+
if _contains_complex_structure(
|
|
726
|
+
self._owner._base_mapping(), self._owner._torch
|
|
727
|
+
)
|
|
728
|
+
else None
|
|
729
|
+
),
|
|
730
|
+
)
|
|
731
|
+
return view
|
|
732
|
+
if nested:
|
|
733
|
+
return TorchStructuredComplexDerivativePayload(
|
|
734
|
+
real=view.with_coordinate_component("real"),
|
|
735
|
+
imag=view.with_coordinate_component("imag"),
|
|
736
|
+
)
|
|
737
|
+
return TorchStructuredComplexDerivativePayload(
|
|
738
|
+
real=view.with_component("real"),
|
|
739
|
+
imag=(
|
|
740
|
+
view.with_component("imag")
|
|
741
|
+
if _contains_complex_structure(
|
|
742
|
+
self._owner._base_mapping(), self._owner._torch
|
|
743
|
+
)
|
|
744
|
+
else None
|
|
745
|
+
),
|
|
746
|
+
)
|
|
747
|
+
|
|
748
|
+
|
|
749
|
+
class TorchStructuredComplexDerivativePayload:
|
|
750
|
+
"""Expose structured output components or nested input-coordinate columns."""
|
|
751
|
+
|
|
752
|
+
def __init__(
|
|
753
|
+
self,
|
|
754
|
+
*,
|
|
755
|
+
real: "TorchStructuredDerivativeView",
|
|
756
|
+
imag: "TorchStructuredDerivativeView | None",
|
|
757
|
+
) -> None:
|
|
758
|
+
self.real = real
|
|
759
|
+
self.imag = imag
|
|
760
|
+
|
|
761
|
+
def to_dict(self) -> Mapping[object, object]:
|
|
762
|
+
"""Require output-component selection before dictionary export."""
|
|
763
|
+
raise ValueError(
|
|
764
|
+
"Select the 'real' or 'imag' output component before exporting "
|
|
765
|
+
"a complex structured derivative."
|
|
766
|
+
)
|
|
767
|
+
|
|
768
|
+
|
|
769
|
+
class TorchStructuredDerivativeView:
|
|
770
|
+
"""Torch dictionary view of a structured first- or second-order derivative."""
|
|
771
|
+
|
|
772
|
+
def __init__(
|
|
773
|
+
self,
|
|
774
|
+
owner: TorchPostprocessRecord,
|
|
775
|
+
name: str,
|
|
776
|
+
views: tuple[object, ...],
|
|
777
|
+
labels: tuple[str, ...],
|
|
778
|
+
*,
|
|
779
|
+
output_component: Literal["real", "imag"] | None = None,
|
|
780
|
+
coordinate_component: Literal["real", "imag"] | None = None,
|
|
781
|
+
pack_coordinates: bool = False,
|
|
782
|
+
inspection_only: bool = False,
|
|
783
|
+
) -> None:
|
|
784
|
+
self._owner, self._name, self._views = owner, name, views
|
|
785
|
+
self._labels = labels
|
|
786
|
+
self._selection = _TorchStructuredSelection(
|
|
787
|
+
order=2 if inspection_only else 1,
|
|
788
|
+
output_component=output_component,
|
|
789
|
+
coordinate_component=coordinate_component,
|
|
790
|
+
packing="coordinates" if pack_coordinates else "single",
|
|
791
|
+
)
|
|
792
|
+
|
|
793
|
+
def _with_selection(
|
|
794
|
+
self, selection: _TorchStructuredSelection
|
|
795
|
+
) -> "TorchStructuredDerivativeView":
|
|
796
|
+
"""Clone this view while replacing only its typed selection state."""
|
|
797
|
+
view = type(self)(self._owner, self._name, self._views, self._labels)
|
|
798
|
+
view._selection = selection
|
|
799
|
+
return view
|
|
800
|
+
|
|
801
|
+
def with_component(
|
|
802
|
+
self, component: Literal["real", "imag"]
|
|
803
|
+
) -> "TorchStructuredDerivativeView":
|
|
804
|
+
"""Return a view selecting one output component."""
|
|
805
|
+
return self._with_selection(
|
|
806
|
+
replace(self._selection, output_component=component)
|
|
807
|
+
)
|
|
808
|
+
|
|
809
|
+
def with_coordinate_component(
|
|
810
|
+
self, component: Literal["real", "imag"]
|
|
811
|
+
) -> "TorchStructuredDerivativeView":
|
|
812
|
+
"""Select one second-input coordinate while preserving first-coordinate packing."""
|
|
813
|
+
return self._with_selection(
|
|
814
|
+
replace(self._selection, coordinate_component=component)
|
|
815
|
+
)
|
|
816
|
+
|
|
817
|
+
@property
|
|
818
|
+
def derivatives(self) -> TorchStructuredDerivativeCollection:
|
|
819
|
+
"""Return nested derivative selection for this view."""
|
|
820
|
+
if self._selection.order == 2:
|
|
821
|
+
raise RuntimeError(
|
|
822
|
+
"Third-order structured solver derivatives are unavailable."
|
|
823
|
+
)
|
|
824
|
+
collections: tuple[object, ...] = tuple(
|
|
825
|
+
getattr(view, "derivatives") for view in self._views
|
|
826
|
+
)
|
|
827
|
+
return TorchStructuredDerivativeCollection(
|
|
828
|
+
self._owner,
|
|
829
|
+
collections,
|
|
830
|
+
output_component=self._selection.output_component,
|
|
831
|
+
inspection_only=False,
|
|
832
|
+
)
|
|
833
|
+
|
|
834
|
+
def to_dict(self) -> Mapping[object, object]:
|
|
835
|
+
"""Export selected numeric leaves as Torch tensors."""
|
|
836
|
+
selection: _TorchStructuredSelection = self._selection
|
|
837
|
+
connected: bool = selection.order == 1
|
|
838
|
+
mappings: list[Mapping[object, object]] = [
|
|
839
|
+
cast(
|
|
840
|
+
Mapping[object, object],
|
|
841
|
+
convert_mapping(
|
|
842
|
+
getattr(view, "to_dict")(),
|
|
843
|
+
bindings={},
|
|
844
|
+
inputs=(),
|
|
845
|
+
torch_module=self._owner._torch,
|
|
846
|
+
),
|
|
847
|
+
)
|
|
848
|
+
for view in self._views
|
|
849
|
+
]
|
|
850
|
+
base_mapping: Mapping[object, object] = cast(
|
|
851
|
+
Mapping[object, object], getattr(self._views[0], "to_dict")()
|
|
852
|
+
)
|
|
853
|
+
if selection.packing == "coordinates":
|
|
854
|
+
output_component: Literal["real", "imag"] = (
|
|
855
|
+
selection.output_component or "real"
|
|
856
|
+
)
|
|
857
|
+
if selection.coordinate_component is not None:
|
|
858
|
+
if len(mappings) != 4:
|
|
859
|
+
raise ValueError(
|
|
860
|
+
"Nested structured derivative coordinates are incomplete."
|
|
861
|
+
)
|
|
862
|
+
selected_column: int = (
|
|
863
|
+
0 if selection.coordinate_component == "real" else 1
|
|
864
|
+
)
|
|
865
|
+
first_direction_index: int = selected_column
|
|
866
|
+
second_direction_index: int = selected_column + 2
|
|
867
|
+
mapping = _pack_structured_components(
|
|
868
|
+
base_mapping,
|
|
869
|
+
mappings[first_direction_index],
|
|
870
|
+
mappings[second_direction_index],
|
|
871
|
+
output_component,
|
|
872
|
+
self._owner._torch,
|
|
873
|
+
)
|
|
874
|
+
elif len(mappings) == 2:
|
|
875
|
+
mapping = _pack_structured_components(
|
|
876
|
+
base_mapping,
|
|
877
|
+
mappings[0],
|
|
878
|
+
mappings[1],
|
|
879
|
+
output_component,
|
|
880
|
+
self._owner._torch,
|
|
881
|
+
)
|
|
882
|
+
else:
|
|
883
|
+
raise ValueError(
|
|
884
|
+
"Structured derivative coordinate packing is incomplete."
|
|
885
|
+
)
|
|
886
|
+
elif selection.output_component is not None:
|
|
887
|
+
mapping = _project_structured_component(
|
|
888
|
+
base_mapping,
|
|
889
|
+
mappings[0],
|
|
890
|
+
selection.output_component,
|
|
891
|
+
self._owner._torch,
|
|
892
|
+
)
|
|
893
|
+
else:
|
|
894
|
+
mapping = mappings[0]
|
|
895
|
+
if not isinstance(mapping, Mapping):
|
|
896
|
+
return {}
|
|
897
|
+
sensitivity_directions: Mapping[str, object] = (
|
|
898
|
+
self._sensitivity_directions(base_mapping) if connected else {}
|
|
899
|
+
)
|
|
900
|
+
numeric_mapping: Mapping[object, object] = _without_structured_root_metadata(
|
|
901
|
+
mapping
|
|
902
|
+
)
|
|
903
|
+
metadata_mapping: Mapping[object, object] = {
|
|
904
|
+
key: value
|
|
905
|
+
for key, value in mapping.items()
|
|
906
|
+
if _is_structured_metadata_key(key, root=True)
|
|
907
|
+
}
|
|
908
|
+
numeric_directions: Mapping[str, object] = {
|
|
909
|
+
label: (
|
|
910
|
+
_without_structured_root_metadata(direction)
|
|
911
|
+
if isinstance(direction, Mapping)
|
|
912
|
+
else direction
|
|
913
|
+
)
|
|
914
|
+
for label, direction in sensitivity_directions.items()
|
|
915
|
+
}
|
|
916
|
+
selected_numeric: Mapping[object, object] = cast(
|
|
917
|
+
Mapping[object, object],
|
|
918
|
+
convert_mapping(
|
|
919
|
+
numeric_mapping,
|
|
920
|
+
bindings=self._owner._bindings if connected else {},
|
|
921
|
+
inputs=self._owner._inputs if connected else (),
|
|
922
|
+
torch_module=self._owner._torch,
|
|
923
|
+
derivative_mapping=numeric_directions if connected else None,
|
|
924
|
+
),
|
|
925
|
+
)
|
|
926
|
+
selected_metadata: Mapping[object, object] = cast(
|
|
927
|
+
Mapping[object, object],
|
|
928
|
+
convert_mapping(
|
|
929
|
+
metadata_mapping,
|
|
930
|
+
bindings={},
|
|
931
|
+
inputs=(),
|
|
932
|
+
torch_module=self._owner._torch,
|
|
933
|
+
),
|
|
934
|
+
)
|
|
935
|
+
selected: dict[object, object] = dict(selected_numeric)
|
|
936
|
+
selected.update(selected_metadata)
|
|
937
|
+
return selected
|
|
938
|
+
|
|
939
|
+
def _sensitivity_directions(
|
|
940
|
+
self, base_mapping: Mapping[object, object]
|
|
941
|
+
) -> Mapping[str, object]:
|
|
942
|
+
"""Return the selected sensitivity's second-order data by input label."""
|
|
943
|
+
selection: _TorchStructuredSelection = self._selection
|
|
944
|
+
pairs: Mapping[str, Mapping[str, object]] = (
|
|
945
|
+
self._owner._structured_second_derivatives()
|
|
946
|
+
)
|
|
947
|
+
directions: dict[str, object] = {}
|
|
948
|
+
bound_labels: tuple[str, ...] = coordinate_labels(self._owner._bindings)
|
|
949
|
+
for label in bound_labels:
|
|
950
|
+
coordinate_maps: list[Mapping[object, object]] = []
|
|
951
|
+
for first in self._labels:
|
|
952
|
+
branch: object = pairs.get(first, {}).get(label)
|
|
953
|
+
if isinstance(branch, Mapping):
|
|
954
|
+
coordinate_maps.append(
|
|
955
|
+
cast(
|
|
956
|
+
Mapping[object, object],
|
|
957
|
+
convert_mapping(
|
|
958
|
+
branch,
|
|
959
|
+
bindings={},
|
|
960
|
+
inputs=(),
|
|
961
|
+
torch_module=self._owner._torch,
|
|
962
|
+
),
|
|
963
|
+
)
|
|
964
|
+
)
|
|
965
|
+
if not coordinate_maps:
|
|
966
|
+
continue
|
|
967
|
+
if selection.packing == "coordinates":
|
|
968
|
+
if len(coordinate_maps) != 2:
|
|
969
|
+
directions[label] = {}
|
|
970
|
+
continue
|
|
971
|
+
output_component: Literal["real", "imag"] = (
|
|
972
|
+
selection.output_component or "real"
|
|
973
|
+
)
|
|
974
|
+
directions[label] = _pack_structured_components(
|
|
975
|
+
base_mapping,
|
|
976
|
+
coordinate_maps[0],
|
|
977
|
+
coordinate_maps[1],
|
|
978
|
+
output_component,
|
|
979
|
+
self._owner._torch,
|
|
980
|
+
)
|
|
981
|
+
elif selection.output_component is not None:
|
|
982
|
+
directions[label] = _project_structured_component(
|
|
983
|
+
base_mapping,
|
|
984
|
+
coordinate_maps[0],
|
|
985
|
+
selection.output_component,
|
|
986
|
+
self._owner._torch,
|
|
987
|
+
)
|
|
988
|
+
else:
|
|
989
|
+
directions[label] = coordinate_maps[0]
|
|
990
|
+
return directions
|
|
991
|
+
|
|
992
|
+
|
|
993
|
+
class _TableOrder(IntEnum):
|
|
994
|
+
"""Derivative selection order, matching the public depth convention."""
|
|
995
|
+
|
|
996
|
+
ROOT = 0
|
|
997
|
+
FIRST = 1
|
|
998
|
+
SECOND = 2
|
|
999
|
+
|
|
1000
|
+
|
|
1001
|
+
@dataclass(frozen=True, slots=True)
|
|
1002
|
+
class _TableSelection:
|
|
1003
|
+
"""Selection mode for a table derivative, separate from payload data."""
|
|
1004
|
+
|
|
1005
|
+
order: _TableOrder
|
|
1006
|
+
output_component: Literal["real", "imag"] | None = None
|
|
1007
|
+
input_coordinate: Literal["real", "imag"] | None = None
|
|
1008
|
+
|
|
1009
|
+
|
|
1010
|
+
class TorchTableDerivativeCollection:
|
|
1011
|
+
"""Select table derivatives through bound Project Key names."""
|
|
1012
|
+
|
|
1013
|
+
def __init__(
|
|
1014
|
+
self,
|
|
1015
|
+
owner: TorchPostprocessRecord,
|
|
1016
|
+
ordinary: object,
|
|
1017
|
+
*,
|
|
1018
|
+
depth: int,
|
|
1019
|
+
component: Literal["real", "imag"] | None = None,
|
|
1020
|
+
companion: object | None = None,
|
|
1021
|
+
) -> None:
|
|
1022
|
+
self._owner: TorchPostprocessRecord = owner
|
|
1023
|
+
self._ordinary: object = ordinary
|
|
1024
|
+
self._selection: _TableSelection = _TableSelection(
|
|
1025
|
+
_TableOrder(min(depth, 2)), component
|
|
1026
|
+
)
|
|
1027
|
+
self._companion: object | None = companion
|
|
1028
|
+
|
|
1029
|
+
def keys(self) -> tuple[str, ...]:
|
|
1030
|
+
"""Return the bound Project Keys available at this derivative order."""
|
|
1031
|
+
if self._selection.order == _TableOrder.SECOND:
|
|
1032
|
+
return ()
|
|
1033
|
+
available: object = getattr(self._ordinary, "keys")()
|
|
1034
|
+
solver_names: set[str] = set(cast(tuple[str, ...], available))
|
|
1035
|
+
return tuple(
|
|
1036
|
+
key
|
|
1037
|
+
for key, binding in self._owner._bindings.items()
|
|
1038
|
+
if any(label in solver_names for label in (binding_labels(binding)))
|
|
1039
|
+
)
|
|
1040
|
+
|
|
1041
|
+
def __getitem__(self, project_key: str) -> "TorchTableDerivativeView":
|
|
1042
|
+
"""Select one first- or second-order derivative by Project Key."""
|
|
1043
|
+
if self._selection.order == _TableOrder.SECOND:
|
|
1044
|
+
raise RuntimeError("Third-order table derivatives are unavailable.")
|
|
1045
|
+
try:
|
|
1046
|
+
binding: DerivativeBinding = self._owner._bindings[project_key]
|
|
1047
|
+
except KeyError:
|
|
1048
|
+
raise KeyError(project_key) from None
|
|
1049
|
+
labels: tuple[str, ...] = binding_labels(binding)
|
|
1050
|
+
available: set[str] = set(
|
|
1051
|
+
cast(tuple[str, ...], getattr(self._ordinary, "keys")())
|
|
1052
|
+
)
|
|
1053
|
+
selected_label: str | None = next(
|
|
1054
|
+
(label for label in labels if label in available), None
|
|
1055
|
+
)
|
|
1056
|
+
if selected_label is None:
|
|
1057
|
+
raise KeyError(f"derivatives[{project_key!r}]")
|
|
1058
|
+
selected: object = self._ordinary[selected_label] # type: ignore[index]
|
|
1059
|
+
companion: object | None = None
|
|
1060
|
+
coordinate_matrix: tuple[object, object, object, object] | None = None
|
|
1061
|
+
if isinstance(binding, ComplexDerivative):
|
|
1062
|
+
companion_label: str = next(
|
|
1063
|
+
(
|
|
1064
|
+
label
|
|
1065
|
+
for label in labels
|
|
1066
|
+
if label != selected_label and label in available
|
|
1067
|
+
),
|
|
1068
|
+
"",
|
|
1069
|
+
)
|
|
1070
|
+
if not companion_label:
|
|
1071
|
+
raise ValueError(
|
|
1072
|
+
f"Complex table-collection derivative {project_key!r} is incomplete."
|
|
1073
|
+
)
|
|
1074
|
+
companion = self._ordinary[companion_label] # type: ignore[index]
|
|
1075
|
+
if (
|
|
1076
|
+
self._selection.order != _TableOrder.ROOT
|
|
1077
|
+
and self._companion is not None
|
|
1078
|
+
):
|
|
1079
|
+
other_available: set[str] = set(
|
|
1080
|
+
cast(tuple[str, ...], getattr(self._companion, "keys")())
|
|
1081
|
+
)
|
|
1082
|
+
if not set(labels).issubset(other_available):
|
|
1083
|
+
raise ValueError(
|
|
1084
|
+
f"Complex table-collection derivative {project_key!r} "
|
|
1085
|
+
"has incomplete mixed-coordinate pairs."
|
|
1086
|
+
)
|
|
1087
|
+
coordinate_matrix = tuple(
|
|
1088
|
+
cast(object, collection[label]) # type: ignore[index]
|
|
1089
|
+
for collection in (self._ordinary, self._companion)
|
|
1090
|
+
for label in labels
|
|
1091
|
+
) # type: ignore[assignment]
|
|
1092
|
+
return TorchTableDerivativeView(
|
|
1093
|
+
self._owner,
|
|
1094
|
+
selected,
|
|
1095
|
+
project_key=project_key,
|
|
1096
|
+
solver_label=selected_label,
|
|
1097
|
+
depth=min(int(self._selection.order) + 1, 2),
|
|
1098
|
+
component=self._selection.output_component,
|
|
1099
|
+
binding=binding,
|
|
1100
|
+
companion=companion,
|
|
1101
|
+
coordinate_matrix=coordinate_matrix,
|
|
1102
|
+
)
|
|
1103
|
+
|
|
1104
|
+
|
|
1105
|
+
class TorchTableDerivativeView:
|
|
1106
|
+
"""Export a selected table sensitivity as Torch tensors."""
|
|
1107
|
+
|
|
1108
|
+
def __init__(
|
|
1109
|
+
self,
|
|
1110
|
+
owner: TorchPostprocessRecord,
|
|
1111
|
+
ordinary: object,
|
|
1112
|
+
*,
|
|
1113
|
+
project_key: str,
|
|
1114
|
+
solver_label: str,
|
|
1115
|
+
depth: int,
|
|
1116
|
+
component: Literal["real", "imag"] | None = None,
|
|
1117
|
+
binding: DerivativeBinding | None = None,
|
|
1118
|
+
companion: object | None = None,
|
|
1119
|
+
coordinate_matrix: tuple[object, object, object, object] | None = None,
|
|
1120
|
+
nested_coordinate: Literal["real", "imag"] | None = None,
|
|
1121
|
+
) -> None:
|
|
1122
|
+
self._owner: TorchPostprocessRecord = owner
|
|
1123
|
+
self._ordinary: object = ordinary
|
|
1124
|
+
self._project_key: str = project_key
|
|
1125
|
+
self._solver_label: str = solver_label
|
|
1126
|
+
self._selection: _TableSelection = _TableSelection(
|
|
1127
|
+
_TableOrder(min(depth, 2)), component, nested_coordinate
|
|
1128
|
+
)
|
|
1129
|
+
self._binding: DerivativeBinding | None = binding
|
|
1130
|
+
self._companion: object | None = companion
|
|
1131
|
+
self._coordinate_matrix = coordinate_matrix
|
|
1132
|
+
|
|
1133
|
+
@property
|
|
1134
|
+
def real(self) -> "TorchTableDerivativeView":
|
|
1135
|
+
"""Select the real output component before dictionary export.
|
|
1136
|
+
|
|
1137
|
+
For a nested complex-input derivative, select the second input's real
|
|
1138
|
+
coordinate instead. The first input's two coordinates remain packed
|
|
1139
|
+
in each complex value.
|
|
1140
|
+
"""
|
|
1141
|
+
return self._component_view("real")
|
|
1142
|
+
|
|
1143
|
+
@property
|
|
1144
|
+
def imag(self) -> "TorchTableDerivativeView":
|
|
1145
|
+
"""Select the imaginary output component before dictionary export.
|
|
1146
|
+
|
|
1147
|
+
For a nested complex-input derivative, select the second input's imaginary
|
|
1148
|
+
coordinate instead. The first input's two coordinates remain packed
|
|
1149
|
+
in each complex value.
|
|
1150
|
+
"""
|
|
1151
|
+
return self._component_view("imag")
|
|
1152
|
+
|
|
1153
|
+
def _component_view(
|
|
1154
|
+
self, component: Literal["real", "imag"]
|
|
1155
|
+
) -> "TorchTableDerivativeView":
|
|
1156
|
+
nested_coordinate: Literal["real", "imag"] | None = None
|
|
1157
|
+
selected_component: Literal["real", "imag"] = component
|
|
1158
|
+
depth: _TableOrder = self._selection.order
|
|
1159
|
+
if depth > 1 and self._coordinate_matrix is not None:
|
|
1160
|
+
nested_coordinate = component
|
|
1161
|
+
selected_component = cast(
|
|
1162
|
+
Literal["real", "imag"], self._selection.output_component
|
|
1163
|
+
)
|
|
1164
|
+
return TorchTableDerivativeView(
|
|
1165
|
+
self._owner,
|
|
1166
|
+
self._ordinary,
|
|
1167
|
+
project_key=self._project_key,
|
|
1168
|
+
solver_label=self._solver_label,
|
|
1169
|
+
depth=depth,
|
|
1170
|
+
component=selected_component,
|
|
1171
|
+
binding=self._binding,
|
|
1172
|
+
companion=self._companion,
|
|
1173
|
+
coordinate_matrix=self._coordinate_matrix,
|
|
1174
|
+
nested_coordinate=nested_coordinate,
|
|
1175
|
+
)
|
|
1176
|
+
|
|
1177
|
+
@property
|
|
1178
|
+
def derivatives(self) -> TorchTableDerivativeCollection:
|
|
1179
|
+
ordinary_collection: object = getattr(self._ordinary, "derivatives")
|
|
1180
|
+
companion_collection: object | None = (
|
|
1181
|
+
getattr(self._companion, "derivatives")
|
|
1182
|
+
if self._companion is not None
|
|
1183
|
+
else None
|
|
1184
|
+
)
|
|
1185
|
+
return TorchTableDerivativeCollection(
|
|
1186
|
+
self._owner,
|
|
1187
|
+
ordinary_collection,
|
|
1188
|
+
depth=self._selection.order,
|
|
1189
|
+
component=self._selection.output_component,
|
|
1190
|
+
companion=companion_collection,
|
|
1191
|
+
)
|
|
1192
|
+
|
|
1193
|
+
def to_dict(self) -> Mapping[object, object]:
|
|
1194
|
+
"""Return the selected table with dictionary-only Torch exports."""
|
|
1195
|
+
ordinary_values: object = getattr(self._ordinary, "to_dict")()
|
|
1196
|
+
if not isinstance(ordinary_values, Mapping):
|
|
1197
|
+
raise TypeError("A selected table derivative must export a mapping.")
|
|
1198
|
+
if (
|
|
1199
|
+
_contains_complex_numeric(ordinary_values)
|
|
1200
|
+
and self._selection.output_component is None
|
|
1201
|
+
):
|
|
1202
|
+
raise ValueError(
|
|
1203
|
+
"Select a complex table derivative output component with .real or .imag before export."
|
|
1204
|
+
)
|
|
1205
|
+
if self._selection.order == _TableOrder.SECOND:
|
|
1206
|
+
if self._coordinate_matrix is not None:
|
|
1207
|
+
pair_mappings: tuple[Mapping[object, object], ...] = tuple(
|
|
1208
|
+
cast(Mapping[object, object], getattr(view, "to_dict")())
|
|
1209
|
+
for view in self._coordinate_matrix
|
|
1210
|
+
)
|
|
1211
|
+
if self._selection.input_coordinate is None:
|
|
1212
|
+
raise ValueError(
|
|
1213
|
+
"Select the real or imaginary complex-input coordinate "
|
|
1214
|
+
"before exporting a nested table Hessian."
|
|
1215
|
+
)
|
|
1216
|
+
column_offset: int = (
|
|
1217
|
+
0 if self._selection.input_coordinate == "real" else 1
|
|
1218
|
+
)
|
|
1219
|
+
packed: Mapping[object, object] = _combine_table_directions(
|
|
1220
|
+
pair_mappings[column_offset],
|
|
1221
|
+
pair_mappings[column_offset + 2],
|
|
1222
|
+
self._selection.output_component,
|
|
1223
|
+
path=f"derivatives[{self._project_key!r}]",
|
|
1224
|
+
)
|
|
1225
|
+
return cast(
|
|
1226
|
+
Mapping[object, object],
|
|
1227
|
+
convert_mapping(
|
|
1228
|
+
packed,
|
|
1229
|
+
bindings={},
|
|
1230
|
+
inputs=(),
|
|
1231
|
+
torch_module=self._owner._torch,
|
|
1232
|
+
),
|
|
1233
|
+
)
|
|
1234
|
+
if self._companion is not None:
|
|
1235
|
+
companion_values: object = getattr(self._companion, "to_dict")()
|
|
1236
|
+
if not isinstance(companion_values, Mapping):
|
|
1237
|
+
raise TypeError(
|
|
1238
|
+
"A complex collection derivative must export a mapping."
|
|
1239
|
+
)
|
|
1240
|
+
ordinary_values = _combine_table_directions(
|
|
1241
|
+
ordinary_values,
|
|
1242
|
+
companion_values,
|
|
1243
|
+
self._selection.output_component,
|
|
1244
|
+
path=f"derivatives[{self._project_key!r}]",
|
|
1245
|
+
)
|
|
1246
|
+
converted: Mapping[object, object] = cast(
|
|
1247
|
+
Mapping[object, object],
|
|
1248
|
+
convert_mapping(
|
|
1249
|
+
ordinary_values,
|
|
1250
|
+
bindings={},
|
|
1251
|
+
inputs=(),
|
|
1252
|
+
torch_module=self._owner._torch,
|
|
1253
|
+
),
|
|
1254
|
+
)
|
|
1255
|
+
return _select_torch_component(
|
|
1256
|
+
converted,
|
|
1257
|
+
(
|
|
1258
|
+
None
|
|
1259
|
+
if self._companion is not None
|
|
1260
|
+
else self._selection.output_component
|
|
1261
|
+
),
|
|
1262
|
+
self._owner._torch,
|
|
1263
|
+
)
|
|
1264
|
+
payload: object = getattr(self._owner._record, "payload", None)
|
|
1265
|
+
if isinstance(payload, TableCollectionPayload):
|
|
1266
|
+
return self._collection_sensitivity_to_dict(
|
|
1267
|
+
cast(Mapping[object, object], ordinary_values)
|
|
1268
|
+
)
|
|
1269
|
+
labels: tuple[str, ...] = coordinate_labels(self._owner._bindings)
|
|
1270
|
+
selected_pairs: Mapping[str, Mapping[str, object]] = (
|
|
1271
|
+
self._owner._table_second_derivatives()
|
|
1272
|
+
)
|
|
1273
|
+
pair_data: dict[str, object] = {}
|
|
1274
|
+
pair_presence: dict[str, dict[str, object]] = {
|
|
1275
|
+
first_label: dict(second_pairs)
|
|
1276
|
+
for first_label, second_pairs in selected_pairs.items()
|
|
1277
|
+
}
|
|
1278
|
+
unavailable_pairs: tuple[tuple[str, str], ...] = missing_pairs(
|
|
1279
|
+
labels, pair_presence
|
|
1280
|
+
)
|
|
1281
|
+
if pair_presence and unavailable_pairs:
|
|
1282
|
+
formatted_missing: list[str] = [
|
|
1283
|
+
f"{first_label!r},{second_label!r}"
|
|
1284
|
+
for first_label, second_label in unavailable_pairs
|
|
1285
|
+
]
|
|
1286
|
+
raise ValueError(
|
|
1287
|
+
f"Incomplete table sensitivity pairs for Project Key "
|
|
1288
|
+
f"{self._project_key!r}: missing {formatted_missing!r}."
|
|
1289
|
+
)
|
|
1290
|
+
base_values: Mapping[object, object] = cast(
|
|
1291
|
+
Mapping[object, object], ordinary_values
|
|
1292
|
+
)
|
|
1293
|
+
complex_binding: bool = isinstance(self._binding, ComplexDerivative)
|
|
1294
|
+
if complex_binding:
|
|
1295
|
+
assert isinstance(self._binding, ComplexDerivative)
|
|
1296
|
+
table_payload: TablePayload = cast(
|
|
1297
|
+
TablePayload, getattr(self._owner._record, "payload")
|
|
1298
|
+
)
|
|
1299
|
+
companion: object = table_payload.derivatives[
|
|
1300
|
+
(
|
|
1301
|
+
self._binding.imaginary
|
|
1302
|
+
if self._solver_label == self._binding.real
|
|
1303
|
+
else self._binding.real
|
|
1304
|
+
)
|
|
1305
|
+
]
|
|
1306
|
+
companion_table_values: object = getattr(companion, "to_dict")()
|
|
1307
|
+
if not isinstance(companion_table_values, Mapping):
|
|
1308
|
+
raise TypeError("A complex table derivative must export a mapping.")
|
|
1309
|
+
base_values = _combine_table_directions(
|
|
1310
|
+
ordinary_values,
|
|
1311
|
+
cast(Mapping[object, object], companion_table_values),
|
|
1312
|
+
self._selection.output_component,
|
|
1313
|
+
path=f"derivatives[{self._project_key!r}]",
|
|
1314
|
+
)
|
|
1315
|
+
selected_row: Mapping[str, object] = selected_pairs.get(self._solver_label, {})
|
|
1316
|
+
if complex_binding:
|
|
1317
|
+
assert isinstance(self._binding, ComplexDerivative)
|
|
1318
|
+
companion_label: str = (
|
|
1319
|
+
self._binding.imaginary
|
|
1320
|
+
if self._solver_label == self._binding.real
|
|
1321
|
+
else self._binding.real
|
|
1322
|
+
)
|
|
1323
|
+
companion_row: Mapping[str, object] = selected_pairs.get(
|
|
1324
|
+
companion_label, {}
|
|
1325
|
+
)
|
|
1326
|
+
else:
|
|
1327
|
+
companion_row = {}
|
|
1328
|
+
for label, second_pair_record in selected_row.items():
|
|
1329
|
+
if complex_binding:
|
|
1330
|
+
second_pair: object = companion_row.get(label)
|
|
1331
|
+
if not isinstance(second_pair, Mapping):
|
|
1332
|
+
continue
|
|
1333
|
+
pair_data[label] = _combine_table_directions(
|
|
1334
|
+
cast(Mapping[object, object], second_pair_record),
|
|
1335
|
+
second_pair,
|
|
1336
|
+
self._selection.output_component,
|
|
1337
|
+
path=(
|
|
1338
|
+
f"derivatives[{self._project_key!r}]" f".derivatives[{label!r}]"
|
|
1339
|
+
),
|
|
1340
|
+
)
|
|
1341
|
+
else:
|
|
1342
|
+
pair_data[label] = second_pair_record
|
|
1343
|
+
converted = cast(
|
|
1344
|
+
Mapping[object, object],
|
|
1345
|
+
convert_mapping(
|
|
1346
|
+
base_values,
|
|
1347
|
+
bindings=self._owner._bindings if pair_data else {},
|
|
1348
|
+
inputs=self._owner._inputs if pair_data else (),
|
|
1349
|
+
torch_module=self._owner._torch,
|
|
1350
|
+
derivative_mapping=pair_data or None,
|
|
1351
|
+
third_order_boundary=bool(pair_data),
|
|
1352
|
+
),
|
|
1353
|
+
)
|
|
1354
|
+
return _select_torch_component(
|
|
1355
|
+
converted,
|
|
1356
|
+
None if complex_binding else self._selection.output_component,
|
|
1357
|
+
self._owner._torch,
|
|
1358
|
+
)
|
|
1359
|
+
|
|
1360
|
+
def _collection_sensitivity_to_dict(
|
|
1361
|
+
self, ordinary_values: Mapping[object, object]
|
|
1362
|
+
) -> Mapping[object, object]:
|
|
1363
|
+
"""Connect selected member sensitivities using only their own pair data."""
|
|
1364
|
+
labels: tuple[str, ...] = coordinate_labels(self._owner._bindings)
|
|
1365
|
+
pairs: dict[str, object] = {}
|
|
1366
|
+
derivative_collection: TableCollectionDerivativeCollection = cast(
|
|
1367
|
+
TableCollectionDerivativeView, self._ordinary
|
|
1368
|
+
).derivatives
|
|
1369
|
+
for label in labels:
|
|
1370
|
+
try:
|
|
1371
|
+
pair_view: TableCollectionDerivativeView = derivative_collection[label]
|
|
1372
|
+
except KeyError:
|
|
1373
|
+
continue
|
|
1374
|
+
pairs[label] = pair_view.to_dict()
|
|
1375
|
+
binding: DerivativeBinding | None = self._binding
|
|
1376
|
+
base_values: Mapping[object, object] = ordinary_values
|
|
1377
|
+
if isinstance(binding, ComplexDerivative):
|
|
1378
|
+
companion_label: str = (
|
|
1379
|
+
binding.imaginary
|
|
1380
|
+
if self._solver_label == binding.real
|
|
1381
|
+
else binding.real
|
|
1382
|
+
)
|
|
1383
|
+
try:
|
|
1384
|
+
companion_collection: TableCollectionPayload = cast(
|
|
1385
|
+
TableCollectionPayload,
|
|
1386
|
+
getattr(self._owner._record, "payload"),
|
|
1387
|
+
)
|
|
1388
|
+
companion_view: TableCollectionDerivativeView = (
|
|
1389
|
+
companion_collection.derivatives[companion_label]
|
|
1390
|
+
)
|
|
1391
|
+
companion_values: object = companion_view.to_dict()
|
|
1392
|
+
except KeyError:
|
|
1393
|
+
raise ValueError(
|
|
1394
|
+
f"Complex table-collection sensitivity {companion_label!r} is unavailable."
|
|
1395
|
+
) from None
|
|
1396
|
+
if not isinstance(companion_values, Mapping):
|
|
1397
|
+
raise TypeError(
|
|
1398
|
+
"A complex collection derivative must export a mapping."
|
|
1399
|
+
)
|
|
1400
|
+
companion_pairs: dict[str, object] = {}
|
|
1401
|
+
companion_derivatives: TableCollectionDerivativeCollection = (
|
|
1402
|
+
companion_view.derivatives
|
|
1403
|
+
)
|
|
1404
|
+
for label in labels:
|
|
1405
|
+
try:
|
|
1406
|
+
companion_pair: TableCollectionDerivativeView = (
|
|
1407
|
+
companion_derivatives[label]
|
|
1408
|
+
)
|
|
1409
|
+
except KeyError:
|
|
1410
|
+
continue
|
|
1411
|
+
companion_pairs[label] = companion_pair.to_dict()
|
|
1412
|
+
packed_pairs: dict[str, object] = {}
|
|
1413
|
+
for label, pair_values in pairs.items():
|
|
1414
|
+
companion_pair_values = companion_pairs.get(label)
|
|
1415
|
+
if not isinstance(companion_pair_values, Mapping):
|
|
1416
|
+
continue
|
|
1417
|
+
packed_pairs[label] = _combine_table_directions(
|
|
1418
|
+
cast(Mapping[object, object], pair_values),
|
|
1419
|
+
companion_pair_values,
|
|
1420
|
+
self._selection.output_component,
|
|
1421
|
+
path=(
|
|
1422
|
+
f"derivatives[{self._project_key!r}]" f".derivatives[{label!r}]"
|
|
1423
|
+
),
|
|
1424
|
+
)
|
|
1425
|
+
pairs = packed_pairs
|
|
1426
|
+
base_values = _combine_table_directions(
|
|
1427
|
+
ordinary_values,
|
|
1428
|
+
companion_values,
|
|
1429
|
+
self._selection.output_component,
|
|
1430
|
+
path=f"derivatives[{self._project_key!r}]",
|
|
1431
|
+
)
|
|
1432
|
+
if pairs:
|
|
1433
|
+
for member in ordinary_values:
|
|
1434
|
+
available_for_member: set[str] = {
|
|
1435
|
+
label
|
|
1436
|
+
for label, values in pairs.items()
|
|
1437
|
+
if isinstance(values, Mapping) and member in values
|
|
1438
|
+
}
|
|
1439
|
+
if available_for_member and available_for_member != set(labels):
|
|
1440
|
+
raise ValueError(
|
|
1441
|
+
"Incomplete table-collection sensitivity pairs for member "
|
|
1442
|
+
f"{member!r}: missing "
|
|
1443
|
+
f"{sorted(set(labels) - available_for_member)!r}."
|
|
1444
|
+
)
|
|
1445
|
+
converted: Mapping[object, object] = cast(
|
|
1446
|
+
Mapping[object, object],
|
|
1447
|
+
convert_mapping(
|
|
1448
|
+
base_values,
|
|
1449
|
+
bindings=self._owner._bindings if pairs else {},
|
|
1450
|
+
inputs=self._owner._inputs if pairs else (),
|
|
1451
|
+
torch_module=self._owner._torch,
|
|
1452
|
+
derivative_mapping=pairs if pairs else None,
|
|
1453
|
+
third_order_boundary=bool(pairs),
|
|
1454
|
+
),
|
|
1455
|
+
)
|
|
1456
|
+
return _select_torch_component(
|
|
1457
|
+
converted,
|
|
1458
|
+
(
|
|
1459
|
+
None
|
|
1460
|
+
if isinstance(binding, ComplexDerivative)
|
|
1461
|
+
else self._selection.output_component
|
|
1462
|
+
),
|
|
1463
|
+
self._owner._torch,
|
|
1464
|
+
)
|
|
1465
|
+
|
|
1466
|
+
def to_df(self, orient: str | None = None) -> object:
|
|
1467
|
+
"""Reject DataFrame export for Torch derivative views."""
|
|
1468
|
+
raise UnsupportedExportError(
|
|
1469
|
+
"to_df is not supported for Torch-bound derivatives; use untorch()."
|
|
1470
|
+
)
|
|
1471
|
+
|
|
1472
|
+
def to_xarray(self) -> object:
|
|
1473
|
+
"""Reject xarray export for Torch derivative views."""
|
|
1474
|
+
raise UnsupportedExportError(
|
|
1475
|
+
"to_xarray is not supported for Torch-bound derivatives; use untorch()."
|
|
1476
|
+
)
|
|
1477
|
+
|
|
1478
|
+
|
|
1479
|
+
def _contains_complex_numeric(value: object) -> bool:
|
|
1480
|
+
if isinstance(value, Mapping):
|
|
1481
|
+
return any(_contains_complex_numeric(item) for item in value.values())
|
|
1482
|
+
if isinstance(value, (list, tuple)):
|
|
1483
|
+
return any(_contains_complex_numeric(item) for item in value)
|
|
1484
|
+
if isinstance(value, complex):
|
|
1485
|
+
return True
|
|
1486
|
+
if isinstance(value, np.ndarray):
|
|
1487
|
+
return bool(value.dtype.kind == "c")
|
|
1488
|
+
return False
|
|
1489
|
+
|
|
1490
|
+
|
|
1491
|
+
def _combine_table_directions(
|
|
1492
|
+
first: Mapping[object, object],
|
|
1493
|
+
second: Mapping[object, object],
|
|
1494
|
+
component: Literal["real", "imag"] | None,
|
|
1495
|
+
*,
|
|
1496
|
+
path: str,
|
|
1497
|
+
) -> Mapping[object, object]:
|
|
1498
|
+
"""Pack two real-coordinate table directions into a complex tensor map."""
|
|
1499
|
+
combined: dict[object, object] = {}
|
|
1500
|
+
for key, left in first.items():
|
|
1501
|
+
right: object = second.get(key)
|
|
1502
|
+
if key in {"header", "title", "cost", "costs", "metadata"}:
|
|
1503
|
+
combined[key] = left
|
|
1504
|
+
elif isinstance(left, Mapping) and isinstance(right, Mapping):
|
|
1505
|
+
combined[key] = _combine_table_directions(
|
|
1506
|
+
left, right, component, path=f"{path}.{key}"
|
|
1507
|
+
)
|
|
1508
|
+
elif isinstance(left, np.ndarray) and isinstance(right, np.ndarray):
|
|
1509
|
+
if left.shape != right.shape:
|
|
1510
|
+
raise ValueError(
|
|
1511
|
+
f"Incompatible table sensitivity shapes at {path}.{key}: "
|
|
1512
|
+
f"{left.shape!r} and {right.shape!r}."
|
|
1513
|
+
)
|
|
1514
|
+
combined[key] = _pack_numeric_directions(left, right, component, np)
|
|
1515
|
+
elif isinstance(left, (int, float, complex, np.number)) and isinstance(
|
|
1516
|
+
right, (int, float, complex, np.number)
|
|
1517
|
+
):
|
|
1518
|
+
combined[key] = _pack_numeric_directions(
|
|
1519
|
+
complex(left), complex(right), component, np
|
|
1520
|
+
)
|
|
1521
|
+
elif key not in second:
|
|
1522
|
+
raise ValueError(f"Missing table sensitivity quantity at {path}.{key}.")
|
|
1523
|
+
else:
|
|
1524
|
+
combined[key] = left
|
|
1525
|
+
return combined
|
|
1526
|
+
|
|
1527
|
+
|
|
1528
|
+
def _select_torch_component(
|
|
1529
|
+
value: Mapping[object, object],
|
|
1530
|
+
component: Literal["real", "imag"] | None,
|
|
1531
|
+
torch_module: object,
|
|
1532
|
+
) -> Mapping[object, object]:
|
|
1533
|
+
if component is None:
|
|
1534
|
+
return value
|
|
1535
|
+
selected: dict[object, object] = {}
|
|
1536
|
+
|
|
1537
|
+
for key, item in value.items():
|
|
1538
|
+
if isinstance(item, Mapping):
|
|
1539
|
+
selected[key] = _select_torch_component(item, component, torch_module)
|
|
1540
|
+
elif isinstance(item, (list, tuple)):
|
|
1541
|
+
selected[key] = type(item)(
|
|
1542
|
+
(
|
|
1543
|
+
_project_numeric_component(entry, component, torch_module, "zero")
|
|
1544
|
+
if is_tensor(entry, torch_module)
|
|
1545
|
+
else entry
|
|
1546
|
+
)
|
|
1547
|
+
for entry in item
|
|
1548
|
+
)
|
|
1549
|
+
elif is_tensor(item, torch_module):
|
|
1550
|
+
selected[key] = _project_numeric_component(
|
|
1551
|
+
item, component, torch_module, "zero"
|
|
1552
|
+
)
|
|
1553
|
+
else:
|
|
1554
|
+
selected[key] = item
|
|
1555
|
+
return selected
|
|
1556
|
+
|
|
1557
|
+
|
|
1558
|
+
class TorchBatchPostprocessRecord(_TorchRecordData):
|
|
1559
|
+
"""Wrap one postprocess stream across a batch.
|
|
1560
|
+
|
|
1561
|
+
The ordinary :class:`jcmsuite.results.BatchPostprocessRecord` defines its
|
|
1562
|
+
batch navigation and export structure. This wrapper adds the Torch
|
|
1563
|
+
semantics of :class:`TorchPostprocessRecord` to each available entry,
|
|
1564
|
+
including tensor conversion and entry-specific autograd connections.
|
|
1565
|
+
|
|
1566
|
+
The collection returns this class. Do not construct it directly.
|
|
1567
|
+
"""
|
|
1568
|
+
|
|
1569
|
+
def __init__(
|
|
1570
|
+
self,
|
|
1571
|
+
record: object,
|
|
1572
|
+
bindings: BindingContext,
|
|
1573
|
+
inputs: InputContext,
|
|
1574
|
+
torch_module: object,
|
|
1575
|
+
) -> None:
|
|
1576
|
+
super().__init__(record, {}, (), torch_module)
|
|
1577
|
+
self._batch_bindings = bindings
|
|
1578
|
+
self._batch_inputs = inputs
|
|
1579
|
+
|
|
1580
|
+
def to_dict(self) -> Mapping[object, object]:
|
|
1581
|
+
"""Return one Torch-aware postprocess mapping per available batch entry.
|
|
1582
|
+
|
|
1583
|
+
The outer mapping uses original batch indices. Each value follows the
|
|
1584
|
+
single-result :meth:`TorchPostprocessRecord.to_dict` contract. Numeric
|
|
1585
|
+
values with solver derivatives connect to that entry's input tensors.
|
|
1586
|
+
|
|
1587
|
+
Returns
|
|
1588
|
+
-------
|
|
1589
|
+
Mapping[object, object]
|
|
1590
|
+
Available postprocess mappings keyed by original batch index.
|
|
1591
|
+
"""
|
|
1592
|
+
converted: dict[object, object] = {}
|
|
1593
|
+
records: object = getattr(self._record, "records")
|
|
1594
|
+
for batch_record in cast(Sequence[object], records):
|
|
1595
|
+
postprocesses: object = getattr(batch_record, "payload", None)
|
|
1596
|
+
index: int = cast(int, getattr(batch_record, "index"))
|
|
1597
|
+
postprocess_index: int = cast(int, getattr(self._record, "index"))
|
|
1598
|
+
if postprocesses is None or postprocess_index >= len(
|
|
1599
|
+
cast(Sequence[object], postprocesses)
|
|
1600
|
+
):
|
|
1601
|
+
continue
|
|
1602
|
+
selected: object = cast(Sequence[object], postprocesses)[postprocess_index]
|
|
1603
|
+
if not getattr(selected, "available", True):
|
|
1604
|
+
continue
|
|
1605
|
+
bindings: BindingMap = _context_binding(self._batch_bindings, index)
|
|
1606
|
+
inputs: tuple[TorchTensor, ...] = _context_inputs(self._batch_inputs, index)
|
|
1607
|
+
converted[index] = TorchPostprocessRecord(
|
|
1608
|
+
selected, bindings, inputs, self._torch
|
|
1609
|
+
).to_dict()
|
|
1610
|
+
return converted
|
|
1611
|
+
|
|
1612
|
+
@property
|
|
1613
|
+
def fields(self) -> "TorchBatchFieldExportPayload":
|
|
1614
|
+
"""Return the aggregate field view with per-entry Torch contexts.
|
|
1615
|
+
|
|
1616
|
+
Returns
|
|
1617
|
+
-------
|
|
1618
|
+
TorchBatchFieldExportPayload
|
|
1619
|
+
Batch field navigation and Torch-aware dictionary export.
|
|
1620
|
+
"""
|
|
1621
|
+
return TorchBatchFieldExportPayload(
|
|
1622
|
+
getattr(self._record, "fields"),
|
|
1623
|
+
self._batch_bindings,
|
|
1624
|
+
self._batch_inputs,
|
|
1625
|
+
self._torch,
|
|
1626
|
+
)
|
|
1627
|
+
|
|
1628
|
+
|
|
1629
|
+
class TorchBatchFieldExportPayload:
|
|
1630
|
+
"""Provide Torch-aware dictionary exports for fields across a batch.
|
|
1631
|
+
|
|
1632
|
+
The ordinary :class:`jcmsuite.results.BatchFieldExportPayload` defines the
|
|
1633
|
+
batch navigation and export structure. This wrapper adds the Torch field
|
|
1634
|
+
semantics of :class:`TorchFieldExportPayload` to each available entry.
|
|
1635
|
+
Operations retain original batch indices. The ``to_dict()`` method returns
|
|
1636
|
+
one mapping per available entry and converts numeric values to Torch
|
|
1637
|
+
tensors. Solver derivatives connect each tensor to its matching input.
|
|
1638
|
+
|
|
1639
|
+
The ``derivatives`` property returns a Torch-specific lookup keyed by bound
|
|
1640
|
+
project key name. Each derivative export uses that entry's derivative
|
|
1641
|
+
bindings and remains keyed by original batch index. The collection is empty
|
|
1642
|
+
when no differentiable inputs are bound.
|
|
1643
|
+
|
|
1644
|
+
A Torch batch postprocess record returns this class. Do not construct it
|
|
1645
|
+
directly.
|
|
1646
|
+
"""
|
|
1647
|
+
|
|
1648
|
+
def __init__(
|
|
1649
|
+
self,
|
|
1650
|
+
payload: object,
|
|
1651
|
+
bindings: BindingContext,
|
|
1652
|
+
inputs: InputContext,
|
|
1653
|
+
torch_module: object,
|
|
1654
|
+
transforms: tuple[_TransformName, ...] = (),
|
|
1655
|
+
) -> None:
|
|
1656
|
+
self._payload = payload
|
|
1657
|
+
self._bindings = bindings
|
|
1658
|
+
self._inputs = inputs
|
|
1659
|
+
self._torch = torch_module
|
|
1660
|
+
self._transforms = transforms
|
|
1661
|
+
|
|
1662
|
+
def __getattr__(self, name: str) -> object:
|
|
1663
|
+
return getattr(self._payload, name)
|
|
1664
|
+
|
|
1665
|
+
def to_dict(self) -> Mapping[int, Mapping[object, object]]:
|
|
1666
|
+
"""Return field mappings keyed by original batch index.
|
|
1667
|
+
|
|
1668
|
+
Each available entry is converted by the single-result field wrapper.
|
|
1669
|
+
Numeric field values are Torch tensors. When solver derivatives are
|
|
1670
|
+
available, each field tensor connects to the matching entry's input
|
|
1671
|
+
tensors. Field transforms apply the same derivative rules as the
|
|
1672
|
+
single-result Torch field wrapper.
|
|
1673
|
+
|
|
1674
|
+
Returns
|
|
1675
|
+
-------
|
|
1676
|
+
Mapping[int, Mapping[object, object]]
|
|
1677
|
+
Available field mappings keyed by original batch index.
|
|
1678
|
+
"""
|
|
1679
|
+
converted: dict[int, Mapping[object, object]] = {}
|
|
1680
|
+
for record in cast(Sequence[object], getattr(self._payload, "records")):
|
|
1681
|
+
payload: object = getattr(record, "payload", None)
|
|
1682
|
+
if payload is None:
|
|
1683
|
+
continue
|
|
1684
|
+
index: int = cast(int, getattr(record, "index"))
|
|
1685
|
+
field: TorchFieldExportPayload = TorchFieldExportPayload(
|
|
1686
|
+
payload,
|
|
1687
|
+
_context_binding(self._bindings, index),
|
|
1688
|
+
_context_inputs(self._inputs, index),
|
|
1689
|
+
self._torch,
|
|
1690
|
+
)
|
|
1691
|
+
for operation in self._transforms:
|
|
1692
|
+
field = (
|
|
1693
|
+
cast(TorchFieldExportPayload, field.intensity)
|
|
1694
|
+
if operation == "intensity"
|
|
1695
|
+
else field.transform(operation)
|
|
1696
|
+
)
|
|
1697
|
+
converted[index] = field.to_dict()
|
|
1698
|
+
return converted
|
|
1699
|
+
|
|
1700
|
+
def to_df(self, orient: str | None = None) -> object:
|
|
1701
|
+
"""Raise because Torch-bound batch fields do not support DataFrame export.
|
|
1702
|
+
|
|
1703
|
+
Parameters
|
|
1704
|
+
----------
|
|
1705
|
+
orient : str | None, optional
|
|
1706
|
+
DataFrame orientation. The value does not change the error.
|
|
1707
|
+
|
|
1708
|
+
Returns
|
|
1709
|
+
-------
|
|
1710
|
+
object
|
|
1711
|
+
This method does not return.
|
|
1712
|
+
|
|
1713
|
+
Raises
|
|
1714
|
+
------
|
|
1715
|
+
UnsupportedExportError
|
|
1716
|
+
Always. Use the underlying ordinary batch result for DataFrame export.
|
|
1717
|
+
"""
|
|
1718
|
+
raise UnsupportedExportError(
|
|
1719
|
+
"to_df is not supported for Torch-bound results; use untorch() for ordinary DataFrame exports."
|
|
1720
|
+
)
|
|
1721
|
+
|
|
1722
|
+
def to_xarray(self) -> object:
|
|
1723
|
+
"""Raise because Torch-bound batch fields do not support xarray export.
|
|
1724
|
+
|
|
1725
|
+
Returns
|
|
1726
|
+
-------
|
|
1727
|
+
object
|
|
1728
|
+
This method does not return.
|
|
1729
|
+
|
|
1730
|
+
Raises
|
|
1731
|
+
------
|
|
1732
|
+
UnsupportedExportError
|
|
1733
|
+
Always. Use the underlying ordinary batch result for xarray export.
|
|
1734
|
+
"""
|
|
1735
|
+
raise UnsupportedExportError(
|
|
1736
|
+
"to_xarray is not supported for Torch-bound results."
|
|
1737
|
+
)
|
|
1738
|
+
|
|
1739
|
+
def _view(self, name: str, *args: object) -> "TorchBatchFieldExportPayload":
|
|
1740
|
+
operation: Callable[..., object] = cast(
|
|
1741
|
+
Callable[..., object], getattr(self._payload, name)
|
|
1742
|
+
)
|
|
1743
|
+
return TorchBatchFieldExportPayload(
|
|
1744
|
+
operation(*args),
|
|
1745
|
+
self._bindings,
|
|
1746
|
+
self._inputs,
|
|
1747
|
+
self._torch,
|
|
1748
|
+
self._transforms,
|
|
1749
|
+
)
|
|
1750
|
+
|
|
1751
|
+
@property
|
|
1752
|
+
def base(self) -> "TorchBatchFieldExportPayload":
|
|
1753
|
+
"""Return the batch field view without solver derivative branches.
|
|
1754
|
+
|
|
1755
|
+
Returns
|
|
1756
|
+
-------
|
|
1757
|
+
TorchBatchFieldExportPayload
|
|
1758
|
+
Base fields for all available batch entries.
|
|
1759
|
+
"""
|
|
1760
|
+
return TorchBatchFieldExportPayload(
|
|
1761
|
+
getattr(self._payload, "base"),
|
|
1762
|
+
self._bindings,
|
|
1763
|
+
self._inputs,
|
|
1764
|
+
self._torch,
|
|
1765
|
+
self._transforms,
|
|
1766
|
+
)
|
|
1767
|
+
|
|
1768
|
+
@property
|
|
1769
|
+
def intensity(self) -> "TorchBatchIntensityFieldExportPayload":
|
|
1770
|
+
"""Return the squared-norm intensity view for the batch.
|
|
1771
|
+
|
|
1772
|
+
Returns
|
|
1773
|
+
-------
|
|
1774
|
+
TorchBatchIntensityFieldExportPayload
|
|
1775
|
+
Non-transformable intensity fields for all available batch entries.
|
|
1776
|
+
"""
|
|
1777
|
+
if "intensity" in self._transforms:
|
|
1778
|
+
raise AttributeError(
|
|
1779
|
+
"TorchBatchFieldExportPayload does not support intensity()."
|
|
1780
|
+
)
|
|
1781
|
+
return TorchBatchIntensityFieldExportPayload(
|
|
1782
|
+
TorchBatchFieldExportPayload(
|
|
1783
|
+
self._payload,
|
|
1784
|
+
self._bindings,
|
|
1785
|
+
self._inputs,
|
|
1786
|
+
self._torch,
|
|
1787
|
+
(*self._transforms, "intensity"),
|
|
1788
|
+
)
|
|
1789
|
+
)
|
|
1790
|
+
|
|
1791
|
+
@property
|
|
1792
|
+
def derivatives(self) -> "TorchBatchFieldDerivativeCollection":
|
|
1793
|
+
"""Return binding-aware solver derivative lookup across the batch.
|
|
1794
|
+
|
|
1795
|
+
Returns
|
|
1796
|
+
-------
|
|
1797
|
+
TorchBatchFieldDerivativeCollection
|
|
1798
|
+
Derivative lookup by differentiable project key name. A lookup
|
|
1799
|
+
returns detached Torch derivative mappings keyed by original batch
|
|
1800
|
+
index. The collection is empty when no differentiable inputs are
|
|
1801
|
+
bound.
|
|
1802
|
+
"""
|
|
1803
|
+
return TorchBatchFieldDerivativeCollection(self)
|
|
1804
|
+
|
|
1805
|
+
def select(self, index: int | None = None) -> "TorchBatchFieldExportPayload":
|
|
1806
|
+
"""Select a field position across available batch entries.
|
|
1807
|
+
|
|
1808
|
+
Parameters
|
|
1809
|
+
----------
|
|
1810
|
+
index : int | None, optional
|
|
1811
|
+
Field position. ``None`` selects all field positions.
|
|
1812
|
+
|
|
1813
|
+
Returns
|
|
1814
|
+
-------
|
|
1815
|
+
TorchBatchFieldExportPayload
|
|
1816
|
+
Selected fields with original batch indices.
|
|
1817
|
+
"""
|
|
1818
|
+
return self._view("select", index)
|
|
1819
|
+
|
|
1820
|
+
def transform(self, name: str) -> "TorchBatchFieldExportPayload":
|
|
1821
|
+
"""Transform fields across the batch and retain input gradients.
|
|
1822
|
+
|
|
1823
|
+
Parameters
|
|
1824
|
+
----------
|
|
1825
|
+
name : str
|
|
1826
|
+
One of ``"abs"``, ``"real"``, ``"imag"``, or ``"phase"``.
|
|
1827
|
+
|
|
1828
|
+
Returns
|
|
1829
|
+
-------
|
|
1830
|
+
TorchBatchFieldExportPayload
|
|
1831
|
+
Transformed fields with original batch indices.
|
|
1832
|
+
|
|
1833
|
+
Raises
|
|
1834
|
+
------
|
|
1835
|
+
ValueError
|
|
1836
|
+
If ``name`` is not supported.
|
|
1837
|
+
AttributeError
|
|
1838
|
+
If this is an intensity view.
|
|
1839
|
+
"""
|
|
1840
|
+
if "intensity" in self._transforms:
|
|
1841
|
+
raise AttributeError(
|
|
1842
|
+
"TorchBatchFieldExportPayload does not support transform()."
|
|
1843
|
+
)
|
|
1844
|
+
if name not in _TRANSFORM_NAMES:
|
|
1845
|
+
raise ValueError(
|
|
1846
|
+
"transform must be one of 'abs', 'real', 'imag', or 'phase'"
|
|
1847
|
+
)
|
|
1848
|
+
return TorchBatchFieldExportPayload(
|
|
1849
|
+
self._payload,
|
|
1850
|
+
self._bindings,
|
|
1851
|
+
self._inputs,
|
|
1852
|
+
self._torch,
|
|
1853
|
+
(*self._transforms, cast(_TransformName, name)),
|
|
1854
|
+
)
|
|
1855
|
+
|
|
1856
|
+
def __getitem__(self, key: object) -> "TorchBatchFieldExportPayload":
|
|
1857
|
+
"""Select a named field quantity across the batch.
|
|
1858
|
+
|
|
1859
|
+
Parameters
|
|
1860
|
+
----------
|
|
1861
|
+
key : object
|
|
1862
|
+
Field quantity name or nested mapping key.
|
|
1863
|
+
|
|
1864
|
+
Returns
|
|
1865
|
+
-------
|
|
1866
|
+
TorchBatchFieldExportPayload
|
|
1867
|
+
Selected fields with original batch indices.
|
|
1868
|
+
"""
|
|
1869
|
+
return TorchBatchFieldExportPayload(
|
|
1870
|
+
self._payload[key], # type: ignore[index]
|
|
1871
|
+
self._bindings,
|
|
1872
|
+
self._inputs,
|
|
1873
|
+
self._torch,
|
|
1874
|
+
self._transforms,
|
|
1875
|
+
)
|
|
1876
|
+
|
|
1877
|
+
|
|
1878
|
+
class TorchBatchIntensityFieldExportPayload:
|
|
1879
|
+
"""Provide a non-transformable Torch intensity view across a batch.
|
|
1880
|
+
|
|
1881
|
+
This wrapper mirrors :class:`TorchIntensityFieldExportPayload` over the
|
|
1882
|
+
ordinary :class:`jcmsuite.results.BatchIntensityFieldExportPayload`.
|
|
1883
|
+
Dictionary exports retain original batch indices and connect each entry to
|
|
1884
|
+
its matching input when solver derivatives are available.
|
|
1885
|
+
|
|
1886
|
+
:attr:`TorchBatchFieldExportPayload.intensity` returns this class. Do not
|
|
1887
|
+
construct it directly.
|
|
1888
|
+
"""
|
|
1889
|
+
|
|
1890
|
+
def __init__(self, view: TorchBatchFieldExportPayload) -> None:
|
|
1891
|
+
self._view = view
|
|
1892
|
+
|
|
1893
|
+
def __getattr__(self, name: str) -> object:
|
|
1894
|
+
if name in {"intensity", "transform"}:
|
|
1895
|
+
raise AttributeError(f"{type(self).__name__!s} does not support {name}().")
|
|
1896
|
+
return getattr(self._view, name)
|
|
1897
|
+
|
|
1898
|
+
@property
|
|
1899
|
+
def base(self) -> "TorchBatchIntensityFieldExportPayload":
|
|
1900
|
+
"""Return the intensity view without solver derivative branches.
|
|
1901
|
+
|
|
1902
|
+
Returns
|
|
1903
|
+
-------
|
|
1904
|
+
TorchBatchIntensityFieldExportPayload
|
|
1905
|
+
Base intensity fields for available batch entries.
|
|
1906
|
+
"""
|
|
1907
|
+
return TorchBatchIntensityFieldExportPayload(self._view.base)
|
|
1908
|
+
|
|
1909
|
+
@property
|
|
1910
|
+
def derivatives(self) -> "TorchBatchFieldDerivativeCollection":
|
|
1911
|
+
"""Return binding-aware derivatives for the batch intensity.
|
|
1912
|
+
|
|
1913
|
+
Returns
|
|
1914
|
+
-------
|
|
1915
|
+
TorchBatchFieldDerivativeCollection
|
|
1916
|
+
Derivative lookup keyed by differentiable project key name. Each
|
|
1917
|
+
payload retains original batch indices.
|
|
1918
|
+
"""
|
|
1919
|
+
return self._view.derivatives
|
|
1920
|
+
|
|
1921
|
+
def select(
|
|
1922
|
+
self, index: int | None = None
|
|
1923
|
+
) -> "TorchBatchIntensityFieldExportPayload":
|
|
1924
|
+
"""Select field positions across the batch.
|
|
1925
|
+
|
|
1926
|
+
Parameters
|
|
1927
|
+
----------
|
|
1928
|
+
index : int | None, optional
|
|
1929
|
+
Field position. ``None`` selects all positions.
|
|
1930
|
+
|
|
1931
|
+
Returns
|
|
1932
|
+
-------
|
|
1933
|
+
TorchBatchIntensityFieldExportPayload
|
|
1934
|
+
Selected intensity fields with original batch indices.
|
|
1935
|
+
"""
|
|
1936
|
+
return TorchBatchIntensityFieldExportPayload(self._view.select(index))
|
|
1937
|
+
|
|
1938
|
+
def to_dict(self) -> Mapping[int, Mapping[object, object]]:
|
|
1939
|
+
"""Return Torch intensity dictionaries keyed by original batch index.
|
|
1940
|
+
|
|
1941
|
+
Returns
|
|
1942
|
+
-------
|
|
1943
|
+
Mapping[int, Mapping[object, object]]
|
|
1944
|
+
Available intensity mappings. Solver derivatives connect each
|
|
1945
|
+
intensity tensor to its matching input tensor.
|
|
1946
|
+
"""
|
|
1947
|
+
return self._view.to_dict()
|
|
1948
|
+
|
|
1949
|
+
def __getitem__(self, key: object) -> "TorchBatchIntensityFieldExportPayload":
|
|
1950
|
+
"""Select a named intensity field quantity across the batch.
|
|
1951
|
+
|
|
1952
|
+
Parameters
|
|
1953
|
+
----------
|
|
1954
|
+
key : object
|
|
1955
|
+
Field quantity name or nested mapping key.
|
|
1956
|
+
|
|
1957
|
+
Returns
|
|
1958
|
+
-------
|
|
1959
|
+
TorchBatchIntensityFieldExportPayload
|
|
1960
|
+
Selected intensity fields with original batch indices.
|
|
1961
|
+
"""
|
|
1962
|
+
return TorchBatchIntensityFieldExportPayload(self._view[key])
|
|
1963
|
+
|
|
1964
|
+
def to_df(self, orient: str | None = None) -> object:
|
|
1965
|
+
"""Raise because Torch intensity fields do not support DataFrame export.
|
|
1966
|
+
|
|
1967
|
+
Parameters
|
|
1968
|
+
----------
|
|
1969
|
+
orient : str | None, optional
|
|
1970
|
+
DataFrame orientation. The value does not change the error.
|
|
1971
|
+
|
|
1972
|
+
Returns
|
|
1973
|
+
-------
|
|
1974
|
+
object
|
|
1975
|
+
This method does not return.
|
|
1976
|
+
|
|
1977
|
+
Raises
|
|
1978
|
+
------
|
|
1979
|
+
UnsupportedExportError
|
|
1980
|
+
Always. Use the ordinary batch result for DataFrame export.
|
|
1981
|
+
"""
|
|
1982
|
+
return self._view.to_df(orient=orient)
|
|
1983
|
+
|
|
1984
|
+
def to_xarray(self) -> object:
|
|
1985
|
+
"""Raise because Torch intensity fields do not support xarray export.
|
|
1986
|
+
|
|
1987
|
+
Returns
|
|
1988
|
+
-------
|
|
1989
|
+
object
|
|
1990
|
+
This method does not return.
|
|
1991
|
+
|
|
1992
|
+
Raises
|
|
1993
|
+
------
|
|
1994
|
+
UnsupportedExportError
|
|
1995
|
+
Always. Use the ordinary batch result for xarray export.
|
|
1996
|
+
"""
|
|
1997
|
+
return self._view.to_xarray()
|
|
1998
|
+
|
|
1999
|
+
|
|
2000
|
+
def _context_binding(context: BindingContext, index: int) -> BindingMap:
|
|
2001
|
+
return context[index] if isinstance(context, tuple) else context
|
|
2002
|
+
|
|
2003
|
+
|
|
2004
|
+
def _context_inputs(context: InputContext, index: int) -> tuple[TorchTensor, ...]:
|
|
2005
|
+
return (
|
|
2006
|
+
cast(tuple[tuple[TorchTensor, ...], ...], context)[index]
|
|
2007
|
+
if context and isinstance(context[0], tuple)
|
|
2008
|
+
else context
|
|
2009
|
+
)
|
|
2010
|
+
|
|
2011
|
+
|
|
2012
|
+
class _TorchFieldView(_TorchRecordData):
|
|
2013
|
+
"""Provide shared selection and derivative navigation for Torch field views."""
|
|
2014
|
+
|
|
2015
|
+
def _view(
|
|
2016
|
+
self,
|
|
2017
|
+
record: object,
|
|
2018
|
+
*,
|
|
2019
|
+
transforms: tuple[_TransformName, ...] | None = None,
|
|
2020
|
+
) -> Self:
|
|
2021
|
+
return type(self)(
|
|
2022
|
+
record,
|
|
2023
|
+
self._bindings,
|
|
2024
|
+
self._inputs,
|
|
2025
|
+
self._torch,
|
|
2026
|
+
transforms=self._transforms if transforms is None else transforms,
|
|
2027
|
+
)
|
|
2028
|
+
|
|
2029
|
+
@property
|
|
2030
|
+
def base(self) -> Self:
|
|
2031
|
+
"""Return the current field view without solver derivative branches.
|
|
2032
|
+
|
|
2033
|
+
Returns
|
|
2034
|
+
-------
|
|
2035
|
+
Self
|
|
2036
|
+
New view with the current field selection and transforms, but
|
|
2037
|
+
without solver derivative branches.
|
|
2038
|
+
"""
|
|
2039
|
+
return self._view(getattr(self._record, "base"))
|
|
2040
|
+
|
|
2041
|
+
@property
|
|
2042
|
+
def derivatives(self) -> "TorchFieldDerivativeCollection":
|
|
2043
|
+
"""Return field derivatives for bound project keys.
|
|
2044
|
+
|
|
2045
|
+
A lookup on the returned collection gives a
|
|
2046
|
+
:class:`TorchFieldDerivativePayload` for a real input or a
|
|
2047
|
+
:class:`TorchComplexFieldDerivativePayload` for a complex input. The
|
|
2048
|
+
collection is empty when no differentiable inputs are bound.
|
|
2049
|
+
|
|
2050
|
+
Returns
|
|
2051
|
+
-------
|
|
2052
|
+
TorchFieldDerivativeCollection
|
|
2053
|
+
Torch-specific derivative lookup keyed by differentiable project key.
|
|
2054
|
+
"""
|
|
2055
|
+
return TorchFieldDerivativeCollection(self)
|
|
2056
|
+
|
|
2057
|
+
def select(self, index: int | None = None) -> Self:
|
|
2058
|
+
"""Select field positions while retaining this view's operations.
|
|
2059
|
+
|
|
2060
|
+
Parameters
|
|
2061
|
+
----------
|
|
2062
|
+
index : int | None, optional
|
|
2063
|
+
Field position. ``None`` selects all field positions.
|
|
2064
|
+
|
|
2065
|
+
Returns
|
|
2066
|
+
-------
|
|
2067
|
+
Self
|
|
2068
|
+
New view with the requested field selection.
|
|
2069
|
+
"""
|
|
2070
|
+
return self._view(getattr(self._record, "select")(index))
|
|
2071
|
+
|
|
2072
|
+
def __getitem__(self, key: object) -> Self:
|
|
2073
|
+
"""Select a field quantity or nested mapping entry.
|
|
2074
|
+
|
|
2075
|
+
Parameters
|
|
2076
|
+
----------
|
|
2077
|
+
key : object
|
|
2078
|
+
Field quantity name or nested mapping key.
|
|
2079
|
+
|
|
2080
|
+
Returns
|
|
2081
|
+
-------
|
|
2082
|
+
Self
|
|
2083
|
+
New view for the selected field data.
|
|
2084
|
+
"""
|
|
2085
|
+
return self._view(self._record[key]) # type: ignore[index]
|
|
2086
|
+
|
|
2087
|
+
|
|
2088
|
+
class TorchFieldExportPayload(_TorchFieldView):
|
|
2089
|
+
"""Provide Torch-aware views of ordinary field-export data.
|
|
2090
|
+
|
|
2091
|
+
The class mirrors :class:`jcmsuite.results.FieldExportPayload`. Its views
|
|
2092
|
+
retain the current field selection and transformation chain. Derivative
|
|
2093
|
+
lookup returns Torch derivative payloads for bound project keys. It returns
|
|
2094
|
+
an empty collection when no differentiable inputs are bound.
|
|
2095
|
+
"""
|
|
2096
|
+
|
|
2097
|
+
@property
|
|
2098
|
+
def base(self) -> "TorchFieldExportPayload":
|
|
2099
|
+
"""Return a base-only field payload.
|
|
2100
|
+
|
|
2101
|
+
Returns
|
|
2102
|
+
-------
|
|
2103
|
+
TorchFieldExportPayload
|
|
2104
|
+
Field view without solver derivative branches.
|
|
2105
|
+
"""
|
|
2106
|
+
return super().base
|
|
2107
|
+
|
|
2108
|
+
@property
|
|
2109
|
+
def derivatives(
|
|
2110
|
+
self,
|
|
2111
|
+
) -> "TorchFieldDerivativeCollection":
|
|
2112
|
+
"""Return Torch-specific derivative lookup.
|
|
2113
|
+
|
|
2114
|
+
Returns
|
|
2115
|
+
-------
|
|
2116
|
+
TorchFieldDerivativeCollection
|
|
2117
|
+
Derivative lookup keyed by differentiable project key name. The
|
|
2118
|
+
collection is empty when no differentiable inputs are bound.
|
|
2119
|
+
"""
|
|
2120
|
+
return super().derivatives
|
|
2121
|
+
|
|
2122
|
+
def select(self, index: int | None = None) -> "TorchFieldExportPayload":
|
|
2123
|
+
"""Return a field payload with the requested field positions.
|
|
2124
|
+
|
|
2125
|
+
Parameters
|
|
2126
|
+
----------
|
|
2127
|
+
index : int | None, optional
|
|
2128
|
+
Field position. ``None`` selects all field positions.
|
|
2129
|
+
|
|
2130
|
+
Returns
|
|
2131
|
+
-------
|
|
2132
|
+
TorchFieldExportPayload
|
|
2133
|
+
New field payload with the requested selection.
|
|
2134
|
+
"""
|
|
2135
|
+
return super().select(index)
|
|
2136
|
+
|
|
2137
|
+
def __getitem__(self, key: object) -> "TorchFieldExportPayload":
|
|
2138
|
+
"""Return a field payload for a named or nested field value.
|
|
2139
|
+
|
|
2140
|
+
Parameters
|
|
2141
|
+
----------
|
|
2142
|
+
key : object
|
|
2143
|
+
Field quantity name or nested mapping key.
|
|
2144
|
+
|
|
2145
|
+
Returns
|
|
2146
|
+
-------
|
|
2147
|
+
TorchFieldExportPayload
|
|
2148
|
+
New field payload for the selected value.
|
|
2149
|
+
"""
|
|
2150
|
+
return super().__getitem__(key)
|
|
2151
|
+
|
|
2152
|
+
@property
|
|
2153
|
+
def intensity(self) -> TorchIntensityFieldExportPayload:
|
|
2154
|
+
"""Return a real-valued squared-norm intensity view.
|
|
2155
|
+
|
|
2156
|
+
Returns
|
|
2157
|
+
-------
|
|
2158
|
+
TorchIntensityFieldExportPayload
|
|
2159
|
+
Non-transformable intensity view. Its field values retain Torch
|
|
2160
|
+
connections to bound input tensors when solver derivatives exist.
|
|
2161
|
+
"""
|
|
2162
|
+
return TorchIntensityFieldExportPayload(
|
|
2163
|
+
self._record,
|
|
2164
|
+
self._bindings,
|
|
2165
|
+
self._inputs,
|
|
2166
|
+
self._torch,
|
|
2167
|
+
transforms=(*self._transforms, "intensity"),
|
|
2168
|
+
)
|
|
2169
|
+
|
|
2170
|
+
def transform(self, operation: str) -> "TorchFieldExportPayload":
|
|
2171
|
+
"""Add a field transformation to this view.
|
|
2172
|
+
|
|
2173
|
+
Apply transforms before derivative lookup to request the derivative of the
|
|
2174
|
+
transformed field. The transforms and field selection can be chained in
|
|
2175
|
+
either order.
|
|
2176
|
+
|
|
2177
|
+
Parameters
|
|
2178
|
+
----------
|
|
2179
|
+
operation : str
|
|
2180
|
+
One of ``"abs"``, ``"real"``, ``"imag"``, or ``"phase"``.
|
|
2181
|
+
|
|
2182
|
+
Returns
|
|
2183
|
+
-------
|
|
2184
|
+
TorchFieldExportPayload
|
|
2185
|
+
New transformed field payload. The original payload does not change.
|
|
2186
|
+
|
|
2187
|
+
Raises
|
|
2188
|
+
------
|
|
2189
|
+
ValueError
|
|
2190
|
+
If ``operation`` is not supported.
|
|
2191
|
+
"""
|
|
2192
|
+
if operation not in _TRANSFORM_NAMES:
|
|
2193
|
+
raise ValueError(
|
|
2194
|
+
"transform must be one of 'abs', 'real', 'imag', or 'phase'"
|
|
2195
|
+
)
|
|
2196
|
+
return self._view(
|
|
2197
|
+
self._record,
|
|
2198
|
+
transforms=(*self._transforms, cast(_TransformName, operation)),
|
|
2199
|
+
)
|
|
2200
|
+
|
|
2201
|
+
|
|
2202
|
+
class TorchIntensityFieldExportPayload(_TorchFieldView):
|
|
2203
|
+
"""Export squared-norm intensity for a Torch field.
|
|
2204
|
+
|
|
2205
|
+
The view supports base-field access, derivative lookup, field selection, and
|
|
2206
|
+
dictionary export. It does not support field transforms. Transform the field
|
|
2207
|
+
before you request intensity.
|
|
2208
|
+
"""
|
|
2209
|
+
|
|
2210
|
+
@property
|
|
2211
|
+
def base(self) -> "TorchIntensityFieldExportPayload":
|
|
2212
|
+
"""Return a base-only intensity payload.
|
|
2213
|
+
|
|
2214
|
+
Returns
|
|
2215
|
+
-------
|
|
2216
|
+
TorchIntensityFieldExportPayload
|
|
2217
|
+
Intensity view without solver derivative branches.
|
|
2218
|
+
"""
|
|
2219
|
+
return super().base
|
|
2220
|
+
|
|
2221
|
+
@property
|
|
2222
|
+
def derivatives(
|
|
2223
|
+
self,
|
|
2224
|
+
) -> "TorchFieldDerivativeCollection":
|
|
2225
|
+
"""Return Torch-specific intensity-derivative lookup.
|
|
2226
|
+
|
|
2227
|
+
Returns
|
|
2228
|
+
-------
|
|
2229
|
+
TorchFieldDerivativeCollection
|
|
2230
|
+
Derivative lookup keyed by differentiable project key name. The
|
|
2231
|
+
collection is empty when no differentiable inputs are bound.
|
|
2232
|
+
"""
|
|
2233
|
+
return super().derivatives
|
|
2234
|
+
|
|
2235
|
+
def select(self, index: int | None = None) -> "TorchIntensityFieldExportPayload":
|
|
2236
|
+
"""Return an intensity payload with the requested field positions.
|
|
2237
|
+
|
|
2238
|
+
Parameters
|
|
2239
|
+
----------
|
|
2240
|
+
index : int | None, optional
|
|
2241
|
+
Field position. ``None`` selects all field positions.
|
|
2242
|
+
|
|
2243
|
+
Returns
|
|
2244
|
+
-------
|
|
2245
|
+
TorchIntensityFieldExportPayload
|
|
2246
|
+
New intensity payload with the requested selection.
|
|
2247
|
+
"""
|
|
2248
|
+
return super().select(index)
|
|
2249
|
+
|
|
2250
|
+
def __getitem__(self, key: object) -> "TorchIntensityFieldExportPayload":
|
|
2251
|
+
"""Return an intensity payload for a named or nested field value.
|
|
2252
|
+
|
|
2253
|
+
Parameters
|
|
2254
|
+
----------
|
|
2255
|
+
key : object
|
|
2256
|
+
Field quantity name or nested mapping key.
|
|
2257
|
+
|
|
2258
|
+
Returns
|
|
2259
|
+
-------
|
|
2260
|
+
TorchIntensityFieldExportPayload
|
|
2261
|
+
New intensity payload for the selected value.
|
|
2262
|
+
"""
|
|
2263
|
+
return super().__getitem__(key)
|
|
2264
|
+
|
|
2265
|
+
def __getattr__(self, name: str) -> object:
|
|
2266
|
+
if name in {"intensity", "transform"}:
|
|
2267
|
+
raise AttributeError(f"{type(self).__name__!s} does not support {name}().")
|
|
2268
|
+
return super().__getattr__(name)
|
|
2269
|
+
|
|
2270
|
+
|
|
2271
|
+
class TorchFieldDerivativeCollection:
|
|
2272
|
+
"""Look up solver field derivatives by differentiable project key name."""
|
|
2273
|
+
|
|
2274
|
+
def __init__(self, owner: _TorchFieldView) -> None:
|
|
2275
|
+
self._owner = owner
|
|
2276
|
+
|
|
2277
|
+
def __getitem__(
|
|
2278
|
+
self, name: str
|
|
2279
|
+
) -> TorchFieldDerivativePayload | TorchComplexFieldDerivativePayload:
|
|
2280
|
+
"""Return the field derivative for one bound project key.
|
|
2281
|
+
|
|
2282
|
+
Parameters
|
|
2283
|
+
----------
|
|
2284
|
+
name : str
|
|
2285
|
+
Differentiable project key name.
|
|
2286
|
+
|
|
2287
|
+
Returns
|
|
2288
|
+
-------
|
|
2289
|
+
TorchFieldDerivativePayload | TorchComplexFieldDerivativePayload
|
|
2290
|
+
Detached field derivatives for the selected input.
|
|
2291
|
+
|
|
2292
|
+
Raises
|
|
2293
|
+
------
|
|
2294
|
+
KeyError
|
|
2295
|
+
If ``name`` is not a bound differentiable input.
|
|
2296
|
+
"""
|
|
2297
|
+
if name not in self.keys():
|
|
2298
|
+
raise KeyError(name)
|
|
2299
|
+
binding = self._owner._bindings[name]
|
|
2300
|
+
if isinstance(binding, RealDerivative):
|
|
2301
|
+
derivative = self._owner._derivative_branch(RealDerivative(binding.label))
|
|
2302
|
+
return TorchFieldDerivativePayload(
|
|
2303
|
+
self._owner,
|
|
2304
|
+
derivative,
|
|
2305
|
+
input_name=name,
|
|
2306
|
+
)
|
|
2307
|
+
real_branch = self._owner._derivative_branch(RealDerivative(binding.real))
|
|
2308
|
+
imaginary_branch = self._owner._derivative_branch(
|
|
2309
|
+
RealDerivative(binding.imaginary)
|
|
2310
|
+
)
|
|
2311
|
+
base_value: object = _convert_numeric(
|
|
2312
|
+
self._owner._base_mapping().get("field"), self._owner._torch
|
|
2313
|
+
)
|
|
2314
|
+
has_imaginary_output: bool = _is_complex_tensor(base_value, self._owner._torch)
|
|
2315
|
+
return TorchComplexFieldDerivativePayload(
|
|
2316
|
+
real=TorchFieldDerivativePayload(
|
|
2317
|
+
self._owner,
|
|
2318
|
+
real_branch,
|
|
2319
|
+
input_name=name,
|
|
2320
|
+
complex_direction=imaginary_branch,
|
|
2321
|
+
),
|
|
2322
|
+
imag=(
|
|
2323
|
+
TorchFieldDerivativePayload(
|
|
2324
|
+
self._owner,
|
|
2325
|
+
real_branch,
|
|
2326
|
+
input_name=name,
|
|
2327
|
+
complex_direction=imaginary_branch,
|
|
2328
|
+
output_component="imag",
|
|
2329
|
+
)
|
|
2330
|
+
if has_imaginary_output
|
|
2331
|
+
else None
|
|
2332
|
+
),
|
|
2333
|
+
)
|
|
2334
|
+
|
|
2335
|
+
def keys(self) -> tuple[str, ...]:
|
|
2336
|
+
"""Return bound project key names in binding order.
|
|
2337
|
+
|
|
2338
|
+
Returns
|
|
2339
|
+
-------
|
|
2340
|
+
tuple[str, ...]
|
|
2341
|
+
Names of gradient-bearing inputs with solver bindings.
|
|
2342
|
+
"""
|
|
2343
|
+
return tuple(
|
|
2344
|
+
name
|
|
2345
|
+
for name, input_value in zip(
|
|
2346
|
+
self._owner._bindings, self._owner._inputs, strict=False
|
|
2347
|
+
)
|
|
2348
|
+
if getattr(input_value, "requires_grad", False)
|
|
2349
|
+
)
|
|
2350
|
+
|
|
2351
|
+
|
|
2352
|
+
@dataclass(frozen=True, slots=True)
|
|
2353
|
+
class TorchComplexFieldDerivativePayload:
|
|
2354
|
+
"""Store packed sensitivities for one complex project key.
|
|
2355
|
+
|
|
2356
|
+
A complex project key has separate solver derivatives for its real and
|
|
2357
|
+
imaginary input directions. The
|
|
2358
|
+
:attr:`~jcmsuite.torch.results.TorchComplexFieldDerivativePayload.real` and
|
|
2359
|
+
:attr:`~jcmsuite.torch.results.TorchComplexFieldDerivativePayload.imag` records
|
|
2360
|
+
expose the corresponding packed gradients of the real and imaginary output
|
|
2361
|
+
components. The ``imag`` record is ``None`` when the output field is not
|
|
2362
|
+
complex.
|
|
2363
|
+
|
|
2364
|
+
Attributes
|
|
2365
|
+
----------
|
|
2366
|
+
real : TorchFieldDerivativePayload
|
|
2367
|
+
Packed gradient of the real output component with respect to the complex
|
|
2368
|
+
project key.
|
|
2369
|
+
imag : TorchFieldDerivativePayload | None
|
|
2370
|
+
Packed gradient of the imaginary output component, or ``None`` for a real
|
|
2371
|
+
output field.
|
|
2372
|
+
|
|
2373
|
+
Notes
|
|
2374
|
+
-----
|
|
2375
|
+
The records contain detached Torch tensors. Use
|
|
2376
|
+
:meth:`~jcmsuite.torch.results.TorchFieldDerivativePayload.to_dict` on each record to
|
|
2377
|
+
access the field derivatives. The lookup name is the differentiable project key
|
|
2378
|
+
name, not either solver derivative label.
|
|
2379
|
+
"""
|
|
2380
|
+
|
|
2381
|
+
real: TorchFieldDerivativePayload
|
|
2382
|
+
imag: TorchFieldDerivativePayload | None
|
|
2383
|
+
|
|
2384
|
+
def to_dict(self) -> Mapping[object, object]:
|
|
2385
|
+
"""Reject export until the complex output component is selected.
|
|
2386
|
+
|
|
2387
|
+
Returns
|
|
2388
|
+
-------
|
|
2389
|
+
Mapping[object, object]
|
|
2390
|
+
This method does not return; select ``real`` or ``imag`` first.
|
|
2391
|
+
|
|
2392
|
+
Raises
|
|
2393
|
+
------
|
|
2394
|
+
ValueError
|
|
2395
|
+
Always, because a complex field derivative has two output components.
|
|
2396
|
+
"""
|
|
2397
|
+
raise ValueError(
|
|
2398
|
+
"Select the 'real' or 'imag' output component before exporting "
|
|
2399
|
+
"a complex field derivative."
|
|
2400
|
+
)
|
|
2401
|
+
|
|
2402
|
+
def select(self, index: int | None = None) -> "TorchComplexFieldDerivativePayload":
|
|
2403
|
+
"""Select the same field position from both output components.
|
|
2404
|
+
|
|
2405
|
+
Parameters
|
|
2406
|
+
----------
|
|
2407
|
+
index : int | None, optional
|
|
2408
|
+
Field position. ``None`` selects all field positions.
|
|
2409
|
+
|
|
2410
|
+
Returns
|
|
2411
|
+
-------
|
|
2412
|
+
TorchComplexFieldDerivativePayload
|
|
2413
|
+
New complex derivative payload with both components selected.
|
|
2414
|
+
"""
|
|
2415
|
+
return type(self)(
|
|
2416
|
+
real=self.real.select(index),
|
|
2417
|
+
imag=None if self.imag is None else self.imag.select(index),
|
|
2418
|
+
)
|
|
2419
|
+
|
|
2420
|
+
|
|
2421
|
+
@dataclass(frozen=True, slots=True)
|
|
2422
|
+
class _FieldSelection:
|
|
2423
|
+
connection: Literal["sensitivity", "inspection"]
|
|
2424
|
+
topology: Literal["pending", "applied"]
|
|
2425
|
+
output_component: Literal["real", "imag"] | None
|
|
2426
|
+
|
|
2427
|
+
|
|
2428
|
+
class TorchFieldDerivativePayload:
|
|
2429
|
+
"""Represent a solver field sensitivity or second-order inspection value.
|
|
2430
|
+
|
|
2431
|
+
Complete first-order real sensitivities can connect to bound inputs when
|
|
2432
|
+
solver second-order pairs are available. Second-order inspection values are
|
|
2433
|
+
detached. The payload supports nested derivative selection, field selection,
|
|
2434
|
+
and dictionary export. It does not support field transforms because a
|
|
2435
|
+
transform on derivative values does not compute a transformed-field
|
|
2436
|
+
derivative.
|
|
2437
|
+
"""
|
|
2438
|
+
|
|
2439
|
+
def __init__(
|
|
2440
|
+
self,
|
|
2441
|
+
owner: _TorchFieldView,
|
|
2442
|
+
derivative: Mapping[object, object],
|
|
2443
|
+
*,
|
|
2444
|
+
input_name: str,
|
|
2445
|
+
complex_direction: Mapping[object, object] | None = None,
|
|
2446
|
+
output_component: Literal["real", "imag"] | None = None,
|
|
2447
|
+
inspection_only: bool = False,
|
|
2448
|
+
selection_applied: bool = False,
|
|
2449
|
+
) -> None:
|
|
2450
|
+
self._owner = owner
|
|
2451
|
+
self._derivative = derivative
|
|
2452
|
+
self._input_name = input_name
|
|
2453
|
+
self._complex_direction = complex_direction
|
|
2454
|
+
self._selection = _FieldSelection(
|
|
2455
|
+
"inspection" if inspection_only else "sensitivity",
|
|
2456
|
+
"applied" if selection_applied else "pending",
|
|
2457
|
+
output_component,
|
|
2458
|
+
)
|
|
2459
|
+
|
|
2460
|
+
def select(self, index: int | None = None) -> "TorchFieldDerivativePayload":
|
|
2461
|
+
"""Select one field entry from this derivative payload.
|
|
2462
|
+
|
|
2463
|
+
The derivative keeps the same project key and output-component meaning.
|
|
2464
|
+
|
|
2465
|
+
Parameters
|
|
2466
|
+
----------
|
|
2467
|
+
index : int | None, optional
|
|
2468
|
+
Field position. ``None`` selects all field positions.
|
|
2469
|
+
|
|
2470
|
+
Returns
|
|
2471
|
+
-------
|
|
2472
|
+
TorchFieldDerivativePayload
|
|
2473
|
+
New derivative payload with the requested field selection.
|
|
2474
|
+
"""
|
|
2475
|
+
owner: _TorchFieldView = self._owner.select(index)
|
|
2476
|
+
return type(self)(
|
|
2477
|
+
owner,
|
|
2478
|
+
self._derivative,
|
|
2479
|
+
input_name=self._input_name,
|
|
2480
|
+
complex_direction=self._complex_direction,
|
|
2481
|
+
output_component=self._selection.output_component,
|
|
2482
|
+
inspection_only=self._selection.connection == "inspection",
|
|
2483
|
+
selection_applied=self._selection.topology == "applied",
|
|
2484
|
+
)
|
|
2485
|
+
|
|
2486
|
+
@property
|
|
2487
|
+
def derivatives(self) -> "TorchNestedFieldDerivativeCollection":
|
|
2488
|
+
"""Return nested field derivatives by bound project key name.
|
|
2489
|
+
|
|
2490
|
+
The collection selects second-order inspection values from a first-order
|
|
2491
|
+
sensitivity. Selecting another derivative from a second-order value
|
|
2492
|
+
raises because third-order solver derivatives are unavailable.
|
|
2493
|
+
"""
|
|
2494
|
+
return TorchNestedFieldDerivativeCollection(self)
|
|
2495
|
+
|
|
2496
|
+
def _mapping_for_selected_owner(
|
|
2497
|
+
self, mapping: Mapping[object, object]
|
|
2498
|
+
) -> Mapping[object, object]:
|
|
2499
|
+
if self._selection.topology == "applied":
|
|
2500
|
+
return mapping
|
|
2501
|
+
selected_indices: tuple[int, ...] = tuple(
|
|
2502
|
+
getattr(self._owner._record, "indices", ())
|
|
2503
|
+
)
|
|
2504
|
+
if len(selected_indices) != 1:
|
|
2505
|
+
return mapping
|
|
2506
|
+
selected_index: int = selected_indices[0]
|
|
2507
|
+
nested_field: object = mapping.get("field")
|
|
2508
|
+
coordinate_names: tuple[str, ...] = ("X", "Y", "Z", "R", "Theta", "Phi")
|
|
2509
|
+
nested_coordinates: bool = isinstance(nested_field, Mapping) and any(
|
|
2510
|
+
isinstance(key, str) and key.upper() in coordinate_names
|
|
2511
|
+
for key in nested_field
|
|
2512
|
+
)
|
|
2513
|
+
has_coordinates: bool = any(
|
|
2514
|
+
isinstance(key, str) and key.upper() in coordinate_names for key in mapping
|
|
2515
|
+
)
|
|
2516
|
+
if not nested_coordinates and not has_coordinates:
|
|
2517
|
+
# Older derivative records can provide only the selected numeric
|
|
2518
|
+
# field tensor, without repeating the base coordinate grid.
|
|
2519
|
+
return mapping
|
|
2520
|
+
field_mapping: Mapping[object, object] = (
|
|
2521
|
+
cast(Mapping[object, object], nested_field)
|
|
2522
|
+
if nested_coordinates
|
|
2523
|
+
else mapping
|
|
2524
|
+
)
|
|
2525
|
+
# Solver derivative payloads can wrap the complete coordinate-bearing
|
|
2526
|
+
# field mapping under an outer ``field`` key. Select inside that mapping
|
|
2527
|
+
# so FieldExportPayload sees the coordinates at its expected root.
|
|
2528
|
+
payload: FieldExportPayload = FieldExportPayload(field_mapping)
|
|
2529
|
+
if selected_index not in payload.indices and len(payload.indices) == 1:
|
|
2530
|
+
# The ordinary selected field view already projected this branch.
|
|
2531
|
+
return mapping
|
|
2532
|
+
selected_mapping: Mapping[object, object] = payload.select(
|
|
2533
|
+
selected_index
|
|
2534
|
+
).to_dict()
|
|
2535
|
+
if not nested_coordinates:
|
|
2536
|
+
return selected_mapping
|
|
2537
|
+
result: dict[object, object] = dict(mapping)
|
|
2538
|
+
result["field"] = selected_mapping
|
|
2539
|
+
return result
|
|
2540
|
+
|
|
2541
|
+
def to_dict(self) -> Mapping[object, object]:
|
|
2542
|
+
"""Return the detached sensitivity field and its metadata.
|
|
2543
|
+
|
|
2544
|
+
Returns
|
|
2545
|
+
-------
|
|
2546
|
+
Mapping[object, object]
|
|
2547
|
+
A mapping whose ``field`` value is a detached Torch tensor.
|
|
2548
|
+
"""
|
|
2549
|
+
base = self._owner._base_mapping()
|
|
2550
|
+
derivative_mapping: Mapping[object, object] = self._mapping_for_selected_owner(
|
|
2551
|
+
self._derivative
|
|
2552
|
+
)
|
|
2553
|
+
derivative = self._field_value(derivative_mapping)
|
|
2554
|
+
if self._complex_direction is not None:
|
|
2555
|
+
imaginary_mapping: Mapping[object, object] = (
|
|
2556
|
+
self._mapping_for_selected_owner(self._complex_direction)
|
|
2557
|
+
)
|
|
2558
|
+
other = self._field_value(imaginary_mapping)
|
|
2559
|
+
if self._owner._transforms and self._selection.connection != "inspection":
|
|
2560
|
+
binding: DerivativeBinding | None = self._owner._bindings.get(
|
|
2561
|
+
self._input_name
|
|
2562
|
+
)
|
|
2563
|
+
if binding is not None and isinstance(binding, ComplexDerivative):
|
|
2564
|
+
derivative = self._connected_transformed_direction(
|
|
2565
|
+
base, derivative_mapping, binding.real
|
|
2566
|
+
)
|
|
2567
|
+
other = self._connected_transformed_direction(
|
|
2568
|
+
base, imaginary_mapping, binding.imaginary
|
|
2569
|
+
)
|
|
2570
|
+
if self._owner._transforms and self._selection.connection != "inspection":
|
|
2571
|
+
derivative = _pack_numeric_directions(
|
|
2572
|
+
derivative, other, None, self._owner._torch
|
|
2573
|
+
)
|
|
2574
|
+
else:
|
|
2575
|
+
derivative = self._packed_gradient(base, derivative, other)
|
|
2576
|
+
else:
|
|
2577
|
+
if self._owner._transforms and self._selection.connection != "inspection":
|
|
2578
|
+
binding = self._owner._bindings.get(self._input_name)
|
|
2579
|
+
if isinstance(binding, RealDerivative):
|
|
2580
|
+
derivative = self._connected_transformed_direction(
|
|
2581
|
+
base, derivative_mapping, binding.label
|
|
2582
|
+
)
|
|
2583
|
+
else:
|
|
2584
|
+
derivative = self._real_derivative(base, derivative)
|
|
2585
|
+
else:
|
|
2586
|
+
derivative = self._real_derivative(base, derivative)
|
|
2587
|
+
result: dict[object, object] = {
|
|
2588
|
+
key: value for key, value in base.items() if key not in {"field", "header"}
|
|
2589
|
+
}
|
|
2590
|
+
if (
|
|
2591
|
+
self._selection.connection != "inspection"
|
|
2592
|
+
and not self._owner._transforms
|
|
2593
|
+
and isinstance(self._owner._record, FieldExportPayload)
|
|
2594
|
+
):
|
|
2595
|
+
sensitivity_binding: DerivativeBinding | None = self._owner._bindings.get(
|
|
2596
|
+
self._input_name
|
|
2597
|
+
)
|
|
2598
|
+
labels: tuple[str, ...] = (
|
|
2599
|
+
(sensitivity_binding.label,)
|
|
2600
|
+
if isinstance(sensitivity_binding, RealDerivative)
|
|
2601
|
+
else (
|
|
2602
|
+
(sensitivity_binding.real, sensitivity_binding.imaginary)
|
|
2603
|
+
if sensitivity_binding is not None
|
|
2604
|
+
else ()
|
|
2605
|
+
)
|
|
2606
|
+
)
|
|
2607
|
+
pairs: Mapping[str, Mapping[str, object]] = (
|
|
2608
|
+
self._owner._field_second_derivatives()
|
|
2609
|
+
)
|
|
2610
|
+
has_second_order_data: bool = any(bool(row) for row in pairs.values())
|
|
2611
|
+
if labels and has_second_order_data:
|
|
2612
|
+
input_labels: tuple[str, ...] = coordinate_labels(self._owner._bindings)
|
|
2613
|
+
unavailable: tuple[str, str] | None = missing_pair(
|
|
2614
|
+
labels, pairs, input_labels
|
|
2615
|
+
)
|
|
2616
|
+
if unavailable is not None:
|
|
2617
|
+
raise ValueError(
|
|
2618
|
+
"Second-order solver data is incomplete for pair "
|
|
2619
|
+
f"{unavailable[0]!r}, {unavailable[1]!r}, payload 'field'."
|
|
2620
|
+
)
|
|
2621
|
+
if self._complex_direction is None:
|
|
2622
|
+
second_mapping: Mapping[str, object] = pairs[labels[0]]
|
|
2623
|
+
else:
|
|
2624
|
+
second_mapping = self._packed_sensitivity_derivatives(
|
|
2625
|
+
labels, input_labels, pairs
|
|
2626
|
+
)
|
|
2627
|
+
derivative = connect_value(
|
|
2628
|
+
derivative,
|
|
2629
|
+
second_mapping,
|
|
2630
|
+
self._owner._bindings,
|
|
2631
|
+
self._owner._inputs,
|
|
2632
|
+
self._owner._torch,
|
|
2633
|
+
third_order_boundary=True,
|
|
2634
|
+
)
|
|
2635
|
+
result["field"] = (
|
|
2636
|
+
derivative
|
|
2637
|
+
if getattr(derivative, "requires_grad", False)
|
|
2638
|
+
else _detach(derivative)
|
|
2639
|
+
)
|
|
2640
|
+
return result
|
|
2641
|
+
|
|
2642
|
+
def _connected_transformed_direction(
|
|
2643
|
+
self,
|
|
2644
|
+
base: Mapping[object, object],
|
|
2645
|
+
derivative_mapping: Mapping[object, object],
|
|
2646
|
+
direction_label: str,
|
|
2647
|
+
) -> object:
|
|
2648
|
+
"""Build a transformed sensitivity graph from solver first/second data."""
|
|
2649
|
+
pair_map: Mapping[str, Mapping[str, object]] = (
|
|
2650
|
+
self._owner._field_second_derivatives()
|
|
2651
|
+
)
|
|
2652
|
+
if not pair_map:
|
|
2653
|
+
return self._real_derivative(base, self._field_value(derivative_mapping))
|
|
2654
|
+
|
|
2655
|
+
bound_labels: tuple[str, ...] = coordinate_labels(self._owner._bindings)
|
|
2656
|
+
unavailable: tuple[str, str] | None = missing_pair(bound_labels, pair_map)
|
|
2657
|
+
if unavailable is not None:
|
|
2658
|
+
raise ValueError(
|
|
2659
|
+
"Second-order solver data is incomplete for transformed sensitivity "
|
|
2660
|
+
f"pair {unavailable[0]!r}, {unavailable[1]!r}, payload 'field'."
|
|
2661
|
+
)
|
|
2662
|
+
|
|
2663
|
+
first_values: dict[str, object] = {}
|
|
2664
|
+
for binding in self._owner._bindings.values():
|
|
2665
|
+
labels: tuple[str, ...] = binding_labels(binding)
|
|
2666
|
+
for label in labels:
|
|
2667
|
+
branch: Mapping[object, object] = self._owner._derivative_branch(
|
|
2668
|
+
RealDerivative(label)
|
|
2669
|
+
)
|
|
2670
|
+
selected_branch: Mapping[object, object] = (
|
|
2671
|
+
self._mapping_for_selected_owner(branch)
|
|
2672
|
+
)
|
|
2673
|
+
first_values[label] = self._field_value(selected_branch)
|
|
2674
|
+
|
|
2675
|
+
base_value: object = self._field_value(base)
|
|
2676
|
+
connected_base: object = connect_value(
|
|
2677
|
+
base_value,
|
|
2678
|
+
first_values,
|
|
2679
|
+
self._owner._bindings,
|
|
2680
|
+
self._owner._inputs,
|
|
2681
|
+
self._owner._torch,
|
|
2682
|
+
pair_map,
|
|
2683
|
+
)
|
|
2684
|
+
direction_value: object = self._field_value(derivative_mapping)
|
|
2685
|
+
connected_direction: object = connect_value(
|
|
2686
|
+
direction_value,
|
|
2687
|
+
pair_map.get(direction_label, {}),
|
|
2688
|
+
self._owner._bindings,
|
|
2689
|
+
self._owner._inputs,
|
|
2690
|
+
self._owner._torch,
|
|
2691
|
+
third_order_boundary=True,
|
|
2692
|
+
)
|
|
2693
|
+
_, transformed_direction = _jvp(
|
|
2694
|
+
connected_base,
|
|
2695
|
+
connected_direction,
|
|
2696
|
+
self._owner._transforms,
|
|
2697
|
+
self._owner._torch,
|
|
2698
|
+
grid_rank=self._grid_rank(base),
|
|
2699
|
+
)
|
|
2700
|
+
return _project_numeric_component(
|
|
2701
|
+
transformed_direction, self._selection.output_component, self._owner._torch
|
|
2702
|
+
)
|
|
2703
|
+
|
|
2704
|
+
def _packed_sensitivity_derivatives(
|
|
2705
|
+
self,
|
|
2706
|
+
direction_labels: tuple[str, ...],
|
|
2707
|
+
input_labels: tuple[str, ...],
|
|
2708
|
+
pairs: Mapping[str, Mapping[str, object]],
|
|
2709
|
+
) -> Mapping[str, object]:
|
|
2710
|
+
"""Pack second field pairs as gradients of this component sensitivity."""
|
|
2711
|
+
if len(direction_labels) != 2:
|
|
2712
|
+
raise ValueError("Complex sensitivity requires both coordinate labels.")
|
|
2713
|
+
packed: dict[str, object] = {}
|
|
2714
|
+
for input_label in input_labels:
|
|
2715
|
+
components: list[object] = []
|
|
2716
|
+
for direction in direction_labels:
|
|
2717
|
+
raw_pair: object = pairs[direction][input_label]
|
|
2718
|
+
if not isinstance(raw_pair, Mapping):
|
|
2719
|
+
raise ValueError(
|
|
2720
|
+
f"Second-order field pair {direction!r}, {input_label!r} "
|
|
2721
|
+
"has no field mapping."
|
|
2722
|
+
)
|
|
2723
|
+
pair_value: object = self._field_value(raw_pair)
|
|
2724
|
+
components.append(pair_value)
|
|
2725
|
+
packed[input_label] = _pack_numeric_directions(
|
|
2726
|
+
components[0],
|
|
2727
|
+
components[1],
|
|
2728
|
+
self._selection.output_component or "real",
|
|
2729
|
+
self._owner._torch,
|
|
2730
|
+
)
|
|
2731
|
+
return packed
|
|
2732
|
+
|
|
2733
|
+
def to_xarray(self) -> object:
|
|
2734
|
+
"""Raise because Torch derivative records support dictionary export only.
|
|
2735
|
+
|
|
2736
|
+
Returns
|
|
2737
|
+
-------
|
|
2738
|
+
object
|
|
2739
|
+
This method does not return because Torch derivative records do not
|
|
2740
|
+
support xarray export.
|
|
2741
|
+
"""
|
|
2742
|
+
raise UnsupportedExportError("Torch derivative records support to_dict() only.")
|
|
2743
|
+
|
|
2744
|
+
def _field_value(self, mapping: Mapping[object, object]) -> object:
|
|
2745
|
+
value: object = mapping.get("field")
|
|
2746
|
+
while isinstance(value, Mapping) and "field" in value:
|
|
2747
|
+
value = value["field"]
|
|
2748
|
+
converted: object = _convert_numeric(value, self._owner._torch)
|
|
2749
|
+
if (
|
|
2750
|
+
self._selection.topology == "applied"
|
|
2751
|
+
and isinstance(self._owner._record, FieldExportPayload)
|
|
2752
|
+
and len(self._owner._record.indices) == 1
|
|
2753
|
+
):
|
|
2754
|
+
indices: list[int] = list(self._owner._record.indices)
|
|
2755
|
+
shape: Sequence[object] = cast(
|
|
2756
|
+
Sequence[object], getattr(converted, "shape", ())
|
|
2757
|
+
)
|
|
2758
|
+
first_axis: int = cast(int, shape[0]) if shape else 0
|
|
2759
|
+
if shape and max(indices) < first_axis:
|
|
2760
|
+
return getattr(converted, "__getitem__")(indices)
|
|
2761
|
+
return converted
|
|
2762
|
+
|
|
2763
|
+
def _real_derivative(
|
|
2764
|
+
self, base: Mapping[object, object], derivative: object
|
|
2765
|
+
) -> object:
|
|
2766
|
+
value: object = _convert_numeric(base.get("field"), self._owner._torch)
|
|
2767
|
+
derivative_value: object
|
|
2768
|
+
_, derivative_value = _jvp(
|
|
2769
|
+
value,
|
|
2770
|
+
derivative,
|
|
2771
|
+
self._owner._transforms,
|
|
2772
|
+
self._owner._torch,
|
|
2773
|
+
grid_rank=_field_grid_rank(base),
|
|
2774
|
+
)
|
|
2775
|
+
return _project_numeric_component(
|
|
2776
|
+
derivative_value, self._selection.output_component, self._owner._torch
|
|
2777
|
+
)
|
|
2778
|
+
|
|
2779
|
+
def _packed_gradient(
|
|
2780
|
+
self, base: Mapping[object, object], real: object, imaginary: object
|
|
2781
|
+
) -> object:
|
|
2782
|
+
value: object = _convert_numeric(base.get("field"), self._owner._torch)
|
|
2783
|
+
real_derivative: object
|
|
2784
|
+
imaginary_derivative: object
|
|
2785
|
+
_, real_derivative = _jvp(
|
|
2786
|
+
value,
|
|
2787
|
+
real,
|
|
2788
|
+
self._owner._transforms,
|
|
2789
|
+
self._owner._torch,
|
|
2790
|
+
grid_rank=self._grid_rank(base),
|
|
2791
|
+
)
|
|
2792
|
+
_, imaginary_derivative = _jvp(
|
|
2793
|
+
value,
|
|
2794
|
+
imaginary,
|
|
2795
|
+
self._owner._transforms,
|
|
2796
|
+
self._owner._torch,
|
|
2797
|
+
grid_rank=self._grid_rank(base),
|
|
2798
|
+
)
|
|
2799
|
+
return _pack_numeric_directions(
|
|
2800
|
+
real_derivative,
|
|
2801
|
+
imaginary_derivative,
|
|
2802
|
+
self._selection.output_component or "real",
|
|
2803
|
+
self._owner._torch,
|
|
2804
|
+
)
|
|
2805
|
+
|
|
2806
|
+
@staticmethod
|
|
2807
|
+
def _grid_rank(base: Mapping[object, object]) -> int:
|
|
2808
|
+
return _field_grid_rank(base)
|
|
2809
|
+
|
|
2810
|
+
|
|
2811
|
+
class TorchNestedFieldDerivativeCollection:
|
|
2812
|
+
"""Select second-order field values by bound project key name."""
|
|
2813
|
+
|
|
2814
|
+
def __init__(self, owner: TorchFieldDerivativePayload) -> None:
|
|
2815
|
+
self._owner = owner
|
|
2816
|
+
|
|
2817
|
+
def keys(self) -> tuple[str, ...]:
|
|
2818
|
+
"""Return available second-order project-key names."""
|
|
2819
|
+
if self._owner._selection.connection == "inspection" or not isinstance(
|
|
2820
|
+
self._owner._owner._record, FieldExportPayload
|
|
2821
|
+
):
|
|
2822
|
+
return ()
|
|
2823
|
+
binding: DerivativeBinding | None = self._owner._owner._bindings.get(
|
|
2824
|
+
self._owner._input_name
|
|
2825
|
+
)
|
|
2826
|
+
if binding is None:
|
|
2827
|
+
return ()
|
|
2828
|
+
first_labels: tuple[str, ...] = binding_labels(binding)
|
|
2829
|
+
pairs: Mapping[str, Mapping[str, object]] = (
|
|
2830
|
+
self._owner._owner._field_second_derivatives()
|
|
2831
|
+
)
|
|
2832
|
+
return tuple(
|
|
2833
|
+
name
|
|
2834
|
+
for name, other in self._owner._owner._bindings.items()
|
|
2835
|
+
if all(
|
|
2836
|
+
label in pairs.get(first, {})
|
|
2837
|
+
for first in first_labels
|
|
2838
|
+
for label in binding_labels(other)
|
|
2839
|
+
)
|
|
2840
|
+
)
|
|
2841
|
+
|
|
2842
|
+
def __getitem__(
|
|
2843
|
+
self, name: str
|
|
2844
|
+
) -> TorchFieldDerivativePayload | TorchComplexFieldDerivativePayload:
|
|
2845
|
+
"""Return a detached second-order field inspection payload."""
|
|
2846
|
+
if self._owner._selection.connection == "inspection":
|
|
2847
|
+
raise ValueError("Third-order field derivatives are not available.")
|
|
2848
|
+
if name not in self.keys():
|
|
2849
|
+
first: DerivativeBinding | None = self._owner._owner._bindings.get(
|
|
2850
|
+
self._owner._input_name
|
|
2851
|
+
)
|
|
2852
|
+
second: DerivativeBinding | None = self._owner._owner._bindings.get(name)
|
|
2853
|
+
first_label: str = (
|
|
2854
|
+
first.label
|
|
2855
|
+
if isinstance(first, RealDerivative)
|
|
2856
|
+
else self._owner._input_name
|
|
2857
|
+
)
|
|
2858
|
+
second_label: str = (
|
|
2859
|
+
second.label if isinstance(second, RealDerivative) else name
|
|
2860
|
+
)
|
|
2861
|
+
raise KeyError(
|
|
2862
|
+
f"Second-order derivative pair {first_label!r}, {second_label!r} is unavailable."
|
|
2863
|
+
)
|
|
2864
|
+
bindings: BindingMap = self._owner._owner._bindings
|
|
2865
|
+
first_binding: DerivativeBinding = bindings[self._owner._input_name]
|
|
2866
|
+
second_binding: DerivativeBinding = bindings[name]
|
|
2867
|
+
first_labels: tuple[str, ...] = (
|
|
2868
|
+
(first_binding.label,)
|
|
2869
|
+
if isinstance(first_binding, RealDerivative)
|
|
2870
|
+
else (first_binding.real, first_binding.imaginary)
|
|
2871
|
+
)
|
|
2872
|
+
second_labels: tuple[str, ...] = (
|
|
2873
|
+
(second_binding.label,)
|
|
2874
|
+
if isinstance(second_binding, RealDerivative)
|
|
2875
|
+
else (second_binding.real, second_binding.imaginary)
|
|
2876
|
+
)
|
|
2877
|
+
pairs: Mapping[str, Mapping[str, object]] = (
|
|
2878
|
+
self._owner._owner._field_second_derivatives()
|
|
2879
|
+
)
|
|
2880
|
+
if isinstance(first_binding, RealDerivative) and isinstance(
|
|
2881
|
+
second_binding, RealDerivative
|
|
2882
|
+
):
|
|
2883
|
+
record: object = self._owner._owner._record
|
|
2884
|
+
if not isinstance(record, FieldExportPayload):
|
|
2885
|
+
raise KeyError(name)
|
|
2886
|
+
first_view: object = record.derivatives[first_binding.label]
|
|
2887
|
+
second_collection: object = getattr(first_view, "derivatives")
|
|
2888
|
+
pair_view: object = second_collection[second_binding.label] # type: ignore[index]
|
|
2889
|
+
pair_mapping: Mapping[object, object] = cast(
|
|
2890
|
+
Mapping[object, object], getattr(pair_view, "to_dict")()
|
|
2891
|
+
)
|
|
2892
|
+
return TorchFieldDerivativePayload(
|
|
2893
|
+
self._owner._owner,
|
|
2894
|
+
pair_mapping,
|
|
2895
|
+
input_name=name,
|
|
2896
|
+
inspection_only=True,
|
|
2897
|
+
)
|
|
2898
|
+
if len(first_labels) == 2:
|
|
2899
|
+
packed_by_second: list[object] = []
|
|
2900
|
+
for second_label in second_labels:
|
|
2901
|
+
derivative_mapping: Mapping[str, object] = (
|
|
2902
|
+
self._owner._packed_sensitivity_derivatives(
|
|
2903
|
+
first_labels, (second_label,), pairs
|
|
2904
|
+
)
|
|
2905
|
+
)
|
|
2906
|
+
packed_by_second.append(derivative_mapping[second_label])
|
|
2907
|
+
if len(second_labels) == 2:
|
|
2908
|
+
return TorchComplexFieldDerivativePayload(
|
|
2909
|
+
real=self._inspection_value(name, packed_by_second[0]),
|
|
2910
|
+
imag=self._inspection_value(name, packed_by_second[1]),
|
|
2911
|
+
)
|
|
2912
|
+
return self._inspection_value(name, packed_by_second[0])
|
|
2913
|
+
|
|
2914
|
+
selected_first_label: str = first_labels[0]
|
|
2915
|
+
second_values: list[object] = []
|
|
2916
|
+
for second_label in second_labels:
|
|
2917
|
+
raw_pair: object = pairs[selected_first_label][second_label]
|
|
2918
|
+
if not isinstance(raw_pair, Mapping):
|
|
2919
|
+
raise ValueError(
|
|
2920
|
+
f"Second-order field pair {selected_first_label!r}, {second_label!r} "
|
|
2921
|
+
"has no field mapping."
|
|
2922
|
+
)
|
|
2923
|
+
pair_value: object = self._owner._field_value(raw_pair)
|
|
2924
|
+
second_values.append(
|
|
2925
|
+
_project_numeric_component(
|
|
2926
|
+
pair_value,
|
|
2927
|
+
self._owner._selection.output_component,
|
|
2928
|
+
self._owner._owner._torch,
|
|
2929
|
+
)
|
|
2930
|
+
)
|
|
2931
|
+
if len(second_values) == 2:
|
|
2932
|
+
if self._owner._selection.output_component is None and _is_complex_tensor(
|
|
2933
|
+
_convert_numeric(
|
|
2934
|
+
self._owner._owner._base_mapping().get("field"),
|
|
2935
|
+
self._owner._owner._torch,
|
|
2936
|
+
),
|
|
2937
|
+
self._owner._owner._torch,
|
|
2938
|
+
):
|
|
2939
|
+
real_values: object = _pack_numeric_directions(
|
|
2940
|
+
second_values[0],
|
|
2941
|
+
second_values[1],
|
|
2942
|
+
"real",
|
|
2943
|
+
self._owner._owner._torch,
|
|
2944
|
+
)
|
|
2945
|
+
imaginary_values: object = _pack_numeric_directions(
|
|
2946
|
+
second_values[0],
|
|
2947
|
+
second_values[1],
|
|
2948
|
+
"imag",
|
|
2949
|
+
self._owner._owner._torch,
|
|
2950
|
+
)
|
|
2951
|
+
return TorchComplexFieldDerivativePayload(
|
|
2952
|
+
real=self._inspection_value(name, real_values),
|
|
2953
|
+
imag=self._inspection_value(name, imaginary_values),
|
|
2954
|
+
)
|
|
2955
|
+
packed: object = _pack_numeric_directions(
|
|
2956
|
+
second_values[0], second_values[1], None, self._owner._owner._torch
|
|
2957
|
+
)
|
|
2958
|
+
return self._inspection_value(name, packed)
|
|
2959
|
+
return self._inspection_value(name, second_values[0])
|
|
2960
|
+
|
|
2961
|
+
def _inspection_value(
|
|
2962
|
+
self, name: str, value: object
|
|
2963
|
+
) -> TorchFieldDerivativePayload:
|
|
2964
|
+
"""Wrap one detached nested field tensor without changing its packing."""
|
|
2965
|
+
explicitly_selected: bool = (
|
|
2966
|
+
isinstance(self._owner._owner._record, FieldExportPayload)
|
|
2967
|
+
and self._owner._owner._record._selected_index is not None
|
|
2968
|
+
)
|
|
2969
|
+
if explicitly_selected:
|
|
2970
|
+
value = getattr(value, "unsqueeze")(0)
|
|
2971
|
+
return TorchFieldDerivativePayload(
|
|
2972
|
+
self._owner._owner,
|
|
2973
|
+
{"field": value},
|
|
2974
|
+
input_name=name,
|
|
2975
|
+
inspection_only=True,
|
|
2976
|
+
selection_applied=not explicitly_selected,
|
|
2977
|
+
)
|
|
2978
|
+
|
|
2979
|
+
|
|
2980
|
+
class TorchBatchFieldDerivativeCollection:
|
|
2981
|
+
"""Look up solver field derivatives by bound project key across a batch.
|
|
2982
|
+
|
|
2983
|
+
This collection composes the lookup behavior of
|
|
2984
|
+
:class:`TorchFieldDerivativeCollection` with the original-index alignment of
|
|
2985
|
+
ordinary batch field payloads. Each lookup collects the corresponding
|
|
2986
|
+
single-entry Torch derivative and retains only entries with available field
|
|
2987
|
+
data and bindings.
|
|
2988
|
+
|
|
2989
|
+
A Torch batch field payload returns this collection. Do not construct it
|
|
2990
|
+
directly.
|
|
2991
|
+
"""
|
|
2992
|
+
|
|
2993
|
+
def __init__(self, owner: TorchBatchFieldExportPayload) -> None:
|
|
2994
|
+
self._owner = owner
|
|
2995
|
+
|
|
2996
|
+
def keys(self) -> tuple[str, ...]:
|
|
2997
|
+
"""Return bound project key names available in the batch.
|
|
2998
|
+
|
|
2999
|
+
Returns
|
|
3000
|
+
-------
|
|
3001
|
+
tuple[str, ...]
|
|
3002
|
+
Bound names in first-seen order across available batch field entries.
|
|
3003
|
+
"""
|
|
3004
|
+
names: list[str] = []
|
|
3005
|
+
seen: set[str] = set()
|
|
3006
|
+
for record in cast(Sequence[object], getattr(self._owner._payload, "records")):
|
|
3007
|
+
payload: object = getattr(record, "payload", None)
|
|
3008
|
+
if payload is None:
|
|
3009
|
+
continue
|
|
3010
|
+
index: int = cast(int, getattr(record, "index"))
|
|
3011
|
+
field: TorchFieldExportPayload = TorchFieldExportPayload(
|
|
3012
|
+
payload,
|
|
3013
|
+
_context_binding(self._owner._bindings, index),
|
|
3014
|
+
_context_inputs(self._owner._inputs, index),
|
|
3015
|
+
self._owner._torch,
|
|
3016
|
+
)
|
|
3017
|
+
for name in field.derivatives.keys():
|
|
3018
|
+
if name not in seen:
|
|
3019
|
+
seen.add(name)
|
|
3020
|
+
names.append(name)
|
|
3021
|
+
return tuple(names)
|
|
3022
|
+
|
|
3023
|
+
def __getitem__(
|
|
3024
|
+
self, name: str
|
|
3025
|
+
) -> "TorchBatchFieldDerivativePayload | TorchBatchComplexFieldDerivativePayload":
|
|
3026
|
+
"""Return one bound solver derivative for each available batch entry.
|
|
3027
|
+
|
|
3028
|
+
Parameters
|
|
3029
|
+
----------
|
|
3030
|
+
name : str
|
|
3031
|
+
Differentiable project key name.
|
|
3032
|
+
|
|
3033
|
+
Returns
|
|
3034
|
+
-------
|
|
3035
|
+
TorchBatchFieldDerivativePayload | TorchBatchComplexFieldDerivativePayload
|
|
3036
|
+
Detached field derivatives keyed by original batch index.
|
|
3037
|
+
|
|
3038
|
+
Raises
|
|
3039
|
+
------
|
|
3040
|
+
KeyError
|
|
3041
|
+
If ``name`` is not bound to a differentiable input.
|
|
3042
|
+
"""
|
|
3043
|
+
if name not in self.keys():
|
|
3044
|
+
raise KeyError(name)
|
|
3045
|
+
real_entries: list[tuple[int, TorchFieldDerivativePayload]] = []
|
|
3046
|
+
imag_entries: list[tuple[int, TorchFieldDerivativePayload]] = []
|
|
3047
|
+
complex_output: bool | None = None
|
|
3048
|
+
records: Sequence[object] = cast(
|
|
3049
|
+
Sequence[object], getattr(self._owner._payload, "records")
|
|
3050
|
+
)
|
|
3051
|
+
for record in records:
|
|
3052
|
+
payload: object = getattr(record, "payload", None)
|
|
3053
|
+
if payload is None:
|
|
3054
|
+
continue
|
|
3055
|
+
index: int = cast(int, getattr(record, "index"))
|
|
3056
|
+
field: TorchFieldExportPayload = TorchFieldExportPayload(
|
|
3057
|
+
payload,
|
|
3058
|
+
_context_binding(self._owner._bindings, index),
|
|
3059
|
+
_context_inputs(self._owner._inputs, index),
|
|
3060
|
+
self._owner._torch,
|
|
3061
|
+
)
|
|
3062
|
+
for operation in self._owner._transforms:
|
|
3063
|
+
field = (
|
|
3064
|
+
cast(TorchFieldExportPayload, field.intensity)
|
|
3065
|
+
if operation == "intensity"
|
|
3066
|
+
else field.transform(operation)
|
|
3067
|
+
)
|
|
3068
|
+
if name not in field.derivatives.keys():
|
|
3069
|
+
continue
|
|
3070
|
+
derivative: (
|
|
3071
|
+
TorchFieldDerivativePayload | TorchComplexFieldDerivativePayload
|
|
3072
|
+
) = field.derivatives[name]
|
|
3073
|
+
is_complex: bool = isinstance(
|
|
3074
|
+
derivative, TorchComplexFieldDerivativePayload
|
|
3075
|
+
)
|
|
3076
|
+
if complex_output is None:
|
|
3077
|
+
complex_output = is_complex
|
|
3078
|
+
elif complex_output != is_complex:
|
|
3079
|
+
raise ValueError(
|
|
3080
|
+
"Batch field-derivative outputs must have a consistent complex topology."
|
|
3081
|
+
)
|
|
3082
|
+
if isinstance(derivative, TorchComplexFieldDerivativePayload):
|
|
3083
|
+
real_entries.append((index, derivative.real))
|
|
3084
|
+
if derivative.imag is not None:
|
|
3085
|
+
imag_entries.append((index, derivative.imag))
|
|
3086
|
+
else:
|
|
3087
|
+
real_entries.append((index, derivative))
|
|
3088
|
+
real_payload: TorchBatchFieldDerivativePayload = (
|
|
3089
|
+
TorchBatchFieldDerivativePayload(tuple(real_entries))
|
|
3090
|
+
)
|
|
3091
|
+
if complex_output:
|
|
3092
|
+
imag_payload: TorchBatchFieldDerivativePayload | None = (
|
|
3093
|
+
TorchBatchFieldDerivativePayload(tuple(imag_entries))
|
|
3094
|
+
if imag_entries
|
|
3095
|
+
else None
|
|
3096
|
+
)
|
|
3097
|
+
return TorchBatchComplexFieldDerivativePayload(real_payload, imag_payload)
|
|
3098
|
+
return real_payload
|
|
3099
|
+
|
|
3100
|
+
|
|
3101
|
+
class TorchBatchFieldDerivativePayload:
|
|
3102
|
+
"""Provide field sensitivities keyed by original batch index.
|
|
3103
|
+
|
|
3104
|
+
This payload composes the dictionary and selection behavior of
|
|
3105
|
+
:class:`TorchFieldDerivativePayload` across available batch entries. Its
|
|
3106
|
+
``to_dict()`` method returns each single-entry derivative mapping under the
|
|
3107
|
+
original batch index.
|
|
3108
|
+
|
|
3109
|
+
First sensitivities remain differentiable when all required second-order
|
|
3110
|
+
pairs are available. Without second-order data, they are detached values.
|
|
3111
|
+
Partial pair data raises an error when exporting a first sensitivity.
|
|
3112
|
+
Selected second-order values are detached.
|
|
3113
|
+
|
|
3114
|
+
A lookup in :class:`TorchBatchFieldDerivativeCollection` returns this payload
|
|
3115
|
+
for a real input. Do not construct it directly.
|
|
3116
|
+
"""
|
|
3117
|
+
|
|
3118
|
+
def __init__(
|
|
3119
|
+
self, entries: tuple[tuple[int, TorchFieldDerivativePayload], ...]
|
|
3120
|
+
) -> None:
|
|
3121
|
+
self._entries = entries
|
|
3122
|
+
|
|
3123
|
+
def to_dict(self) -> Mapping[int, Mapping[object, object]]:
|
|
3124
|
+
"""Return derivative mappings for available batch entries.
|
|
3125
|
+
|
|
3126
|
+
Returns
|
|
3127
|
+
-------
|
|
3128
|
+
Mapping[int, Mapping[object, object]]
|
|
3129
|
+
Derivative mappings keyed by original batch index.
|
|
3130
|
+
"""
|
|
3131
|
+
return {index: derivative.to_dict() for index, derivative in self._entries}
|
|
3132
|
+
|
|
3133
|
+
@property
|
|
3134
|
+
def derivatives(self) -> "TorchNestedBatchFieldDerivativeCollection":
|
|
3135
|
+
"""Return nested solver derivatives aligned by original batch index.
|
|
3136
|
+
|
|
3137
|
+
Each available entry is navigated independently. Missing and failed
|
|
3138
|
+
entries remain absent; they are never filled from a neighboring entry.
|
|
3139
|
+
"""
|
|
3140
|
+
return TorchNestedBatchFieldDerivativeCollection(self._entries)
|
|
3141
|
+
|
|
3142
|
+
def select(self, index: int | None = None) -> "TorchBatchFieldDerivativePayload":
|
|
3143
|
+
"""Select one field position in every available batch entry.
|
|
3144
|
+
|
|
3145
|
+
Parameters
|
|
3146
|
+
----------
|
|
3147
|
+
index : int | None, optional
|
|
3148
|
+
Field position. ``None`` selects all positions.
|
|
3149
|
+
|
|
3150
|
+
Returns
|
|
3151
|
+
-------
|
|
3152
|
+
TorchBatchFieldDerivativePayload
|
|
3153
|
+
Selected derivatives with original batch indices.
|
|
3154
|
+
"""
|
|
3155
|
+
return TorchBatchFieldDerivativePayload(
|
|
3156
|
+
tuple(
|
|
3157
|
+
(batch_index, derivative.select(index))
|
|
3158
|
+
for batch_index, derivative in self._entries
|
|
3159
|
+
)
|
|
3160
|
+
)
|
|
3161
|
+
|
|
3162
|
+
def to_xarray(self) -> object:
|
|
3163
|
+
"""Raise because Torch batch derivative records support dictionary export only.
|
|
3164
|
+
|
|
3165
|
+
Returns
|
|
3166
|
+
-------
|
|
3167
|
+
object
|
|
3168
|
+
This method does not return.
|
|
3169
|
+
|
|
3170
|
+
Raises
|
|
3171
|
+
------
|
|
3172
|
+
UnsupportedExportError
|
|
3173
|
+
Always. Batch Torch derivative records support ``to_dict()`` only.
|
|
3174
|
+
"""
|
|
3175
|
+
raise UnsupportedExportError("Torch derivative records support to_dict() only.")
|
|
3176
|
+
|
|
3177
|
+
|
|
3178
|
+
class TorchNestedBatchFieldDerivativeCollection:
|
|
3179
|
+
"""Navigate second-order derivatives for independently bound batch entries."""
|
|
3180
|
+
|
|
3181
|
+
def __init__(
|
|
3182
|
+
self, entries: tuple[tuple[int, TorchFieldDerivativePayload], ...]
|
|
3183
|
+
) -> None:
|
|
3184
|
+
self._entries = entries
|
|
3185
|
+
|
|
3186
|
+
def keys(self) -> tuple[str, ...]:
|
|
3187
|
+
"""Return second-order key names present in at least one entry."""
|
|
3188
|
+
names: list[str] = []
|
|
3189
|
+
for _, derivative in self._entries:
|
|
3190
|
+
for name in derivative.derivatives.keys():
|
|
3191
|
+
if name not in names:
|
|
3192
|
+
names.append(name)
|
|
3193
|
+
return tuple(names)
|
|
3194
|
+
|
|
3195
|
+
def __getitem__(
|
|
3196
|
+
self, name: str
|
|
3197
|
+
) -> "TorchBatchFieldDerivativePayload | TorchBatchComplexFieldDerivativePayload":
|
|
3198
|
+
"""Return independently selected pair payloads by original batch index."""
|
|
3199
|
+
if any(
|
|
3200
|
+
derivative._selection.connection == "inspection"
|
|
3201
|
+
for _, derivative in self._entries
|
|
3202
|
+
):
|
|
3203
|
+
raise ValueError("Third-order field derivatives are not available.")
|
|
3204
|
+
if name not in self.keys():
|
|
3205
|
+
raise KeyError(name)
|
|
3206
|
+
real: list[tuple[int, TorchFieldDerivativePayload]] = []
|
|
3207
|
+
imag: list[tuple[int, TorchFieldDerivativePayload]] = []
|
|
3208
|
+
complex_output: bool = False
|
|
3209
|
+
for index, derivative in self._entries:
|
|
3210
|
+
if name not in derivative.derivatives.keys():
|
|
3211
|
+
continue
|
|
3212
|
+
selected: object = derivative.derivatives[name]
|
|
3213
|
+
if isinstance(selected, TorchComplexFieldDerivativePayload):
|
|
3214
|
+
complex_output = True
|
|
3215
|
+
real.append((index, selected.real))
|
|
3216
|
+
if selected.imag is not None:
|
|
3217
|
+
imag.append((index, selected.imag))
|
|
3218
|
+
else:
|
|
3219
|
+
real.append((index, cast(TorchFieldDerivativePayload, selected)))
|
|
3220
|
+
real_payload: TorchBatchFieldDerivativePayload = (
|
|
3221
|
+
TorchBatchFieldDerivativePayload(tuple(real))
|
|
3222
|
+
)
|
|
3223
|
+
if complex_output:
|
|
3224
|
+
return TorchBatchComplexFieldDerivativePayload(
|
|
3225
|
+
real_payload,
|
|
3226
|
+
TorchBatchFieldDerivativePayload(tuple(imag)) if imag else None,
|
|
3227
|
+
)
|
|
3228
|
+
return real_payload
|
|
3229
|
+
|
|
3230
|
+
|
|
3231
|
+
@dataclass(frozen=True, slots=True)
|
|
3232
|
+
class TorchBatchComplexFieldDerivativePayload:
|
|
3233
|
+
"""Store packed output-component derivatives across a batch.
|
|
3234
|
+
|
|
3235
|
+
This payload composes the component behavior of
|
|
3236
|
+
:class:`TorchComplexFieldDerivativePayload` across batch entries. The ``real``
|
|
3237
|
+
and optional ``imag`` values are batch derivative payloads. Selection applies
|
|
3238
|
+
to both components.
|
|
3239
|
+
|
|
3240
|
+
A lookup in :class:`TorchBatchFieldDerivativeCollection` returns this payload
|
|
3241
|
+
for a complex input.
|
|
3242
|
+
|
|
3243
|
+
Attributes
|
|
3244
|
+
----------
|
|
3245
|
+
real : TorchBatchFieldDerivativePayload
|
|
3246
|
+
Packed gradient of the real output component by original batch index.
|
|
3247
|
+
imag : TorchBatchFieldDerivativePayload | None
|
|
3248
|
+
Packed gradient of the imaginary output component, or ``None`` when the field
|
|
3249
|
+
output is real.
|
|
3250
|
+
"""
|
|
3251
|
+
|
|
3252
|
+
real: TorchBatchFieldDerivativePayload
|
|
3253
|
+
imag: TorchBatchFieldDerivativePayload | None
|
|
3254
|
+
|
|
3255
|
+
@property
|
|
3256
|
+
def derivatives(self) -> "TorchNestedBatchComplexFieldDerivativeCollection":
|
|
3257
|
+
"""Return nested derivatives for both output components."""
|
|
3258
|
+
return TorchNestedBatchComplexFieldDerivativeCollection(self)
|
|
3259
|
+
|
|
3260
|
+
def select(
|
|
3261
|
+
self, index: int | None = None
|
|
3262
|
+
) -> "TorchBatchComplexFieldDerivativePayload":
|
|
3263
|
+
"""Select the same field position from both output components.
|
|
3264
|
+
|
|
3265
|
+
Parameters
|
|
3266
|
+
----------
|
|
3267
|
+
index : int | None, optional
|
|
3268
|
+
Field position. ``None`` selects all positions.
|
|
3269
|
+
|
|
3270
|
+
Returns
|
|
3271
|
+
-------
|
|
3272
|
+
TorchBatchComplexFieldDerivativePayload
|
|
3273
|
+
Complex derivative payload with both components selected.
|
|
3274
|
+
"""
|
|
3275
|
+
return TorchBatchComplexFieldDerivativePayload(
|
|
3276
|
+
self.real.select(index),
|
|
3277
|
+
None if self.imag is None else self.imag.select(index),
|
|
3278
|
+
)
|
|
3279
|
+
|
|
3280
|
+
|
|
3281
|
+
class TorchNestedBatchComplexFieldDerivativeCollection:
|
|
3282
|
+
"""Navigate nested derivative pairs while preserving output components."""
|
|
3283
|
+
|
|
3284
|
+
def __init__(self, owner: TorchBatchComplexFieldDerivativePayload) -> None:
|
|
3285
|
+
self._owner = owner
|
|
3286
|
+
|
|
3287
|
+
def keys(self) -> tuple[str, ...]:
|
|
3288
|
+
"""Return second-order names available in either component."""
|
|
3289
|
+
names: list[str] = list(self._owner.real.derivatives.keys())
|
|
3290
|
+
if self._owner.imag is not None:
|
|
3291
|
+
names.extend(
|
|
3292
|
+
name
|
|
3293
|
+
for name in self._owner.imag.derivatives.keys()
|
|
3294
|
+
if name not in names
|
|
3295
|
+
)
|
|
3296
|
+
return tuple(names)
|
|
3297
|
+
|
|
3298
|
+
def __getitem__(self, name: str) -> "TorchBatchNestedComplexFieldDerivativePayload":
|
|
3299
|
+
"""Return nested real and imaginary outputs without positional alignment."""
|
|
3300
|
+
derivative_entries: tuple[tuple[int, TorchFieldDerivativePayload], ...] = (
|
|
3301
|
+
self._owner.real._entries
|
|
3302
|
+
+ (() if self._owner.imag is None else self._owner.imag._entries)
|
|
3303
|
+
)
|
|
3304
|
+
if any(
|
|
3305
|
+
derivative._selection.connection == "inspection"
|
|
3306
|
+
for _, derivative in derivative_entries
|
|
3307
|
+
):
|
|
3308
|
+
raise ValueError("Third-order field derivatives are not available.")
|
|
3309
|
+
if name not in self.keys():
|
|
3310
|
+
raise KeyError(name)
|
|
3311
|
+
real: object = self._owner.real.derivatives[name]
|
|
3312
|
+
imaginary: object | None = (
|
|
3313
|
+
None
|
|
3314
|
+
if self._owner.imag is None
|
|
3315
|
+
or name not in self._owner.imag.derivatives.keys()
|
|
3316
|
+
else self._owner.imag.derivatives[name]
|
|
3317
|
+
)
|
|
3318
|
+
return TorchBatchNestedComplexFieldDerivativePayload(
|
|
3319
|
+
real=cast(
|
|
3320
|
+
TorchBatchFieldDerivativePayload
|
|
3321
|
+
| TorchBatchComplexFieldDerivativePayload,
|
|
3322
|
+
real,
|
|
3323
|
+
),
|
|
3324
|
+
imag=cast(
|
|
3325
|
+
TorchBatchFieldDerivativePayload
|
|
3326
|
+
| TorchBatchComplexFieldDerivativePayload
|
|
3327
|
+
| None,
|
|
3328
|
+
imaginary,
|
|
3329
|
+
),
|
|
3330
|
+
)
|
|
3331
|
+
|
|
3332
|
+
|
|
3333
|
+
@dataclass(frozen=True, slots=True)
|
|
3334
|
+
class TorchBatchNestedComplexFieldDerivativePayload:
|
|
3335
|
+
"""Represent nested output components, each retaining its input packing."""
|
|
3336
|
+
|
|
3337
|
+
real: TorchBatchFieldDerivativePayload | TorchBatchComplexFieldDerivativePayload
|
|
3338
|
+
imag: (
|
|
3339
|
+
TorchBatchFieldDerivativePayload
|
|
3340
|
+
| TorchBatchComplexFieldDerivativePayload
|
|
3341
|
+
| None
|
|
3342
|
+
)
|
|
3343
|
+
|
|
3344
|
+
|
|
3345
|
+
def _transform_mapping(
|
|
3346
|
+
mapping: Mapping[object, object],
|
|
3347
|
+
transforms: tuple[_TransformName, ...],
|
|
3348
|
+
torch_module: object,
|
|
3349
|
+
*,
|
|
3350
|
+
grid_rank: int,
|
|
3351
|
+
) -> Mapping[object, object]:
|
|
3352
|
+
if not transforms:
|
|
3353
|
+
return mapping
|
|
3354
|
+
transformed: dict[object, object] = {}
|
|
3355
|
+
for key, value in mapping.items():
|
|
3356
|
+
if key == "field":
|
|
3357
|
+
transformed[key] = _transform_field_value(
|
|
3358
|
+
value, transforms, torch_module, grid_rank
|
|
3359
|
+
)
|
|
3360
|
+
elif isinstance(value, Mapping):
|
|
3361
|
+
transformed[key] = _transform_mapping(
|
|
3362
|
+
value,
|
|
3363
|
+
transforms,
|
|
3364
|
+
torch_module,
|
|
3365
|
+
grid_rank=grid_rank,
|
|
3366
|
+
)
|
|
3367
|
+
else:
|
|
3368
|
+
transformed[key] = value
|
|
3369
|
+
return transformed
|
|
3370
|
+
|
|
3371
|
+
|
|
3372
|
+
def _field_grid_rank(mapping: Mapping[object, object]) -> int:
|
|
3373
|
+
"""Return the active spatial rank using the ordinary field topology rules."""
|
|
3374
|
+
|
|
3375
|
+
raw_field: object = mapping.get("field")
|
|
3376
|
+
if isinstance(raw_field, (list, tuple)) and raw_field:
|
|
3377
|
+
raw_field = raw_field[0]
|
|
3378
|
+
field_shape: tuple[int, ...] = tuple(
|
|
3379
|
+
int(size) for size in np.asarray(cast(Sequence[object], raw_field)).shape
|
|
3380
|
+
)
|
|
3381
|
+
return len(resolve_coordinates(mapping, field_shape=field_shape).grid_shape)
|
|
3382
|
+
|
|
3383
|
+
|
|
3384
|
+
def _convert_numeric(value: object, torch_module: object) -> object:
|
|
3385
|
+
converted: TorchTensor | None = numeric_tensor(value, torch_module, device="cpu")
|
|
3386
|
+
return value if converted is None else converted
|
|
3387
|
+
|
|
3388
|
+
|
|
3389
|
+
def _detach(value: object) -> object:
|
|
3390
|
+
detach: object = getattr(value, "detach", None)
|
|
3391
|
+
return detach() if callable(detach) else value
|
|
3392
|
+
|
|
3393
|
+
|
|
3394
|
+
def _is_complex_tensor(value: object, torch_module: object) -> bool:
|
|
3395
|
+
is_complex: object = getattr(torch_module, "is_complex", None)
|
|
3396
|
+
if callable(is_complex):
|
|
3397
|
+
return bool(is_complex(value))
|
|
3398
|
+
return "complex" in str(getattr(value, "dtype", ""))
|
|
3399
|
+
|
|
3400
|
+
|
|
3401
|
+
def _jvp(
|
|
3402
|
+
value: object,
|
|
3403
|
+
tangent: object,
|
|
3404
|
+
transforms: tuple[_TransformName, ...],
|
|
3405
|
+
torch_module: object,
|
|
3406
|
+
*,
|
|
3407
|
+
grid_rank: int,
|
|
3408
|
+
) -> tuple[object, object]:
|
|
3409
|
+
"""Apply field operations and their forward directional derivatives."""
|
|
3410
|
+
|
|
3411
|
+
current: object = value
|
|
3412
|
+
current_tangent: object = tangent
|
|
3413
|
+
for operation in transforms:
|
|
3414
|
+
if operation == "real":
|
|
3415
|
+
current = getattr(torch_module, "real")(current)
|
|
3416
|
+
current_tangent = getattr(torch_module, "real")(current_tangent)
|
|
3417
|
+
elif operation == "imag":
|
|
3418
|
+
current = getattr(torch_module, "imag")(current)
|
|
3419
|
+
current_tangent = getattr(torch_module, "imag")(current_tangent)
|
|
3420
|
+
elif operation == "abs":
|
|
3421
|
+
magnitude: object = getattr(torch_module, "abs")(current)
|
|
3422
|
+
numerator: object = getattr(torch_module, "real")(
|
|
3423
|
+
getattr(torch_module, "conj")(current) * current_tangent
|
|
3424
|
+
)
|
|
3425
|
+
current_tangent = getattr(torch_module, "where")(
|
|
3426
|
+
magnitude == 0,
|
|
3427
|
+
getattr(torch_module, "zeros_like")(magnitude),
|
|
3428
|
+
getattr(numerator, "__truediv__")(magnitude),
|
|
3429
|
+
)
|
|
3430
|
+
current = magnitude
|
|
3431
|
+
elif operation == "phase":
|
|
3432
|
+
phase_magnitude: object = getattr(torch_module, "abs")(current)
|
|
3433
|
+
numerator = getattr(torch_module, "imag")(
|
|
3434
|
+
getattr(torch_module, "conj")(current) * current_tangent
|
|
3435
|
+
)
|
|
3436
|
+
current_tangent = getattr(torch_module, "where")(
|
|
3437
|
+
phase_magnitude == 0,
|
|
3438
|
+
getattr(torch_module, "zeros_like")(phase_magnitude),
|
|
3439
|
+
getattr(numerator, "__truediv__")(
|
|
3440
|
+
getattr(phase_magnitude, "__mul__")(phase_magnitude)
|
|
3441
|
+
),
|
|
3442
|
+
)
|
|
3443
|
+
current = getattr(torch_module, "angle")(current)
|
|
3444
|
+
elif operation == "intensity":
|
|
3445
|
+
magnitude = getattr(torch_module, "abs")(current)
|
|
3446
|
+
intensity: object = getattr(magnitude, "__mul__")(magnitude)
|
|
3447
|
+
current_tangent = getattr(
|
|
3448
|
+
getattr(torch_module, "real")(
|
|
3449
|
+
getattr(torch_module, "conj")(current) * current_tangent
|
|
3450
|
+
),
|
|
3451
|
+
"__mul__",
|
|
3452
|
+
)(2)
|
|
3453
|
+
if getattr(current, "ndim") == grid_rank + 1:
|
|
3454
|
+
current_tangent = getattr(current_tangent, "sum")(dim=-1)
|
|
3455
|
+
intensity = getattr(intensity, "sum")(dim=-1)
|
|
3456
|
+
current = intensity
|
|
3457
|
+
return current, current_tangent
|
|
3458
|
+
|
|
3459
|
+
|
|
3460
|
+
def _transform_field_value(
|
|
3461
|
+
value: object,
|
|
3462
|
+
transforms: tuple[_TransformName, ...],
|
|
3463
|
+
torch_module: object,
|
|
3464
|
+
grid_rank: int,
|
|
3465
|
+
) -> object:
|
|
3466
|
+
if is_tensor(value, torch_module):
|
|
3467
|
+
transformed: object = value
|
|
3468
|
+
for operation in transforms:
|
|
3469
|
+
if operation == "intensity":
|
|
3470
|
+
magnitude: object = getattr(torch_module, "abs")(transformed)
|
|
3471
|
+
magnitude_squared: object = getattr(magnitude, "__mul__")(magnitude)
|
|
3472
|
+
if getattr(transformed, "ndim") == grid_rank + 1:
|
|
3473
|
+
transformed = getattr(magnitude_squared, "sum")(dim=-1)
|
|
3474
|
+
else:
|
|
3475
|
+
transformed = magnitude_squared
|
|
3476
|
+
else:
|
|
3477
|
+
transformed = _apply_torch_transform(
|
|
3478
|
+
operation, transformed, torch_module
|
|
3479
|
+
)
|
|
3480
|
+
return transformed
|
|
3481
|
+
if isinstance(value, list):
|
|
3482
|
+
return [
|
|
3483
|
+
_transform_field_value(item, transforms, torch_module, grid_rank)
|
|
3484
|
+
for item in value
|
|
3485
|
+
]
|
|
3486
|
+
if isinstance(value, tuple):
|
|
3487
|
+
return tuple(
|
|
3488
|
+
_transform_field_value(item, transforms, torch_module, grid_rank)
|
|
3489
|
+
for item in value
|
|
3490
|
+
)
|
|
3491
|
+
return value
|
|
3492
|
+
|
|
3493
|
+
|
|
3494
|
+
def _apply_torch_transform(
|
|
3495
|
+
operation: _TransformName, value: object, torch_module: object
|
|
3496
|
+
) -> object:
|
|
3497
|
+
if operation != "phase":
|
|
3498
|
+
return getattr(torch_module, operation)(value)
|
|
3499
|
+
magnitude: object = getattr(torch_module, "abs")(value)
|
|
3500
|
+
phase: object = getattr(torch_module, "angle")(value)
|
|
3501
|
+
return getattr(torch_module, "where")(
|
|
3502
|
+
magnitude == 0,
|
|
3503
|
+
getattr(torch_module, "zeros_like")(phase),
|
|
3504
|
+
phase,
|
|
3505
|
+
)
|
|
3506
|
+
|
|
3507
|
+
|
|
3508
|
+
class TorchPostprocessCollection:
|
|
3509
|
+
"""Provide Torch-aware access to a result's postprocess records.
|
|
3510
|
+
|
|
3511
|
+
Indexing or iteration returns :class:`TorchPostprocessRecord` values. For
|
|
3512
|
+
the navigation and export contract shared with ordinary results, see
|
|
3513
|
+
:class:`jcmsuite.results.PostprocessCollection`.
|
|
3514
|
+
|
|
3515
|
+
This class is returned by result accessors. Do not construct it directly.
|
|
3516
|
+
"""
|
|
3517
|
+
|
|
3518
|
+
def __init__(
|
|
3519
|
+
self,
|
|
3520
|
+
collection: object,
|
|
3521
|
+
bindings: BindingMap,
|
|
3522
|
+
inputs: tuple[TorchTensor, ...],
|
|
3523
|
+
torch_module: object,
|
|
3524
|
+
) -> None:
|
|
3525
|
+
self._collection, self._bindings, self._inputs, self._torch = (
|
|
3526
|
+
collection,
|
|
3527
|
+
bindings,
|
|
3528
|
+
inputs,
|
|
3529
|
+
torch_module,
|
|
3530
|
+
)
|
|
3531
|
+
|
|
3532
|
+
def __len__(self) -> int:
|
|
3533
|
+
"""Return the number of postprocess records.
|
|
3534
|
+
|
|
3535
|
+
Returns
|
|
3536
|
+
-------
|
|
3537
|
+
int
|
|
3538
|
+
Number of postprocess records.
|
|
3539
|
+
"""
|
|
3540
|
+
return len(cast(Sequence[object], self._collection))
|
|
3541
|
+
|
|
3542
|
+
def __iter__(self) -> Iterator[TorchPostprocessRecord]:
|
|
3543
|
+
"""Iterate over Torch postprocess records in project order.
|
|
3544
|
+
|
|
3545
|
+
Returns
|
|
3546
|
+
-------
|
|
3547
|
+
Iterator[TorchPostprocessRecord]
|
|
3548
|
+
Torch-aware records in postprocess order.
|
|
3549
|
+
"""
|
|
3550
|
+
return (self[index] for index in range(len(self)))
|
|
3551
|
+
|
|
3552
|
+
def __getitem__(self, index: int) -> TorchPostprocessRecord:
|
|
3553
|
+
"""Return one Torch postprocess record by its integer position.
|
|
3554
|
+
|
|
3555
|
+
Parameters
|
|
3556
|
+
----------
|
|
3557
|
+
index : int
|
|
3558
|
+
Postprocess position.
|
|
3559
|
+
|
|
3560
|
+
Returns
|
|
3561
|
+
-------
|
|
3562
|
+
TorchPostprocessRecord
|
|
3563
|
+
Selected Torch-aware record.
|
|
3564
|
+
"""
|
|
3565
|
+
return TorchPostprocessRecord(self._collection[index], self._bindings, self._inputs, self._torch) # type: ignore[index]
|
|
3566
|
+
|
|
3567
|
+
def titles(self) -> tuple[str, ...]:
|
|
3568
|
+
"""Return postprocess titles in project order.
|
|
3569
|
+
|
|
3570
|
+
Returns
|
|
3571
|
+
-------
|
|
3572
|
+
tuple[str, ...]
|
|
3573
|
+
Titles in postprocess order.
|
|
3574
|
+
"""
|
|
3575
|
+
return cast(tuple[str, ...], getattr(self._collection, "titles")())
|
|
3576
|
+
|
|
3577
|
+
def __getattr__(self, name: str) -> object:
|
|
3578
|
+
return getattr(self._collection, name)
|
|
3579
|
+
|
|
3580
|
+
|
|
3581
|
+
class TorchBatchPostprocessCollection:
|
|
3582
|
+
"""Provide Torch-aware access to postprocess streams across a batch.
|
|
3583
|
+
|
|
3584
|
+
The ordinary :class:`jcmsuite.results.BatchPostprocessCollection` defines
|
|
3585
|
+
the batch navigation. This wrapper adds the Torch semantics of
|
|
3586
|
+
:class:`TorchPostprocessCollection` to each selected record.
|
|
3587
|
+
|
|
3588
|
+
A Torch batch solve result returns this class. Do not construct it directly.
|
|
3589
|
+
"""
|
|
3590
|
+
|
|
3591
|
+
def __init__(
|
|
3592
|
+
self,
|
|
3593
|
+
collection: object,
|
|
3594
|
+
bindings: BindingContext,
|
|
3595
|
+
inputs: InputContext,
|
|
3596
|
+
torch_module: object,
|
|
3597
|
+
) -> None:
|
|
3598
|
+
self._collection, self._bindings, self._inputs, self._torch = (
|
|
3599
|
+
collection,
|
|
3600
|
+
bindings,
|
|
3601
|
+
inputs,
|
|
3602
|
+
torch_module,
|
|
3603
|
+
)
|
|
3604
|
+
|
|
3605
|
+
def __len__(self) -> int:
|
|
3606
|
+
"""Return the number of postprocess streams.
|
|
3607
|
+
|
|
3608
|
+
Returns
|
|
3609
|
+
-------
|
|
3610
|
+
int
|
|
3611
|
+
Number of postprocess streams.
|
|
3612
|
+
"""
|
|
3613
|
+
return len(cast(Sequence[object], self._collection))
|
|
3614
|
+
|
|
3615
|
+
def __iter__(self) -> Iterator[TorchBatchPostprocessRecord]:
|
|
3616
|
+
"""Iterate over batch postprocess streams in project order.
|
|
3617
|
+
|
|
3618
|
+
Returns
|
|
3619
|
+
-------
|
|
3620
|
+
Iterator[TorchBatchPostprocessRecord]
|
|
3621
|
+
Torch-aware records in postprocess order.
|
|
3622
|
+
"""
|
|
3623
|
+
return (self[index] for index in range(len(self)))
|
|
3624
|
+
|
|
3625
|
+
def __getitem__(self, index: int) -> TorchBatchPostprocessRecord:
|
|
3626
|
+
"""Return one batch postprocess stream.
|
|
3627
|
+
|
|
3628
|
+
Parameters
|
|
3629
|
+
----------
|
|
3630
|
+
index : int
|
|
3631
|
+
Postprocess position.
|
|
3632
|
+
|
|
3633
|
+
Returns
|
|
3634
|
+
-------
|
|
3635
|
+
TorchBatchPostprocessRecord
|
|
3636
|
+
Selected batch record with entry-specific input contexts.
|
|
3637
|
+
"""
|
|
3638
|
+
return TorchBatchPostprocessRecord(
|
|
3639
|
+
self._collection[index], self._bindings, self._inputs, self._torch # type: ignore[index]
|
|
3640
|
+
)
|
|
3641
|
+
|
|
3642
|
+
def titles(self) -> tuple[str, ...]:
|
|
3643
|
+
"""Return postprocess titles in project order.
|
|
3644
|
+
|
|
3645
|
+
Returns
|
|
3646
|
+
-------
|
|
3647
|
+
tuple[str, ...]
|
|
3648
|
+
Titles from the ordinary batch collection.
|
|
3649
|
+
"""
|
|
3650
|
+
return cast(tuple[str, ...], getattr(self._collection, "titles")())
|
|
3651
|
+
|
|
3652
|
+
def __getattr__(self, name: str) -> object:
|
|
3653
|
+
return getattr(self._collection, name)
|
|
3654
|
+
|
|
3655
|
+
|
|
3656
|
+
class _TorchResultBase:
|
|
3657
|
+
"""Implement shared Torch-aware access for solve-result wrappers.
|
|
3658
|
+
|
|
3659
|
+
The wrapper preserves the ordinary result returned by the shared solve
|
|
3660
|
+
implementation. Use :meth:`~jcmsuite.torch.results.TorchSolveResult.untorch`
|
|
3661
|
+
on a public wrapper when ordinary result and payload behavior is required
|
|
3662
|
+
instead of Torch-connected values.
|
|
3663
|
+
"""
|
|
3664
|
+
|
|
3665
|
+
def __init__(
|
|
3666
|
+
self,
|
|
3667
|
+
result: object,
|
|
3668
|
+
bindings: BindingContext,
|
|
3669
|
+
inputs: InputContext,
|
|
3670
|
+
torch_module: object,
|
|
3671
|
+
) -> None:
|
|
3672
|
+
self._result, self._bindings, self._inputs, self._torch = (
|
|
3673
|
+
result,
|
|
3674
|
+
bindings,
|
|
3675
|
+
inputs,
|
|
3676
|
+
torch_module,
|
|
3677
|
+
)
|
|
3678
|
+
|
|
3679
|
+
def untorch(
|
|
3680
|
+
self,
|
|
3681
|
+
) -> SolveResult | BatchSolveResult | BundledSolveResult | BundledBatchSolveResult:
|
|
3682
|
+
"""Return the underlying ordinary solve result without recomputing it.
|
|
3683
|
+
|
|
3684
|
+
Returns
|
|
3685
|
+
-------
|
|
3686
|
+
SolveResult | BatchSolveResult | BundledSolveResult | BundledBatchSolveResult
|
|
3687
|
+
The ordinary result produced by the shared solve implementation.
|
|
3688
|
+
"""
|
|
3689
|
+
|
|
3690
|
+
return cast(
|
|
3691
|
+
SolveResult
|
|
3692
|
+
| BatchSolveResult
|
|
3693
|
+
| BundledSolveResult
|
|
3694
|
+
| BundledBatchSolveResult,
|
|
3695
|
+
self._result,
|
|
3696
|
+
)
|
|
3697
|
+
|
|
3698
|
+
def _entry_bindings(self, index: int) -> BindingMap:
|
|
3699
|
+
return (
|
|
3700
|
+
self._bindings[index]
|
|
3701
|
+
if isinstance(self._bindings, tuple)
|
|
3702
|
+
else self._bindings
|
|
3703
|
+
)
|
|
3704
|
+
|
|
3705
|
+
def _entry_inputs(self, index: int) -> tuple[TorchTensor, ...]:
|
|
3706
|
+
return (
|
|
3707
|
+
cast(tuple[tuple[TorchTensor, ...], ...], self._inputs)[index]
|
|
3708
|
+
if self._inputs and isinstance(self._inputs[0], tuple)
|
|
3709
|
+
else self._inputs
|
|
3710
|
+
)
|
|
3711
|
+
|
|
3712
|
+
@property
|
|
3713
|
+
def postprocesses(
|
|
3714
|
+
self,
|
|
3715
|
+
) -> TorchPostprocessCollection | TorchBatchPostprocessCollection:
|
|
3716
|
+
"""Return Torch-aware access to the ordinary postprocess collection."""
|
|
3717
|
+
collection: object = getattr(self._result, "postprocesses")
|
|
3718
|
+
if isinstance(self._result, BatchSolveResult):
|
|
3719
|
+
return TorchBatchPostprocessCollection(
|
|
3720
|
+
collection, self._bindings, self._inputs, self._torch
|
|
3721
|
+
)
|
|
3722
|
+
return TorchPostprocessCollection(
|
|
3723
|
+
collection,
|
|
3724
|
+
self._entry_bindings(0),
|
|
3725
|
+
self._entry_inputs(0),
|
|
3726
|
+
self._torch,
|
|
3727
|
+
)
|
|
3728
|
+
|
|
3729
|
+
def _select(self, index: int | slice) -> object:
|
|
3730
|
+
selected: object = self._result[index] # type: ignore[index]
|
|
3731
|
+
if isinstance(self._result, BundledBatchSolveResult):
|
|
3732
|
+
project_index: int = cast(int, index)
|
|
3733
|
+
project_inputs: tuple[tuple[TorchTensor, ...], ...] = cast(
|
|
3734
|
+
tuple[tuple[tuple[TorchTensor, ...], ...], ...], self._inputs
|
|
3735
|
+
)[project_index]
|
|
3736
|
+
return wrap_result(
|
|
3737
|
+
selected,
|
|
3738
|
+
self._entry_bindings(project_index),
|
|
3739
|
+
project_inputs,
|
|
3740
|
+
self._torch,
|
|
3741
|
+
)
|
|
3742
|
+
if isinstance(index, slice) and isinstance(self._result, BatchSolveResult):
|
|
3743
|
+
return wrap_result(selected, self._bindings, self._inputs, self._torch)
|
|
3744
|
+
if hasattr(selected, "result"):
|
|
3745
|
+
return TorchBatchEntry(
|
|
3746
|
+
selected,
|
|
3747
|
+
self._entry_bindings(index if isinstance(index, int) else 0),
|
|
3748
|
+
self._entry_inputs(index if isinstance(index, int) else 0),
|
|
3749
|
+
self._torch,
|
|
3750
|
+
)
|
|
3751
|
+
selected_index: int = index if isinstance(index, int) else 0
|
|
3752
|
+
return wrap_result(
|
|
3753
|
+
selected,
|
|
3754
|
+
self._entry_bindings(selected_index),
|
|
3755
|
+
self._entry_inputs(selected_index),
|
|
3756
|
+
self._torch,
|
|
3757
|
+
)
|
|
3758
|
+
|
|
3759
|
+
def __getattr__(self, name: str) -> object:
|
|
3760
|
+
return getattr(self._result, name)
|
|
3761
|
+
|
|
3762
|
+
|
|
3763
|
+
class TorchSolveResult(_TorchResultBase):
|
|
3764
|
+
"""Wrap a :class:`~jcmsuite.results.SolveResult` with Torch-aware access."""
|
|
3765
|
+
|
|
3766
|
+
@property
|
|
3767
|
+
def postprocesses(self) -> TorchPostprocessCollection:
|
|
3768
|
+
"""Return the Torch-aware single-result postprocess collection."""
|
|
3769
|
+
return cast(TorchPostprocessCollection, super().postprocesses)
|
|
3770
|
+
|
|
3771
|
+
def untorch(self) -> SolveResult:
|
|
3772
|
+
"""Return the underlying single-project result without recomputing it.
|
|
3773
|
+
|
|
3774
|
+
Returns
|
|
3775
|
+
-------
|
|
3776
|
+
SolveResult
|
|
3777
|
+
The ordinary :class:`~jcmsuite.results.SolveResult`.
|
|
3778
|
+
"""
|
|
3779
|
+
return cast(SolveResult, super().untorch())
|
|
3780
|
+
|
|
3781
|
+
|
|
3782
|
+
class TorchBatchSolveResult(_TorchResultBase):
|
|
3783
|
+
"""Wrap a :class:`~jcmsuite.results.BatchSolveResult` with Torch-aware access."""
|
|
3784
|
+
|
|
3785
|
+
@property
|
|
3786
|
+
def postprocesses(self) -> TorchBatchPostprocessCollection:
|
|
3787
|
+
"""Return the Torch-aware aggregate batch postprocess collection."""
|
|
3788
|
+
return cast(TorchBatchPostprocessCollection, super().postprocesses)
|
|
3789
|
+
|
|
3790
|
+
def untorch(self) -> BatchSolveResult:
|
|
3791
|
+
"""Return the underlying batched result without recomputing it.
|
|
3792
|
+
|
|
3793
|
+
Returns
|
|
3794
|
+
-------
|
|
3795
|
+
BatchSolveResult
|
|
3796
|
+
The ordinary :class:`~jcmsuite.results.BatchSolveResult`.
|
|
3797
|
+
"""
|
|
3798
|
+
return cast(BatchSolveResult, super().untorch())
|
|
3799
|
+
|
|
3800
|
+
def __len__(self) -> int:
|
|
3801
|
+
"""Return the number of batch entries.
|
|
3802
|
+
|
|
3803
|
+
Returns
|
|
3804
|
+
-------
|
|
3805
|
+
int
|
|
3806
|
+
Number of batch entries.
|
|
3807
|
+
"""
|
|
3808
|
+
return len(cast(Sequence[object], self._result))
|
|
3809
|
+
|
|
3810
|
+
def __iter__(self) -> Iterator[object]:
|
|
3811
|
+
"""Iterate over Torch-aware batch entries in input order.
|
|
3812
|
+
|
|
3813
|
+
Returns
|
|
3814
|
+
-------
|
|
3815
|
+
Iterator[object]
|
|
3816
|
+
Torch-aware batch entries.
|
|
3817
|
+
"""
|
|
3818
|
+
return (self[index] for index in range(len(self)))
|
|
3819
|
+
|
|
3820
|
+
def __getitem__(self, index: int | slice) -> object:
|
|
3821
|
+
"""Return one Torch-aware batch entry or a sliced batch result.
|
|
3822
|
+
|
|
3823
|
+
Parameters
|
|
3824
|
+
----------
|
|
3825
|
+
index : int | slice
|
|
3826
|
+
Batch entry position or slice.
|
|
3827
|
+
|
|
3828
|
+
Returns
|
|
3829
|
+
-------
|
|
3830
|
+
object
|
|
3831
|
+
A Torch-aware batch entry or batch result.
|
|
3832
|
+
"""
|
|
3833
|
+
return self._select(index)
|
|
3834
|
+
|
|
3835
|
+
|
|
3836
|
+
class TorchBundledSolveResult(_TorchResultBase):
|
|
3837
|
+
"""Wrap a :class:`~jcmsuite.results.BundledSolveResult` with Torch-aware access."""
|
|
3838
|
+
|
|
3839
|
+
def untorch(self) -> BundledSolveResult:
|
|
3840
|
+
"""Return the underlying ordered-bundle result without recomputing it.
|
|
3841
|
+
|
|
3842
|
+
Returns
|
|
3843
|
+
-------
|
|
3844
|
+
BundledSolveResult
|
|
3845
|
+
The ordinary :class:`~jcmsuite.results.BundledSolveResult`.
|
|
3846
|
+
"""
|
|
3847
|
+
return cast(BundledSolveResult, super().untorch())
|
|
3848
|
+
|
|
3849
|
+
def __len__(self) -> int:
|
|
3850
|
+
"""Return the number of projects in the ordered bundle.
|
|
3851
|
+
|
|
3852
|
+
Returns
|
|
3853
|
+
-------
|
|
3854
|
+
int
|
|
3855
|
+
Number of projects.
|
|
3856
|
+
"""
|
|
3857
|
+
return len(cast(Sequence[object], self._result))
|
|
3858
|
+
|
|
3859
|
+
def __iter__(self) -> Iterator[object]:
|
|
3860
|
+
"""Iterate over project results in ordered bundle order.
|
|
3861
|
+
|
|
3862
|
+
Returns
|
|
3863
|
+
-------
|
|
3864
|
+
Iterator[object]
|
|
3865
|
+
Torch-aware project results.
|
|
3866
|
+
"""
|
|
3867
|
+
return (self[index] for index in range(len(self)))
|
|
3868
|
+
|
|
3869
|
+
def __getitem__(self, index: int | slice) -> object:
|
|
3870
|
+
"""Return one project result by integer position.
|
|
3871
|
+
|
|
3872
|
+
Parameters
|
|
3873
|
+
----------
|
|
3874
|
+
index : int | slice
|
|
3875
|
+
Project position or slice.
|
|
3876
|
+
|
|
3877
|
+
Returns
|
|
3878
|
+
-------
|
|
3879
|
+
object
|
|
3880
|
+
A Torch-aware project result or selected bundle result.
|
|
3881
|
+
"""
|
|
3882
|
+
return self._select(index)
|
|
3883
|
+
|
|
3884
|
+
|
|
3885
|
+
class TorchBundledBatchSolveResult(_TorchResultBase):
|
|
3886
|
+
"""Wrap a :class:`~jcmsuite.results.BundledBatchSolveResult` with Torch-aware access."""
|
|
3887
|
+
|
|
3888
|
+
def untorch(self) -> BundledBatchSolveResult:
|
|
3889
|
+
"""Return the underlying bundled-batch result without recomputing it.
|
|
3890
|
+
|
|
3891
|
+
Returns
|
|
3892
|
+
-------
|
|
3893
|
+
BundledBatchSolveResult
|
|
3894
|
+
The ordinary :class:`~jcmsuite.results.BundledBatchSolveResult`.
|
|
3895
|
+
"""
|
|
3896
|
+
return cast(BundledBatchSolveResult, super().untorch())
|
|
3897
|
+
|
|
3898
|
+
def __len__(self) -> int:
|
|
3899
|
+
"""Return the number of projects in the bundled batch.
|
|
3900
|
+
|
|
3901
|
+
Returns
|
|
3902
|
+
-------
|
|
3903
|
+
int
|
|
3904
|
+
Number of projects.
|
|
3905
|
+
"""
|
|
3906
|
+
return len(cast(Sequence[object], self._result))
|
|
3907
|
+
|
|
3908
|
+
def __iter__(self) -> Iterator[object]:
|
|
3909
|
+
"""Iterate over project batch results in bundle order.
|
|
3910
|
+
|
|
3911
|
+
Returns
|
|
3912
|
+
-------
|
|
3913
|
+
Iterator[object]
|
|
3914
|
+
Torch-aware project batch results.
|
|
3915
|
+
"""
|
|
3916
|
+
return (self[index] for index in range(len(self)))
|
|
3917
|
+
|
|
3918
|
+
def __getitem__(self, index: int | slice) -> object:
|
|
3919
|
+
"""Return one project batch result by integer position.
|
|
3920
|
+
|
|
3921
|
+
Parameters
|
|
3922
|
+
----------
|
|
3923
|
+
index : int | slice
|
|
3924
|
+
Project position or slice.
|
|
3925
|
+
|
|
3926
|
+
Returns
|
|
3927
|
+
-------
|
|
3928
|
+
object
|
|
3929
|
+
A Torch-aware project batch result.
|
|
3930
|
+
"""
|
|
3931
|
+
return self._select(index)
|
|
3932
|
+
|
|
3933
|
+
|
|
3934
|
+
class TorchBatchEntry:
|
|
3935
|
+
"""Expose one batch entry and wrap its successful result when present."""
|
|
3936
|
+
|
|
3937
|
+
def __init__(
|
|
3938
|
+
self,
|
|
3939
|
+
entry: object,
|
|
3940
|
+
bindings: BindingMap,
|
|
3941
|
+
inputs: tuple[TorchTensor, ...],
|
|
3942
|
+
torch_module: object,
|
|
3943
|
+
) -> None:
|
|
3944
|
+
self._entry, self._bindings, self._inputs, self._torch = (
|
|
3945
|
+
entry,
|
|
3946
|
+
bindings,
|
|
3947
|
+
inputs,
|
|
3948
|
+
torch_module,
|
|
3949
|
+
)
|
|
3950
|
+
|
|
3951
|
+
@property
|
|
3952
|
+
def result(self) -> object | None:
|
|
3953
|
+
result: object = getattr(self._entry, "result")
|
|
3954
|
+
return (
|
|
3955
|
+
None
|
|
3956
|
+
if result is None
|
|
3957
|
+
else wrap_result(result, self._bindings, self._inputs, self._torch)
|
|
3958
|
+
)
|
|
3959
|
+
|
|
3960
|
+
def __getattr__(self, name: str) -> object:
|
|
3961
|
+
return getattr(self._entry, name)
|
|
3962
|
+
|
|
3963
|
+
|
|
3964
|
+
class TorchSubmission(Generic[_TorchResultType]):
|
|
3965
|
+
"""Wrap a daemon submission and Torch-wrap the result returned by ``wait``."""
|
|
3966
|
+
|
|
3967
|
+
def __init__(
|
|
3968
|
+
self,
|
|
3969
|
+
submission: object,
|
|
3970
|
+
bindings: BindingContext,
|
|
3971
|
+
inputs: InputContext,
|
|
3972
|
+
torch_module: object,
|
|
3973
|
+
) -> None:
|
|
3974
|
+
self._submission, self._bindings, self._inputs, self._torch = (
|
|
3975
|
+
submission,
|
|
3976
|
+
bindings,
|
|
3977
|
+
inputs,
|
|
3978
|
+
torch_module,
|
|
3979
|
+
)
|
|
3980
|
+
|
|
3981
|
+
def __getattr__(self, name: str) -> object:
|
|
3982
|
+
return getattr(self._submission, name)
|
|
3983
|
+
|
|
3984
|
+
def untorch(self) -> object:
|
|
3985
|
+
"""Return the underlying ordinary submission without recomputing it."""
|
|
3986
|
+
|
|
3987
|
+
return self._submission
|
|
3988
|
+
|
|
3989
|
+
def _entry_bindings(self, index: int) -> BindingMap:
|
|
3990
|
+
return (
|
|
3991
|
+
self._bindings[index]
|
|
3992
|
+
if isinstance(self._bindings, tuple)
|
|
3993
|
+
else self._bindings
|
|
3994
|
+
)
|
|
3995
|
+
|
|
3996
|
+
def _entry_inputs(self, index: int) -> tuple[TorchTensor, ...]:
|
|
3997
|
+
return (
|
|
3998
|
+
cast(tuple[tuple[TorchTensor, ...], ...], self._inputs)[index]
|
|
3999
|
+
if self._inputs and isinstance(self._inputs[0], tuple)
|
|
4000
|
+
else self._inputs
|
|
4001
|
+
)
|
|
4002
|
+
|
|
4003
|
+
def _select(self, index: int | slice) -> object:
|
|
4004
|
+
selected: object = self._submission[index] # type: ignore[index]
|
|
4005
|
+
selected_index: int = index if isinstance(index, int) else 0
|
|
4006
|
+
return wrap_result(
|
|
4007
|
+
selected,
|
|
4008
|
+
self._entry_bindings(selected_index),
|
|
4009
|
+
self._entry_inputs(selected_index),
|
|
4010
|
+
self._torch,
|
|
4011
|
+
)
|
|
4012
|
+
|
|
4013
|
+
@overload
|
|
4014
|
+
def wait(
|
|
4015
|
+
self, *, asynchronous: Literal[False] = False, **kwargs: object
|
|
4016
|
+
) -> _TorchResultType: ...
|
|
4017
|
+
|
|
4018
|
+
@overload
|
|
4019
|
+
def wait(
|
|
4020
|
+
self, *, asynchronous: Literal[True], **kwargs: object
|
|
4021
|
+
) -> Coroutine[object, object, _TorchResultType]: ...
|
|
4022
|
+
|
|
4023
|
+
def wait(
|
|
4024
|
+
self, **kwargs: object
|
|
4025
|
+
) -> _TorchResultType | Coroutine[object, object, _TorchResultType]:
|
|
4026
|
+
"""Wait for completion and return the shape-specific Torch result wrapper.
|
|
4027
|
+
|
|
4028
|
+
Parameters
|
|
4029
|
+
----------
|
|
4030
|
+
kwargs : object
|
|
4031
|
+
Options accepted by the corresponding ordinary submission wait
|
|
4032
|
+
method, such as :meth:`~jcmsuite.results.SolveSubmission.wait`. Set
|
|
4033
|
+
``asynchronous=True`` to receive a coroutine.
|
|
4034
|
+
|
|
4035
|
+
Returns
|
|
4036
|
+
-------
|
|
4037
|
+
_TorchResultType | Coroutine[object, object, _TorchResultType]
|
|
4038
|
+
The Torch result wrapper, or a coroutine that resolves to it.
|
|
4039
|
+
"""
|
|
4040
|
+
return self._wait_impl(**kwargs)
|
|
4041
|
+
|
|
4042
|
+
def _wait_impl(
|
|
4043
|
+
self, **kwargs: object
|
|
4044
|
+
) -> _TorchResultType | Coroutine[object, object, _TorchResultType]:
|
|
4045
|
+
"""Delegate ordinary waiting and wrap the returned result."""
|
|
4046
|
+
waited: object = getattr(self._submission, "wait")(**kwargs)
|
|
4047
|
+
if asyncio.iscoroutine(waited):
|
|
4048
|
+
|
|
4049
|
+
async def bind() -> _TorchResultType:
|
|
4050
|
+
return cast(
|
|
4051
|
+
_TorchResultType,
|
|
4052
|
+
wrap_result(
|
|
4053
|
+
await waited, self._bindings, self._inputs, self._torch
|
|
4054
|
+
),
|
|
4055
|
+
)
|
|
4056
|
+
|
|
4057
|
+
return bind()
|
|
4058
|
+
return cast(
|
|
4059
|
+
_TorchResultType,
|
|
4060
|
+
wrap_result(waited, self._bindings, self._inputs, self._torch),
|
|
4061
|
+
)
|
|
4062
|
+
|
|
4063
|
+
|
|
4064
|
+
class TorchSolveSubmission(TorchSubmission["TorchSolveResult"]):
|
|
4065
|
+
"""Wrap a :class:`~jcmsuite.results.SolveSubmission`."""
|
|
4066
|
+
|
|
4067
|
+
def untorch(self) -> SolveSubmission:
|
|
4068
|
+
"""Return the ordinary single-project submission without recomputing it.
|
|
4069
|
+
|
|
4070
|
+
Returns
|
|
4071
|
+
-------
|
|
4072
|
+
SolveSubmission
|
|
4073
|
+
The underlying :class:`~jcmsuite.results.SolveSubmission`.
|
|
4074
|
+
"""
|
|
4075
|
+
return cast(SolveSubmission, super().untorch())
|
|
4076
|
+
|
|
4077
|
+
@overload
|
|
4078
|
+
def wait(
|
|
4079
|
+
self, *, asynchronous: Literal[False] = False, **kwargs: object
|
|
4080
|
+
) -> TorchSolveResult: ...
|
|
4081
|
+
|
|
4082
|
+
@overload
|
|
4083
|
+
def wait(
|
|
4084
|
+
self, *, asynchronous: Literal[True], **kwargs: object
|
|
4085
|
+
) -> Coroutine[object, object, TorchSolveResult]: ...
|
|
4086
|
+
|
|
4087
|
+
def wait(
|
|
4088
|
+
self, **kwargs: object
|
|
4089
|
+
) -> TorchSolveResult | Coroutine[object, object, TorchSolveResult]:
|
|
4090
|
+
"""Wait for a single-project Torch result.
|
|
4091
|
+
|
|
4092
|
+
Parameters
|
|
4093
|
+
----------
|
|
4094
|
+
kwargs : object
|
|
4095
|
+
Options accepted by :meth:`~jcmsuite.results.SolveSubmission.wait`.
|
|
4096
|
+
Use ``asynchronous=True`` to receive a coroutine.
|
|
4097
|
+
|
|
4098
|
+
Returns
|
|
4099
|
+
-------
|
|
4100
|
+
TorchSolveResult | Coroutine[object, object, TorchSolveResult]
|
|
4101
|
+
The :class:`~jcmsuite.torch.results.TorchSolveResult`, or a
|
|
4102
|
+
coroutine that resolves to it.
|
|
4103
|
+
"""
|
|
4104
|
+
return self._wait_impl(**kwargs)
|
|
4105
|
+
|
|
4106
|
+
|
|
4107
|
+
class TorchBatchSolveSubmission(TorchSubmission["TorchBatchSolveResult"]):
|
|
4108
|
+
"""Wrap a :class:`~jcmsuite.results.BatchSolveSubmission`."""
|
|
4109
|
+
|
|
4110
|
+
def untorch(self) -> BatchSolveSubmission:
|
|
4111
|
+
"""Return the ordinary batched submission without recomputing it.
|
|
4112
|
+
|
|
4113
|
+
Returns
|
|
4114
|
+
-------
|
|
4115
|
+
BatchSolveSubmission
|
|
4116
|
+
The underlying :class:`~jcmsuite.results.BatchSolveSubmission`.
|
|
4117
|
+
"""
|
|
4118
|
+
return cast(BatchSolveSubmission, super().untorch())
|
|
4119
|
+
|
|
4120
|
+
@overload
|
|
4121
|
+
def wait(
|
|
4122
|
+
self, *, asynchronous: Literal[False] = False, **kwargs: object
|
|
4123
|
+
) -> TorchBatchSolveResult: ...
|
|
4124
|
+
|
|
4125
|
+
@overload
|
|
4126
|
+
def wait(
|
|
4127
|
+
self, *, asynchronous: Literal[True], **kwargs: object
|
|
4128
|
+
) -> Coroutine[object, object, TorchBatchSolveResult]: ...
|
|
4129
|
+
|
|
4130
|
+
def wait(
|
|
4131
|
+
self, **kwargs: object
|
|
4132
|
+
) -> TorchBatchSolveResult | Coroutine[object, object, TorchBatchSolveResult]:
|
|
4133
|
+
"""Wait for a batched Torch result.
|
|
4134
|
+
|
|
4135
|
+
Parameters
|
|
4136
|
+
----------
|
|
4137
|
+
kwargs : object
|
|
4138
|
+
Options accepted by :meth:`~jcmsuite.results.BatchSolveSubmission.wait`.
|
|
4139
|
+
Use ``asynchronous=True`` to receive a coroutine.
|
|
4140
|
+
|
|
4141
|
+
Returns
|
|
4142
|
+
-------
|
|
4143
|
+
TorchBatchSolveResult | Coroutine[object, object, TorchBatchSolveResult]
|
|
4144
|
+
The :class:`~jcmsuite.torch.results.TorchBatchSolveResult`, or a
|
|
4145
|
+
coroutine that resolves to it.
|
|
4146
|
+
"""
|
|
4147
|
+
return self._wait_impl(**kwargs)
|
|
4148
|
+
|
|
4149
|
+
def __len__(self) -> int:
|
|
4150
|
+
"""Return the number of batch submissions.
|
|
4151
|
+
|
|
4152
|
+
Returns
|
|
4153
|
+
-------
|
|
4154
|
+
int
|
|
4155
|
+
Number of batch submissions.
|
|
4156
|
+
"""
|
|
4157
|
+
return len(cast(Sequence[object], self._submission))
|
|
4158
|
+
|
|
4159
|
+
def __iter__(self) -> Iterator[object]:
|
|
4160
|
+
"""Iterate over batch submissions in input order.
|
|
4161
|
+
|
|
4162
|
+
Returns
|
|
4163
|
+
-------
|
|
4164
|
+
Iterator[object]
|
|
4165
|
+
Torch-aware batch submissions.
|
|
4166
|
+
"""
|
|
4167
|
+
return (self[index] for index in range(len(self)))
|
|
4168
|
+
|
|
4169
|
+
def __getitem__(self, index: int | slice) -> object:
|
|
4170
|
+
"""Return one Torch-aware batch submission entry or a slice.
|
|
4171
|
+
|
|
4172
|
+
Parameters
|
|
4173
|
+
----------
|
|
4174
|
+
index : int | slice
|
|
4175
|
+
Batch submission position or slice.
|
|
4176
|
+
|
|
4177
|
+
Returns
|
|
4178
|
+
-------
|
|
4179
|
+
object
|
|
4180
|
+
A Torch-aware batch submission entry or batch submission.
|
|
4181
|
+
"""
|
|
4182
|
+
return self._select(index)
|
|
4183
|
+
|
|
4184
|
+
|
|
4185
|
+
class TorchBundledSolveSubmission(TorchSubmission["TorchBundledSolveResult"]):
|
|
4186
|
+
"""Wrap a :class:`~jcmsuite.results.BundledSolveSubmission`."""
|
|
4187
|
+
|
|
4188
|
+
def untorch(self) -> BundledSolveSubmission:
|
|
4189
|
+
"""Return the ordinary ordered-bundle submission without recomputing it.
|
|
4190
|
+
|
|
4191
|
+
Returns
|
|
4192
|
+
-------
|
|
4193
|
+
BundledSolveSubmission
|
|
4194
|
+
The underlying :class:`~jcmsuite.results.BundledSolveSubmission`.
|
|
4195
|
+
"""
|
|
4196
|
+
return cast(BundledSolveSubmission, super().untorch())
|
|
4197
|
+
|
|
4198
|
+
@overload
|
|
4199
|
+
def wait(
|
|
4200
|
+
self, *, asynchronous: Literal[False] = False, **kwargs: object
|
|
4201
|
+
) -> TorchBundledSolveResult: ...
|
|
4202
|
+
|
|
4203
|
+
@overload
|
|
4204
|
+
def wait(
|
|
4205
|
+
self, *, asynchronous: Literal[True], **kwargs: object
|
|
4206
|
+
) -> Coroutine[object, object, TorchBundledSolveResult]: ...
|
|
4207
|
+
|
|
4208
|
+
def wait(
|
|
4209
|
+
self, **kwargs: object
|
|
4210
|
+
) -> TorchBundledSolveResult | Coroutine[object, object, TorchBundledSolveResult]:
|
|
4211
|
+
"""Wait for an ordered-bundle Torch result.
|
|
4212
|
+
|
|
4213
|
+
Parameters
|
|
4214
|
+
----------
|
|
4215
|
+
kwargs : object
|
|
4216
|
+
Options accepted by :meth:`~jcmsuite.results.BundledSolveSubmission.wait`.
|
|
4217
|
+
Use ``asynchronous=True`` to receive a coroutine.
|
|
4218
|
+
|
|
4219
|
+
Returns
|
|
4220
|
+
-------
|
|
4221
|
+
TorchBundledSolveResult | Coroutine[object, object, TorchBundledSolveResult]
|
|
4222
|
+
The :class:`~jcmsuite.torch.results.TorchBundledSolveResult`, or a
|
|
4223
|
+
coroutine that resolves to it.
|
|
4224
|
+
"""
|
|
4225
|
+
return self._wait_impl(**kwargs)
|
|
4226
|
+
|
|
4227
|
+
|
|
4228
|
+
class TorchBundledBatchSolveSubmission(TorchSubmission["TorchBundledBatchSolveResult"]):
|
|
4229
|
+
"""Wrap a :class:`~jcmsuite.results.BundledBatchSolveSubmission`."""
|
|
4230
|
+
|
|
4231
|
+
def untorch(self) -> BundledBatchSolveSubmission:
|
|
4232
|
+
"""Return the ordinary bundled-batch submission without recomputing it.
|
|
4233
|
+
|
|
4234
|
+
Returns
|
|
4235
|
+
-------
|
|
4236
|
+
BundledBatchSolveSubmission
|
|
4237
|
+
The underlying :class:`~jcmsuite.results.BundledBatchSolveSubmission`.
|
|
4238
|
+
"""
|
|
4239
|
+
return cast(BundledBatchSolveSubmission, super().untorch())
|
|
4240
|
+
|
|
4241
|
+
@overload
|
|
4242
|
+
def wait(
|
|
4243
|
+
self, *, asynchronous: Literal[False] = False, **kwargs: object
|
|
4244
|
+
) -> TorchBundledBatchSolveResult: ...
|
|
4245
|
+
|
|
4246
|
+
@overload
|
|
4247
|
+
def wait(
|
|
4248
|
+
self, *, asynchronous: Literal[True], **kwargs: object
|
|
4249
|
+
) -> Coroutine[object, object, TorchBundledBatchSolveResult]: ...
|
|
4250
|
+
|
|
4251
|
+
def wait(
|
|
4252
|
+
self, **kwargs: object
|
|
4253
|
+
) -> (
|
|
4254
|
+
TorchBundledBatchSolveResult
|
|
4255
|
+
| Coroutine[object, object, TorchBundledBatchSolveResult]
|
|
4256
|
+
):
|
|
4257
|
+
"""Wait for a bundled-batch Torch result.
|
|
4258
|
+
|
|
4259
|
+
Parameters
|
|
4260
|
+
----------
|
|
4261
|
+
kwargs : object
|
|
4262
|
+
Options accepted by :meth:`~jcmsuite.results.BundledBatchSolveSubmission.wait`.
|
|
4263
|
+
Use ``asynchronous=True`` to receive a coroutine.
|
|
4264
|
+
|
|
4265
|
+
Returns
|
|
4266
|
+
-------
|
|
4267
|
+
TorchBundledBatchSolveResult | Coroutine[object, object, TorchBundledBatchSolveResult]
|
|
4268
|
+
The :class:`~jcmsuite.torch.results.TorchBundledBatchSolveResult`,
|
|
4269
|
+
or a coroutine that resolves to it.
|
|
4270
|
+
"""
|
|
4271
|
+
return self._wait_impl(**kwargs)
|
|
4272
|
+
|
|
4273
|
+
def __len__(self) -> int:
|
|
4274
|
+
"""Return the number of projects in the bundled batch submission.
|
|
4275
|
+
|
|
4276
|
+
Returns
|
|
4277
|
+
-------
|
|
4278
|
+
int
|
|
4279
|
+
Number of projects.
|
|
4280
|
+
"""
|
|
4281
|
+
return len(cast(Sequence[object], self._submission))
|
|
4282
|
+
|
|
4283
|
+
def __iter__(self) -> Iterator[object]:
|
|
4284
|
+
"""Iterate over project batch submissions in bundle order.
|
|
4285
|
+
|
|
4286
|
+
Returns
|
|
4287
|
+
-------
|
|
4288
|
+
Iterator[object]
|
|
4289
|
+
Torch-aware project batch submissions.
|
|
4290
|
+
"""
|
|
4291
|
+
return (self[index] for index in range(len(self)))
|
|
4292
|
+
|
|
4293
|
+
def __getitem__(self, index: int | slice) -> object:
|
|
4294
|
+
"""Return one project batch submission by position.
|
|
4295
|
+
|
|
4296
|
+
Parameters
|
|
4297
|
+
----------
|
|
4298
|
+
index : int | slice
|
|
4299
|
+
Project batch submission position or slice.
|
|
4300
|
+
|
|
4301
|
+
Returns
|
|
4302
|
+
-------
|
|
4303
|
+
object
|
|
4304
|
+
A Torch-aware project batch submission.
|
|
4305
|
+
"""
|
|
4306
|
+
return self._select(index)
|
|
4307
|
+
|
|
4308
|
+
|
|
4309
|
+
def wrap_result(
|
|
4310
|
+
result: object, bindings: BindingContext, inputs: InputContext, torch_module: object
|
|
4311
|
+
) -> object:
|
|
4312
|
+
result_wrappers: tuple[tuple[type[object], type[_TorchResultBase]], ...] = (
|
|
4313
|
+
(SolveResult, TorchSolveResult),
|
|
4314
|
+
(BatchSolveResult, TorchBatchSolveResult),
|
|
4315
|
+
(BundledSolveResult, TorchBundledSolveResult),
|
|
4316
|
+
(BundledBatchSolveResult, TorchBundledBatchSolveResult),
|
|
4317
|
+
)
|
|
4318
|
+
for result_type, result_wrapper_type in result_wrappers:
|
|
4319
|
+
if isinstance(result, result_type):
|
|
4320
|
+
return result_wrapper_type(result, bindings, inputs, torch_module)
|
|
4321
|
+
submission_wrappers: tuple[
|
|
4322
|
+
tuple[type[object], type[TorchSubmission[object]]], ...
|
|
4323
|
+
] = (
|
|
4324
|
+
(SolveSubmission, TorchSolveSubmission),
|
|
4325
|
+
(BatchSolveSubmission, TorchBatchSolveSubmission),
|
|
4326
|
+
(BundledSolveSubmission, TorchBundledSolveSubmission),
|
|
4327
|
+
(BundledBatchSolveSubmission, TorchBundledBatchSolveSubmission),
|
|
4328
|
+
)
|
|
4329
|
+
for submission_type, submission_wrapper_type in submission_wrappers:
|
|
4330
|
+
if isinstance(result, submission_type):
|
|
4331
|
+
return submission_wrapper_type(result, bindings, inputs, torch_module)
|
|
4332
|
+
return result
|