"""Torch-aware façades for solve results and submissions."""
from __future__ import annotations
import asyncio
from collections.abc import Callable, Coroutine, Iterator, Mapping, Sequence
from dataclasses import dataclass, replace
from enum import IntEnum
from typing import Generic, Literal, Protocol, Self, TypeVar, cast, overload
import numpy as np
from jcmsuite.exceptions import UnsupportedExportError
from jcmsuite.results import (
BatchSolveResult,
BatchSolveSubmission,
BundledBatchSolveResult,
BundledBatchSolveSubmission,
BundledSolveResult,
BundledSolveSubmission,
SolveResult,
SolveSubmission,
TableCollectionPayload,
TablePayload,
)
from jcmsuite.results.field_exports import FieldExportPayload
from jcmsuite.results.field_payloads import resolve_coordinates
from jcmsuite.results.postprocess_payloads import (
TableCollectionDerivativeCollection,
TableCollectionDerivativeView,
TableDerivativeCollection,
TableDerivativeView,
)
from jcmsuite.results.structured_derivatives import StructuredDerivativeCollection
from .autograd import connect_value, convert_mapping, numeric_tensor
from .coordinate_policy import (
binding_labels,
coordinate_labels,
missing_pair,
missing_pairs,
)
from .types import (
BindingContext,
BindingMap,
ComplexDerivative,
DerivativeBinding,
InputContext,
RealDerivative,
TorchTensor,
)
from .validation import is_tensor
_TransformName = Literal["abs", "real", "imag", "phase", "intensity"]
_TRANSFORM_NAMES: frozenset[str] = frozenset(("abs", "real", "imag", "phase"))
_TorchResultType = TypeVar("_TorchResultType", covariant=True)
_OMIT_STRUCTURED_VALUE = object()
_STRUCTURED_ROOT_METADATA_KEYS: frozenset[str] = frozenset(
{"coordinates", "header", "metadata", "title"}
)
def _project_numeric_component(
value: object,
component: Literal["real", "imag"] | None,
backend: object,
real_projection: Literal["project", "preserve", "zero"] = "project",
) -> object:
if (
real_projection != "project"
and component == "imag"
and not (
np.iscomplexobj(value)
if isinstance(value, (np.ndarray, np.number, int, float, complex))
else _is_complex_tensor(value, backend)
)
):
if real_projection == "preserve":
return value
return getattr(backend, "zeros_like")(value)
return value if component is None else getattr(backend, component)(value)
def _pack_numeric_directions(
first: object,
second: object,
component: Literal["real", "imag"] | None,
backend: object,
real_projection: Literal["project", "preserve"] = "project",
) -> object:
left, right = (
_project_numeric_component(value, component, backend, real_projection)
for value in (first, second)
)
return (
getattr(backend, "complex")(left, right)
if real_projection == "preserve"
else getattr(left, "__add__")(getattr(right, "__rmul__")(1j))
)
class _OrdinaryDerivativeCollection(Protocol):
"""Expose only name selection for an unwrapped ordinary collection."""
def __getitem__(self, name: str) -> object: ...
def _is_structured_metadata_key(key: object, *, root: bool) -> bool:
"""Classify root-level schema metadata without hiding nested quantities."""
return (
root and isinstance(key, str) and key.lower() in _STRUCTURED_ROOT_METADATA_KEYS
)
def _without_structured_root_metadata(
mapping: Mapping[object, object],
) -> Mapping[object, object]:
"""Remove root metadata before solver bindings are applied to numeric leaves."""
return {
key: value
for key, value in mapping.items()
if not _is_structured_metadata_key(key, root=True)
}
def _contains_complex_structure(value: object, torch_module: object) -> bool:
if isinstance(value, Mapping):
return any(
_contains_complex_structure(child, torch_module) for child in value.values()
)
tensor: TorchTensor | None = numeric_tensor(value, torch_module, device="cpu")
return tensor is not None and _is_complex_tensor(tensor, torch_module)
def _same_structured_value(left: object, right: object, torch_module: object) -> bool:
left_tensor: TorchTensor | None = numeric_tensor(left, torch_module, device="cpu")
right_tensor: TorchTensor | None = numeric_tensor(right, torch_module, device="cpu")
if left_tensor is not None and right_tensor is not None:
left_array: np.ndarray = cast(
np.ndarray, getattr(left_tensor, "detach")().cpu().numpy()
)
right_array: np.ndarray = cast(
np.ndarray, getattr(right_tensor, "detach")().cpu().numpy()
)
return bool(np.array_equal(left_array, right_array, equal_nan=True))
try:
return bool(np.array_equal(np.asarray(left), np.asarray(right), equal_nan=True))
except (TypeError, ValueError):
return left == right
def _project_structured_component(
base: object,
values: object,
component: Literal["real", "imag"],
torch_module: object,
*,
path: str = "payload",
root: bool = True,
) -> object:
if isinstance(base, Mapping) and isinstance(values, Mapping):
projected: dict[object, object] = {}
for key, base_value in base.items():
if key not in values:
continue
if _is_structured_metadata_key(key, root=root):
projected[key] = base_value
continue
child: object = _project_structured_component(
base_value,
values[key],
component,
torch_module,
path=f"{path}.{key}",
root=False,
)
if child is not _OMIT_STRUCTURED_VALUE:
projected[key] = child
return projected
base_tensor: TorchTensor | None = numeric_tensor(base, torch_module, device="cpu")
value_tensor: TorchTensor | None = numeric_tensor(
values, torch_module, device="cpu"
)
if base_tensor is None or value_tensor is None:
return values
if component == "imag" and (
not _is_complex_tensor(base_tensor, torch_module)
or not _is_complex_tensor(value_tensor, torch_module)
):
return _OMIT_STRUCTURED_VALUE
return _project_numeric_component(value_tensor, component, torch_module)
def _pack_structured_components(
base: object,
first: object,
second: object,
component: Literal["real", "imag"],
torch_module: object,
*,
path: str = "payload",
root: bool = True,
) -> object:
if isinstance(base, Mapping):
if not isinstance(first, Mapping) or not isinstance(second, Mapping):
if first is _OMIT_STRUCTURED_VALUE and second is _OMIT_STRUCTURED_VALUE:
return _OMIT_STRUCTURED_VALUE
raise ValueError(
f"Structured derivative coordinate data is incomplete for quantity {path!r}."
)
packed: dict[object, object] = {}
for key, base_value in base.items():
if _is_structured_metadata_key(key, root=root):
packed[key] = base_value
continue
first_value: object = first.get(key, _OMIT_STRUCTURED_VALUE)
second_value: object = second.get(key, _OMIT_STRUCTURED_VALUE)
child: object = _pack_structured_components(
base_value,
first_value,
second_value,
component,
torch_module,
path=f"{path}.{key}",
root=False,
)
if child is not _OMIT_STRUCTURED_VALUE:
packed[key] = child
return packed
if first is _OMIT_STRUCTURED_VALUE and second is _OMIT_STRUCTURED_VALUE:
return _OMIT_STRUCTURED_VALUE
if first is _OMIT_STRUCTURED_VALUE or second is _OMIT_STRUCTURED_VALUE:
raise ValueError(
f"Structured derivative coordinate data is incomplete for quantity {path!r}."
)
base_tensor: TorchTensor | None = numeric_tensor(base, torch_module, device="cpu")
first_tensor: TorchTensor | None = numeric_tensor(first, torch_module, device="cpu")
second_tensor: TorchTensor | None = numeric_tensor(
second, torch_module, device="cpu"
)
if base_tensor is None or first_tensor is None or second_tensor is None:
return (
first
if _same_structured_value(first, second, torch_module)
else _OMIT_STRUCTURED_VALUE
)
if component == "imag" and not _is_complex_tensor(base_tensor, torch_module):
return _OMIT_STRUCTURED_VALUE
return _pack_numeric_directions(
first_tensor,
second_tensor,
component,
torch_module,
real_projection="preserve",
)
class _TorchRecordData:
"""Convert ordinary postprocess or field data into Torch tensors."""
def __init__(
self,
record: object,
bindings: BindingMap,
inputs: tuple[TorchTensor, ...],
torch_module: object,
transforms: tuple[_TransformName, ...] = (),
) -> None:
self._record, self._bindings, self._inputs, self._torch = (
record,
bindings,
inputs,
torch_module,
)
self._transforms = transforms
def __getattr__(self, name: str) -> object:
return getattr(self._record, name)
def to_dict(self) -> Mapping[object, object]:
"""Return the payload as a mapping with Torch numeric leaves.
Returns
-------
Mapping[object, object]
The ordinary mapping with numeric leaves converted to Torch tensors.
Leaves with solver derivative data remain connected to the bound
inputs; numeric leaves without derivative data are detached.
"""
raw: Mapping[object, object] = self._raw_mapping()
payload: object = getattr(self._record, "payload", None)
if isinstance(payload, TableCollectionPayload):
return self._table_collection_to_dict(payload)
root: object = getattr(self._record, "_mapping", None)
projected: bool = (
isinstance(root, Mapping)
and "derivatives" in root
and "derivatives" not in raw
)
if projected:
raw = dict(raw)
raw["derivatives"] = root["derivatives"] # type: ignore[index]
derivative_raw: object = raw.get("derivatives")
branches: Mapping[str, object] = (
cast(Mapping[str, object], derivative_raw)
if isinstance(derivative_raw, Mapping)
else {}
)
required: set[str] = set(coordinate_labels(self._bindings))
if not branches:
flat_branches: dict[str, object] = {}
for label in required:
field_key: str = f"d_field_{label}"
table_key: str = f"d_{label}"
if field_key in raw:
flat_branches[label] = {"field": raw[field_key]}
elif table_key in raw:
flat_branches[label] = raw[table_key]
branches = flat_branches
if required:
missing: set[str] = required - set(branches)
if missing:
raise ValueError(
"Solver derivative labels are unavailable in the result: "
f"{sorted(missing)!r}."
)
converted: Mapping[object, object] = cast(
Mapping[object, object],
convert_mapping(
raw,
bindings=self._bindings,
inputs=self._inputs,
torch_module=self._torch,
derivative_mapping=branches,
second_derivative_mapping=(
self._field_second_derivatives()
or self._structured_second_derivatives()
or self._table_second_derivatives()
),
),
)
if projected:
converted = dict(converted)
converted.pop("derivatives", None)
if not self._transforms:
return converted
return _transform_mapping(
converted,
self._transforms,
self._torch,
grid_rank=_field_grid_rank(raw),
)
def _table_collection_to_dict(
self, payload: TableCollectionPayload
) -> Mapping[object, object]:
"""Convert identifiable collection members without sharing their derivatives."""
raw_collection: Mapping[object, object] = payload.to_dict()
ordinary_derivatives: object = payload.derivatives
labels: tuple[str, ...] = coordinate_labels(self._bindings)
converted: dict[object, object] = {}
for member, raw_member in raw_collection.items():
if not isinstance(raw_member, Mapping):
converted[member] = raw_member
continue
branches: dict[str, object] = {}
first_views: dict[str, object] = {}
for label in labels:
try:
first_view: object = ordinary_derivatives[label] # type: ignore[index]
except KeyError:
continue
first_views[label] = first_view
first_values: object = getattr(first_view, "to_dict")()
if isinstance(first_values, Mapping):
member_branch: object = first_values.get(member)
if isinstance(member_branch, Mapping):
branches[label] = member_branch
bound_labels: set[str] = set(labels)
present_labels: set[str] = set(branches)
if present_labels and present_labels != bound_labels:
raise ValueError(
f"Incomplete table-collection first derivatives for member {member!r}: missing "
f"{sorted(bound_labels - present_labels)!r}."
)
active_bindings: BindingMap = {
key: binding
for key, binding in self._bindings.items()
if all(label in branches for label in (binding_labels(binding)))
}
active_inputs: tuple[TorchTensor, ...] = tuple(
self._inputs[index]
for index, key in enumerate(self._bindings)
if key in active_bindings
)
pair_map: dict[str, dict[str, object]] = {}
for first in branches:
nested_derivatives: object = getattr(first_views[first], "derivatives")
for second in labels:
try:
pair_view: object = nested_derivatives[second] # type: ignore[index]
except KeyError:
continue
pair_values: object = getattr(pair_view, "to_dict")()
if isinstance(pair_values, Mapping):
member_pair: object = pair_values.get(member)
if isinstance(member_pair, Mapping):
pair_map.setdefault(first, {})[second] = member_pair
converted[member] = convert_mapping(
raw_member,
bindings=active_bindings,
inputs=active_inputs,
torch_module=self._torch,
derivative_mapping=branches or None,
second_derivative_mapping=pair_map or None,
)
return converted
def _field_second_derivatives(self) -> Mapping[str, Mapping[str, object]]:
"""Read pair data through ordinary field derivative navigation."""
if not isinstance(self._record, FieldExportPayload):
return {}
raw_mapping: Mapping[object, object] = cast(
Mapping[object, object], getattr(self._record, "to_dict")()
)
if not any(
isinstance(key, str) and key.startswith("dd_field_") for key in raw_mapping
):
return {}
bound_labels: tuple[str, ...] = coordinate_labels(self._bindings)
result: dict[str, dict[str, object]] = {}
collection: object = self._record.derivatives
for first_label in bound_labels:
try:
first_view: object = collection[first_label] # type: ignore[index]
except KeyError:
continue
second_collection: object = getattr(first_view, "derivatives")
for second_label in bound_labels:
try:
pair_view: object = second_collection[second_label] # type: ignore[index]
except KeyError:
continue
pair_mapping: object = getattr(pair_view, "to_dict")()
if isinstance(pair_mapping, Mapping):
result.setdefault(first_label, {})[second_label] = pair_mapping
return result
def _table_second_derivatives(self) -> Mapping[str, Mapping[str, object]]:
"""Collect table pair payloads through ordinary derivative selection."""
payload: object = getattr(self._record, "payload", self._record)
if not isinstance(payload, TablePayload):
return {}
labels: tuple[str, ...] = coordinate_labels(self._bindings)
result: dict[str, dict[str, object]] = {}
ordinary: TableDerivativeCollection = payload.derivatives
for first in labels:
try:
first_view: TableDerivativeView = ordinary[first]
except KeyError:
continue
second_collection: TableDerivativeCollection = first_view.derivatives
pairs: dict[str, object] = {}
for second in labels:
try:
pair_view: TableDerivativeView = second_collection[second]
except KeyError:
continue
pairs[second] = pair_view.to_dict()
if pairs:
result[first] = pairs
return result
def _structured_second_derivatives(self) -> Mapping[str, Mapping[str, object]]:
"""Read structured numeric pairs through the ordinary derivative views."""
try:
collection: object = getattr(self._record, "derivatives")
except AttributeError:
return {}
if not isinstance(collection, StructuredDerivativeCollection):
return {}
labels: tuple[str, ...] = coordinate_labels(self._bindings)
select: Callable[[str], object] = cast(
Callable[[str], object], getattr(collection, "__getitem__")
)
pairs: dict[str, dict[str, object]] = {}
for first in labels:
try:
first_view: object = select(first)
nested: object = getattr(first_view, "derivatives")
select_second: Callable[[str], object] = cast(
Callable[[str], object], getattr(nested, "__getitem__")
)
except (AttributeError, KeyError):
continue
for second in labels:
try:
pair_view: object = select_second(second)
pair_mapping: object = getattr(pair_view, "to_dict")()
except (AttributeError, KeyError):
continue
if isinstance(pair_mapping, Mapping):
pairs.setdefault(first, {})[second] = pair_mapping
return pairs
def _raw_mapping(self) -> Mapping[object, object]:
records: object = getattr(self._record, "records", None)
if isinstance(records, tuple):
values: dict[object, object] = {}
for record in records:
payload: object = getattr(record, "payload", None)
if payload is None:
continue
projected: object = getattr(payload, "to_dict")()
root: object = getattr(payload, "_mapping", None)
if isinstance(projected, Mapping) and isinstance(root, Mapping):
result: dict[object, object] = dict(projected)
if "derivatives" in root and "derivatives" not in result:
result["derivatives"] = root["derivatives"]
values[getattr(record, "index")] = result
else:
values[getattr(record, "index")] = projected
if values:
return values
return cast(Mapping[object, object], getattr(self._record, "to_dict")())
def _base_mapping(self) -> Mapping[object, object]:
raw: Mapping[object, object] = self._raw_mapping()
return {
key: value
for key, value in raw.items()
if key != "derivatives"
and not (isinstance(key, str) and key.startswith("d_"))
}
def _derivative_branch(self, binding: RealDerivative) -> Mapping[object, object]:
raw: Mapping[object, object] = self._raw_mapping()
derivatives: object = raw.get("derivatives")
if isinstance(derivatives, Mapping) and binding.label in derivatives:
branch: object = derivatives[binding.label]
if isinstance(branch, Mapping):
return branch
field_key: str = f"d_field_{binding.label}"
table_key: str = f"d_{binding.label}"
if field_key in raw:
return {"field": raw[field_key]}
if table_key in raw and isinstance(raw[table_key], Mapping):
return cast(Mapping[object, object], raw[table_key])
raise ValueError(
f"Solver derivative label {binding.label!r} is unavailable in the result."
)
def to_df(self, orient: str | None = None) -> object:
"""Raise because Torch tensor payloads do not support DataFrame export.
Parameters
----------
orient : str | None, optional
DataFrame orientation. The value does not change the error.
Returns
-------
object
This method does not return.
Raises
------
UnsupportedExportError
Always. Use the ordinary solve result for DataFrame export.
"""
raise UnsupportedExportError(
"to_df is not supported for Torch-bound results; use untorch() for ordinary DataFrame exports."
)
def to_xarray(self) -> object:
"""Raise because Torch tensor payloads do not support xarray export.
Returns
-------
object
This method does not return.
Raises
------
UnsupportedExportError
Always. Use the ordinary solve result for xarray export.
"""
raise UnsupportedExportError(
"to_xarray is not supported for Torch-bound results."
)
[docs]
class TorchPostprocessRecord(_TorchRecordData):
"""Wrap one ordinary postprocess record with Torch-aware exports.
Use :attr:`fields` to get the field-export interface when the postprocess
contains field data. Other postprocess data is available through
:meth:`to_dict`. The class is returned by
:class:`TorchPostprocessCollection`; do not construct it directly.
"""
@property
def fields(self) -> TorchFieldExportPayload:
"""Return the field-export view for this postprocess.
Returns
-------
TorchFieldExportPayload
Torch-aware field navigation and export.
"""
return TorchFieldExportPayload(
getattr(self._record, "fields"),
self._bindings,
self._inputs,
self._torch,
)
@property
def derivatives(
self,
) -> (
TorchTableDerivativeCollection
| TorchStructuredDerivativeCollection
| _OrdinaryDerivativeCollection
):
"""Return derivative navigation for this postprocess result."""
payload: object = getattr(self._record, "payload", None)
if isinstance(payload, (TablePayload, TableCollectionPayload)):
return TorchTableDerivativeCollection(self, payload.derivatives, depth=0)
ordinary: object = getattr(self._record, "derivatives")
if isinstance(ordinary, StructuredDerivativeCollection):
return TorchStructuredDerivativeCollection(self, ordinary)
# The ordinary fallback intentionally preserves identity and behavior.
# Its source collection is dynamically supplied by the payload adapter.
return cast(_OrdinaryDerivativeCollection, ordinary)
@dataclass(frozen=True, slots=True)
class _TorchStructuredSelection:
"""Selection state shared by structured Torch derivative navigation."""
order: Literal[0, 1, 2] = 0
output_component: Literal["real", "imag"] | None = None
coordinate_component: Literal["real", "imag"] | None = None
packing: Literal["single", "coordinates"] = "single"
class TorchStructuredDerivativeCollection:
"""Select structured numeric sensitivities using bound Project Key names."""
def __init__(
self,
owner: TorchPostprocessRecord,
collection: object | tuple[object, ...] | None = None,
*,
output_component: Literal["real", "imag"] | None = None,
inspection_only: bool = False,
) -> None:
self._owner = owner
self._collection = (
getattr(owner._record, "derivatives") if collection is None else collection
)
self._selection = _TorchStructuredSelection(
order=2 if inspection_only else 0,
output_component=output_component,
)
def keys(self) -> tuple[str, ...]:
return tuple(
name
for name, value in zip(self._owner._bindings, self._owner._inputs)
if getattr(value, "requires_grad", False)
)
def __getitem__(
self, name: str
) -> "TorchStructuredDerivativeView | TorchStructuredComplexDerivativePayload":
if name not in self.keys():
raise KeyError(name)
if self._selection.order == 2:
raise RuntimeError(
"Third-order structured solver derivatives are unavailable."
)
binding = self._owner._bindings[name]
labels = binding_labels(binding)
collections: tuple[object, ...] = (
self._collection
if isinstance(self._collection, tuple)
else (self._collection,)
)
selected_views: list[object] = []
for collection in collections:
select: Callable[[str], object] = cast(
Callable[[str], object], getattr(collection, "__getitem__")
)
for label in labels:
try:
selected_views.append(select(label))
except KeyError as error:
raise ValueError(
f"Structured derivative for Project Key {name!r} is unavailable."
) from error
nested: bool = any(
getattr(collection, "_derivative_order", 0) >= 1
for collection in collections
)
view = TorchStructuredDerivativeView(
self._owner,
name,
tuple(selected_views),
labels,
output_component=self._selection.output_component,
pack_coordinates=(len(collections) > 1 or len(labels) > 1),
inspection_only=nested,
)
if isinstance(binding, RealDerivative):
if self._selection.output_component is not None:
return view
if _contains_complex_structure(
self._owner._base_mapping(), self._owner._torch
):
return TorchStructuredComplexDerivativePayload(
real=view.with_component("real"),
imag=(
view.with_component("imag")
if _contains_complex_structure(
self._owner._base_mapping(), self._owner._torch
)
else None
),
)
return view
if nested:
return TorchStructuredComplexDerivativePayload(
real=view.with_coordinate_component("real"),
imag=view.with_coordinate_component("imag"),
)
return TorchStructuredComplexDerivativePayload(
real=view.with_component("real"),
imag=(
view.with_component("imag")
if _contains_complex_structure(
self._owner._base_mapping(), self._owner._torch
)
else None
),
)
class TorchStructuredComplexDerivativePayload:
"""Expose structured output components or nested input-coordinate columns."""
def __init__(
self,
*,
real: "TorchStructuredDerivativeView",
imag: "TorchStructuredDerivativeView | None",
) -> None:
self.real = real
self.imag = imag
def to_dict(self) -> Mapping[object, object]:
"""Require output-component selection before dictionary export."""
raise ValueError(
"Select the 'real' or 'imag' output component before exporting "
"a complex structured derivative."
)
class TorchStructuredDerivativeView:
"""Torch dictionary view of a structured first- or second-order derivative."""
def __init__(
self,
owner: TorchPostprocessRecord,
name: str,
views: tuple[object, ...],
labels: tuple[str, ...],
*,
output_component: Literal["real", "imag"] | None = None,
coordinate_component: Literal["real", "imag"] | None = None,
pack_coordinates: bool = False,
inspection_only: bool = False,
) -> None:
self._owner, self._name, self._views = owner, name, views
self._labels = labels
self._selection = _TorchStructuredSelection(
order=2 if inspection_only else 1,
output_component=output_component,
coordinate_component=coordinate_component,
packing="coordinates" if pack_coordinates else "single",
)
def _with_selection(
self, selection: _TorchStructuredSelection
) -> "TorchStructuredDerivativeView":
"""Clone this view while replacing only its typed selection state."""
view = type(self)(self._owner, self._name, self._views, self._labels)
view._selection = selection
return view
def with_component(
self, component: Literal["real", "imag"]
) -> "TorchStructuredDerivativeView":
"""Return a view selecting one output component."""
return self._with_selection(
replace(self._selection, output_component=component)
)
def with_coordinate_component(
self, component: Literal["real", "imag"]
) -> "TorchStructuredDerivativeView":
"""Select one second-input coordinate while preserving first-coordinate packing."""
return self._with_selection(
replace(self._selection, coordinate_component=component)
)
@property
def derivatives(self) -> TorchStructuredDerivativeCollection:
"""Return nested derivative selection for this view."""
if self._selection.order == 2:
raise RuntimeError(
"Third-order structured solver derivatives are unavailable."
)
collections: tuple[object, ...] = tuple(
getattr(view, "derivatives") for view in self._views
)
return TorchStructuredDerivativeCollection(
self._owner,
collections,
output_component=self._selection.output_component,
inspection_only=False,
)
def to_dict(self) -> Mapping[object, object]:
"""Export selected numeric leaves as Torch tensors."""
selection: _TorchStructuredSelection = self._selection
connected: bool = selection.order == 1
mappings: list[Mapping[object, object]] = [
cast(
Mapping[object, object],
convert_mapping(
getattr(view, "to_dict")(),
bindings={},
inputs=(),
torch_module=self._owner._torch,
),
)
for view in self._views
]
base_mapping: Mapping[object, object] = cast(
Mapping[object, object], getattr(self._views[0], "to_dict")()
)
if selection.packing == "coordinates":
output_component: Literal["real", "imag"] = (
selection.output_component or "real"
)
if selection.coordinate_component is not None:
if len(mappings) != 4:
raise ValueError(
"Nested structured derivative coordinates are incomplete."
)
selected_column: int = (
0 if selection.coordinate_component == "real" else 1
)
first_direction_index: int = selected_column
second_direction_index: int = selected_column + 2
mapping = _pack_structured_components(
base_mapping,
mappings[first_direction_index],
mappings[second_direction_index],
output_component,
self._owner._torch,
)
elif len(mappings) == 2:
mapping = _pack_structured_components(
base_mapping,
mappings[0],
mappings[1],
output_component,
self._owner._torch,
)
else:
raise ValueError(
"Structured derivative coordinate packing is incomplete."
)
elif selection.output_component is not None:
mapping = _project_structured_component(
base_mapping,
mappings[0],
selection.output_component,
self._owner._torch,
)
else:
mapping = mappings[0]
if not isinstance(mapping, Mapping):
return {}
sensitivity_directions: Mapping[str, object] = (
self._sensitivity_directions(base_mapping) if connected else {}
)
numeric_mapping: Mapping[object, object] = _without_structured_root_metadata(
mapping
)
metadata_mapping: Mapping[object, object] = {
key: value
for key, value in mapping.items()
if _is_structured_metadata_key(key, root=True)
}
numeric_directions: Mapping[str, object] = {
label: (
_without_structured_root_metadata(direction)
if isinstance(direction, Mapping)
else direction
)
for label, direction in sensitivity_directions.items()
}
selected_numeric: Mapping[object, object] = cast(
Mapping[object, object],
convert_mapping(
numeric_mapping,
bindings=self._owner._bindings if connected else {},
inputs=self._owner._inputs if connected else (),
torch_module=self._owner._torch,
derivative_mapping=numeric_directions if connected else None,
),
)
selected_metadata: Mapping[object, object] = cast(
Mapping[object, object],
convert_mapping(
metadata_mapping,
bindings={},
inputs=(),
torch_module=self._owner._torch,
),
)
selected: dict[object, object] = dict(selected_numeric)
selected.update(selected_metadata)
return selected
def _sensitivity_directions(
self, base_mapping: Mapping[object, object]
) -> Mapping[str, object]:
"""Return the selected sensitivity's second-order data by input label."""
selection: _TorchStructuredSelection = self._selection
pairs: Mapping[str, Mapping[str, object]] = (
self._owner._structured_second_derivatives()
)
directions: dict[str, object] = {}
bound_labels: tuple[str, ...] = coordinate_labels(self._owner._bindings)
for label in bound_labels:
coordinate_maps: list[Mapping[object, object]] = []
for first in self._labels:
branch: object = pairs.get(first, {}).get(label)
if isinstance(branch, Mapping):
coordinate_maps.append(
cast(
Mapping[object, object],
convert_mapping(
branch,
bindings={},
inputs=(),
torch_module=self._owner._torch,
),
)
)
if not coordinate_maps:
continue
if selection.packing == "coordinates":
if len(coordinate_maps) != 2:
directions[label] = {}
continue
output_component: Literal["real", "imag"] = (
selection.output_component or "real"
)
directions[label] = _pack_structured_components(
base_mapping,
coordinate_maps[0],
coordinate_maps[1],
output_component,
self._owner._torch,
)
elif selection.output_component is not None:
directions[label] = _project_structured_component(
base_mapping,
coordinate_maps[0],
selection.output_component,
self._owner._torch,
)
else:
directions[label] = coordinate_maps[0]
return directions
class _TableOrder(IntEnum):
"""Derivative selection order, matching the public depth convention."""
ROOT = 0
FIRST = 1
SECOND = 2
@dataclass(frozen=True, slots=True)
class _TableSelection:
"""Selection mode for a table derivative, separate from payload data."""
order: _TableOrder
output_component: Literal["real", "imag"] | None = None
input_coordinate: Literal["real", "imag"] | None = None
class TorchTableDerivativeCollection:
"""Select table derivatives through bound Project Key names."""
def __init__(
self,
owner: TorchPostprocessRecord,
ordinary: object,
*,
depth: int,
component: Literal["real", "imag"] | None = None,
companion: object | None = None,
) -> None:
self._owner: TorchPostprocessRecord = owner
self._ordinary: object = ordinary
self._selection: _TableSelection = _TableSelection(
_TableOrder(min(depth, 2)), component
)
self._companion: object | None = companion
def keys(self) -> tuple[str, ...]:
"""Return the bound Project Keys available at this derivative order."""
if self._selection.order == _TableOrder.SECOND:
return ()
available: object = getattr(self._ordinary, "keys")()
solver_names: set[str] = set(cast(tuple[str, ...], available))
return tuple(
key
for key, binding in self._owner._bindings.items()
if any(label in solver_names for label in (binding_labels(binding)))
)
def __getitem__(self, project_key: str) -> "TorchTableDerivativeView":
"""Select one first- or second-order derivative by Project Key."""
if self._selection.order == _TableOrder.SECOND:
raise RuntimeError("Third-order table derivatives are unavailable.")
try:
binding: DerivativeBinding = self._owner._bindings[project_key]
except KeyError:
raise KeyError(project_key) from None
labels: tuple[str, ...] = binding_labels(binding)
available: set[str] = set(
cast(tuple[str, ...], getattr(self._ordinary, "keys")())
)
selected_label: str | None = next(
(label for label in labels if label in available), None
)
if selected_label is None:
raise KeyError(f"derivatives[{project_key!r}]")
selected: object = self._ordinary[selected_label] # type: ignore[index]
companion: object | None = None
coordinate_matrix: tuple[object, object, object, object] | None = None
if isinstance(binding, ComplexDerivative):
companion_label: str = next(
(
label
for label in labels
if label != selected_label and label in available
),
"",
)
if not companion_label:
raise ValueError(
f"Complex table-collection derivative {project_key!r} is incomplete."
)
companion = self._ordinary[companion_label] # type: ignore[index]
if (
self._selection.order != _TableOrder.ROOT
and self._companion is not None
):
other_available: set[str] = set(
cast(tuple[str, ...], getattr(self._companion, "keys")())
)
if not set(labels).issubset(other_available):
raise ValueError(
f"Complex table-collection derivative {project_key!r} "
"has incomplete mixed-coordinate pairs."
)
coordinate_matrix = tuple(
cast(object, collection[label]) # type: ignore[index]
for collection in (self._ordinary, self._companion)
for label in labels
) # type: ignore[assignment]
return TorchTableDerivativeView(
self._owner,
selected,
project_key=project_key,
solver_label=selected_label,
depth=min(int(self._selection.order) + 1, 2),
component=self._selection.output_component,
binding=binding,
companion=companion,
coordinate_matrix=coordinate_matrix,
)
class TorchTableDerivativeView:
"""Export a selected table sensitivity as Torch tensors."""
def __init__(
self,
owner: TorchPostprocessRecord,
ordinary: object,
*,
project_key: str,
solver_label: str,
depth: int,
component: Literal["real", "imag"] | None = None,
binding: DerivativeBinding | None = None,
companion: object | None = None,
coordinate_matrix: tuple[object, object, object, object] | None = None,
nested_coordinate: Literal["real", "imag"] | None = None,
) -> None:
self._owner: TorchPostprocessRecord = owner
self._ordinary: object = ordinary
self._project_key: str = project_key
self._solver_label: str = solver_label
self._selection: _TableSelection = _TableSelection(
_TableOrder(min(depth, 2)), component, nested_coordinate
)
self._binding: DerivativeBinding | None = binding
self._companion: object | None = companion
self._coordinate_matrix = coordinate_matrix
@property
def real(self) -> "TorchTableDerivativeView":
"""Select the real output component before dictionary export.
For a nested complex-input derivative, select the second input's real
coordinate instead. The first input's two coordinates remain packed
in each complex value.
"""
return self._component_view("real")
@property
def imag(self) -> "TorchTableDerivativeView":
"""Select the imaginary output component before dictionary export.
For a nested complex-input derivative, select the second input's imaginary
coordinate instead. The first input's two coordinates remain packed
in each complex value.
"""
return self._component_view("imag")
def _component_view(
self, component: Literal["real", "imag"]
) -> "TorchTableDerivativeView":
nested_coordinate: Literal["real", "imag"] | None = None
selected_component: Literal["real", "imag"] = component
depth: _TableOrder = self._selection.order
if depth > 1 and self._coordinate_matrix is not None:
nested_coordinate = component
selected_component = cast(
Literal["real", "imag"], self._selection.output_component
)
return TorchTableDerivativeView(
self._owner,
self._ordinary,
project_key=self._project_key,
solver_label=self._solver_label,
depth=depth,
component=selected_component,
binding=self._binding,
companion=self._companion,
coordinate_matrix=self._coordinate_matrix,
nested_coordinate=nested_coordinate,
)
@property
def derivatives(self) -> TorchTableDerivativeCollection:
ordinary_collection: object = getattr(self._ordinary, "derivatives")
companion_collection: object | None = (
getattr(self._companion, "derivatives")
if self._companion is not None
else None
)
return TorchTableDerivativeCollection(
self._owner,
ordinary_collection,
depth=self._selection.order,
component=self._selection.output_component,
companion=companion_collection,
)
def to_dict(self) -> Mapping[object, object]:
"""Return the selected table with dictionary-only Torch exports."""
ordinary_values: object = getattr(self._ordinary, "to_dict")()
if not isinstance(ordinary_values, Mapping):
raise TypeError("A selected table derivative must export a mapping.")
if (
_contains_complex_numeric(ordinary_values)
and self._selection.output_component is None
):
raise ValueError(
"Select a complex table derivative output component with .real or .imag before export."
)
if self._selection.order == _TableOrder.SECOND:
if self._coordinate_matrix is not None:
pair_mappings: tuple[Mapping[object, object], ...] = tuple(
cast(Mapping[object, object], getattr(view, "to_dict")())
for view in self._coordinate_matrix
)
if self._selection.input_coordinate is None:
raise ValueError(
"Select the real or imaginary complex-input coordinate "
"before exporting a nested table Hessian."
)
column_offset: int = (
0 if self._selection.input_coordinate == "real" else 1
)
packed: Mapping[object, object] = _combine_table_directions(
pair_mappings[column_offset],
pair_mappings[column_offset + 2],
self._selection.output_component,
path=f"derivatives[{self._project_key!r}]",
)
return cast(
Mapping[object, object],
convert_mapping(
packed,
bindings={},
inputs=(),
torch_module=self._owner._torch,
),
)
if self._companion is not None:
companion_values: object = getattr(self._companion, "to_dict")()
if not isinstance(companion_values, Mapping):
raise TypeError(
"A complex collection derivative must export a mapping."
)
ordinary_values = _combine_table_directions(
ordinary_values,
companion_values,
self._selection.output_component,
path=f"derivatives[{self._project_key!r}]",
)
converted: Mapping[object, object] = cast(
Mapping[object, object],
convert_mapping(
ordinary_values,
bindings={},
inputs=(),
torch_module=self._owner._torch,
),
)
return _select_torch_component(
converted,
(
None
if self._companion is not None
else self._selection.output_component
),
self._owner._torch,
)
payload: object = getattr(self._owner._record, "payload", None)
if isinstance(payload, TableCollectionPayload):
return self._collection_sensitivity_to_dict(
cast(Mapping[object, object], ordinary_values)
)
labels: tuple[str, ...] = coordinate_labels(self._owner._bindings)
selected_pairs: Mapping[str, Mapping[str, object]] = (
self._owner._table_second_derivatives()
)
pair_data: dict[str, object] = {}
pair_presence: dict[str, dict[str, object]] = {
first_label: dict(second_pairs)
for first_label, second_pairs in selected_pairs.items()
}
unavailable_pairs: tuple[tuple[str, str], ...] = missing_pairs(
labels, pair_presence
)
if pair_presence and unavailable_pairs:
formatted_missing: list[str] = [
f"{first_label!r},{second_label!r}"
for first_label, second_label in unavailable_pairs
]
raise ValueError(
f"Incomplete table sensitivity pairs for Project Key "
f"{self._project_key!r}: missing {formatted_missing!r}."
)
base_values: Mapping[object, object] = cast(
Mapping[object, object], ordinary_values
)
complex_binding: bool = isinstance(self._binding, ComplexDerivative)
if complex_binding:
assert isinstance(self._binding, ComplexDerivative)
table_payload: TablePayload = cast(
TablePayload, getattr(self._owner._record, "payload")
)
companion: object = table_payload.derivatives[
(
self._binding.imaginary
if self._solver_label == self._binding.real
else self._binding.real
)
]
companion_table_values: object = getattr(companion, "to_dict")()
if not isinstance(companion_table_values, Mapping):
raise TypeError("A complex table derivative must export a mapping.")
base_values = _combine_table_directions(
ordinary_values,
cast(Mapping[object, object], companion_table_values),
self._selection.output_component,
path=f"derivatives[{self._project_key!r}]",
)
selected_row: Mapping[str, object] = selected_pairs.get(self._solver_label, {})
if complex_binding:
assert isinstance(self._binding, ComplexDerivative)
companion_label: str = (
self._binding.imaginary
if self._solver_label == self._binding.real
else self._binding.real
)
companion_row: Mapping[str, object] = selected_pairs.get(
companion_label, {}
)
else:
companion_row = {}
for label, second_pair_record in selected_row.items():
if complex_binding:
second_pair: object = companion_row.get(label)
if not isinstance(second_pair, Mapping):
continue
pair_data[label] = _combine_table_directions(
cast(Mapping[object, object], second_pair_record),
second_pair,
self._selection.output_component,
path=(
f"derivatives[{self._project_key!r}]" f".derivatives[{label!r}]"
),
)
else:
pair_data[label] = second_pair_record
converted = cast(
Mapping[object, object],
convert_mapping(
base_values,
bindings=self._owner._bindings if pair_data else {},
inputs=self._owner._inputs if pair_data else (),
torch_module=self._owner._torch,
derivative_mapping=pair_data or None,
third_order_boundary=bool(pair_data),
),
)
return _select_torch_component(
converted,
None if complex_binding else self._selection.output_component,
self._owner._torch,
)
def _collection_sensitivity_to_dict(
self, ordinary_values: Mapping[object, object]
) -> Mapping[object, object]:
"""Connect selected member sensitivities using only their own pair data."""
labels: tuple[str, ...] = coordinate_labels(self._owner._bindings)
pairs: dict[str, object] = {}
derivative_collection: TableCollectionDerivativeCollection = cast(
TableCollectionDerivativeView, self._ordinary
).derivatives
for label in labels:
try:
pair_view: TableCollectionDerivativeView = derivative_collection[label]
except KeyError:
continue
pairs[label] = pair_view.to_dict()
binding: DerivativeBinding | None = self._binding
base_values: Mapping[object, object] = ordinary_values
if isinstance(binding, ComplexDerivative):
companion_label: str = (
binding.imaginary
if self._solver_label == binding.real
else binding.real
)
try:
companion_collection: TableCollectionPayload = cast(
TableCollectionPayload,
getattr(self._owner._record, "payload"),
)
companion_view: TableCollectionDerivativeView = (
companion_collection.derivatives[companion_label]
)
companion_values: object = companion_view.to_dict()
except KeyError:
raise ValueError(
f"Complex table-collection sensitivity {companion_label!r} is unavailable."
) from None
if not isinstance(companion_values, Mapping):
raise TypeError(
"A complex collection derivative must export a mapping."
)
companion_pairs: dict[str, object] = {}
companion_derivatives: TableCollectionDerivativeCollection = (
companion_view.derivatives
)
for label in labels:
try:
companion_pair: TableCollectionDerivativeView = (
companion_derivatives[label]
)
except KeyError:
continue
companion_pairs[label] = companion_pair.to_dict()
packed_pairs: dict[str, object] = {}
for label, pair_values in pairs.items():
companion_pair_values = companion_pairs.get(label)
if not isinstance(companion_pair_values, Mapping):
continue
packed_pairs[label] = _combine_table_directions(
cast(Mapping[object, object], pair_values),
companion_pair_values,
self._selection.output_component,
path=(
f"derivatives[{self._project_key!r}]" f".derivatives[{label!r}]"
),
)
pairs = packed_pairs
base_values = _combine_table_directions(
ordinary_values,
companion_values,
self._selection.output_component,
path=f"derivatives[{self._project_key!r}]",
)
if pairs:
for member in ordinary_values:
available_for_member: set[str] = {
label
for label, values in pairs.items()
if isinstance(values, Mapping) and member in values
}
if available_for_member and available_for_member != set(labels):
raise ValueError(
"Incomplete table-collection sensitivity pairs for member "
f"{member!r}: missing "
f"{sorted(set(labels) - available_for_member)!r}."
)
converted: Mapping[object, object] = cast(
Mapping[object, object],
convert_mapping(
base_values,
bindings=self._owner._bindings if pairs else {},
inputs=self._owner._inputs if pairs else (),
torch_module=self._owner._torch,
derivative_mapping=pairs if pairs else None,
third_order_boundary=bool(pairs),
),
)
return _select_torch_component(
converted,
(
None
if isinstance(binding, ComplexDerivative)
else self._selection.output_component
),
self._owner._torch,
)
def to_df(self, orient: str | None = None) -> object:
"""Reject DataFrame export for Torch derivative views."""
raise UnsupportedExportError(
"to_df is not supported for Torch-bound derivatives; use untorch()."
)
def to_xarray(self) -> object:
"""Reject xarray export for Torch derivative views."""
raise UnsupportedExportError(
"to_xarray is not supported for Torch-bound derivatives; use untorch()."
)
def _contains_complex_numeric(value: object) -> bool:
if isinstance(value, Mapping):
return any(_contains_complex_numeric(item) for item in value.values())
if isinstance(value, (list, tuple)):
return any(_contains_complex_numeric(item) for item in value)
if isinstance(value, complex):
return True
if isinstance(value, np.ndarray):
return bool(value.dtype.kind == "c")
return False
def _combine_table_directions(
first: Mapping[object, object],
second: Mapping[object, object],
component: Literal["real", "imag"] | None,
*,
path: str,
) -> Mapping[object, object]:
"""Pack two real-coordinate table directions into a complex tensor map."""
combined: dict[object, object] = {}
for key, left in first.items():
right: object = second.get(key)
if key in {"header", "title", "cost", "costs", "metadata"}:
combined[key] = left
elif isinstance(left, Mapping) and isinstance(right, Mapping):
combined[key] = _combine_table_directions(
left, right, component, path=f"{path}.{key}"
)
elif isinstance(left, np.ndarray) and isinstance(right, np.ndarray):
if left.shape != right.shape:
raise ValueError(
f"Incompatible table sensitivity shapes at {path}.{key}: "
f"{left.shape!r} and {right.shape!r}."
)
combined[key] = _pack_numeric_directions(left, right, component, np)
elif isinstance(left, (int, float, complex, np.number)) and isinstance(
right, (int, float, complex, np.number)
):
combined[key] = _pack_numeric_directions(
complex(left), complex(right), component, np
)
elif key not in second:
raise ValueError(f"Missing table sensitivity quantity at {path}.{key}.")
else:
combined[key] = left
return combined
def _select_torch_component(
value: Mapping[object, object],
component: Literal["real", "imag"] | None,
torch_module: object,
) -> Mapping[object, object]:
if component is None:
return value
selected: dict[object, object] = {}
for key, item in value.items():
if isinstance(item, Mapping):
selected[key] = _select_torch_component(item, component, torch_module)
elif isinstance(item, (list, tuple)):
selected[key] = type(item)(
(
_project_numeric_component(entry, component, torch_module, "zero")
if is_tensor(entry, torch_module)
else entry
)
for entry in item
)
elif is_tensor(item, torch_module):
selected[key] = _project_numeric_component(
item, component, torch_module, "zero"
)
else:
selected[key] = item
return selected
[docs]
class TorchBatchPostprocessRecord(_TorchRecordData):
"""Wrap one postprocess stream across a batch.
The ordinary :class:`jcmsuite.results.BatchPostprocessRecord` defines its
batch navigation and export structure. This wrapper adds the Torch
semantics of :class:`TorchPostprocessRecord` to each available entry,
including tensor conversion and entry-specific autograd connections.
The collection returns this class. Do not construct it directly.
"""
def __init__(
self,
record: object,
bindings: BindingContext,
inputs: InputContext,
torch_module: object,
) -> None:
super().__init__(record, {}, (), torch_module)
self._batch_bindings = bindings
self._batch_inputs = inputs
[docs]
def to_dict(self) -> Mapping[object, object]:
"""Return one Torch-aware postprocess mapping per available batch entry.
The outer mapping uses original batch indices. Each value follows the
single-result :meth:`TorchPostprocessRecord.to_dict` contract. Numeric
values with solver derivatives connect to that entry's input tensors.
Returns
-------
Mapping[object, object]
Available postprocess mappings keyed by original batch index.
"""
converted: dict[object, object] = {}
records: object = getattr(self._record, "records")
for batch_record in cast(Sequence[object], records):
postprocesses: object = getattr(batch_record, "payload", None)
index: int = cast(int, getattr(batch_record, "index"))
postprocess_index: int = cast(int, getattr(self._record, "index"))
if postprocesses is None or postprocess_index >= len(
cast(Sequence[object], postprocesses)
):
continue
selected: object = cast(Sequence[object], postprocesses)[postprocess_index]
if not getattr(selected, "available", True):
continue
bindings: BindingMap = _context_binding(self._batch_bindings, index)
inputs: tuple[TorchTensor, ...] = _context_inputs(self._batch_inputs, index)
converted[index] = TorchPostprocessRecord(
selected, bindings, inputs, self._torch
).to_dict()
return converted
@property
def fields(self) -> "TorchBatchFieldExportPayload":
"""Return the aggregate field view with per-entry Torch contexts.
Returns
-------
TorchBatchFieldExportPayload
Batch field navigation and Torch-aware dictionary export.
"""
return TorchBatchFieldExportPayload(
getattr(self._record, "fields"),
self._batch_bindings,
self._batch_inputs,
self._torch,
)
[docs]
class TorchBatchFieldExportPayload:
"""Provide Torch-aware dictionary exports for fields across a batch.
The ordinary :class:`jcmsuite.results.BatchFieldExportPayload` defines the
batch navigation and export structure. This wrapper adds the Torch field
semantics of :class:`TorchFieldExportPayload` to each available entry.
Operations retain original batch indices. The ``to_dict()`` method returns
one mapping per available entry and converts numeric values to Torch
tensors. Solver derivatives connect each tensor to its matching input.
The ``derivatives`` property returns a Torch-specific lookup keyed by bound
project key name. Each derivative export uses that entry's derivative
bindings and remains keyed by original batch index. The collection is empty
when no differentiable inputs are bound.
A Torch batch postprocess record returns this class. Do not construct it
directly.
"""
def __init__(
self,
payload: object,
bindings: BindingContext,
inputs: InputContext,
torch_module: object,
transforms: tuple[_TransformName, ...] = (),
) -> None:
self._payload = payload
self._bindings = bindings
self._inputs = inputs
self._torch = torch_module
self._transforms = transforms
def __getattr__(self, name: str) -> object:
return getattr(self._payload, name)
[docs]
def to_dict(self) -> Mapping[int, Mapping[object, object]]:
"""Return field mappings keyed by original batch index.
Each available entry is converted by the single-result field wrapper.
Numeric field values are Torch tensors. When solver derivatives are
available, each field tensor connects to the matching entry's input
tensors. Field transforms apply the same derivative rules as the
single-result Torch field wrapper.
Returns
-------
Mapping[int, Mapping[object, object]]
Available field mappings keyed by original batch index.
"""
converted: dict[int, Mapping[object, object]] = {}
for record in cast(Sequence[object], getattr(self._payload, "records")):
payload: object = getattr(record, "payload", None)
if payload is None:
continue
index: int = cast(int, getattr(record, "index"))
field: TorchFieldExportPayload = TorchFieldExportPayload(
payload,
_context_binding(self._bindings, index),
_context_inputs(self._inputs, index),
self._torch,
)
for operation in self._transforms:
field = (
cast(TorchFieldExportPayload, field.intensity)
if operation == "intensity"
else field.transform(operation)
)
converted[index] = field.to_dict()
return converted
[docs]
def to_df(self, orient: str | None = None) -> object:
"""Raise because Torch-bound batch fields do not support DataFrame export.
Parameters
----------
orient : str | None, optional
DataFrame orientation. The value does not change the error.
Returns
-------
object
This method does not return.
Raises
------
UnsupportedExportError
Always. Use the underlying ordinary batch result for DataFrame export.
"""
raise UnsupportedExportError(
"to_df is not supported for Torch-bound results; use untorch() for ordinary DataFrame exports."
)
[docs]
def to_xarray(self) -> object:
"""Raise because Torch-bound batch fields do not support xarray export.
Returns
-------
object
This method does not return.
Raises
------
UnsupportedExportError
Always. Use the underlying ordinary batch result for xarray export.
"""
raise UnsupportedExportError(
"to_xarray is not supported for Torch-bound results."
)
def _view(self, name: str, *args: object) -> "TorchBatchFieldExportPayload":
operation: Callable[..., object] = cast(
Callable[..., object], getattr(self._payload, name)
)
return TorchBatchFieldExportPayload(
operation(*args),
self._bindings,
self._inputs,
self._torch,
self._transforms,
)
@property
def base(self) -> "TorchBatchFieldExportPayload":
"""Return the batch field view without solver derivative branches.
Returns
-------
TorchBatchFieldExportPayload
Base fields for all available batch entries.
"""
return TorchBatchFieldExportPayload(
getattr(self._payload, "base"),
self._bindings,
self._inputs,
self._torch,
self._transforms,
)
@property
def intensity(self) -> "TorchBatchIntensityFieldExportPayload":
"""Return the squared-norm intensity view for the batch.
Returns
-------
TorchBatchIntensityFieldExportPayload
Non-transformable intensity fields for all available batch entries.
"""
if "intensity" in self._transforms:
raise AttributeError(
"TorchBatchFieldExportPayload does not support intensity()."
)
return TorchBatchIntensityFieldExportPayload(
TorchBatchFieldExportPayload(
self._payload,
self._bindings,
self._inputs,
self._torch,
(*self._transforms, "intensity"),
)
)
@property
def derivatives(self) -> "TorchBatchFieldDerivativeCollection":
"""Return binding-aware solver derivative lookup across the batch.
Returns
-------
TorchBatchFieldDerivativeCollection
Derivative lookup by differentiable project key name. A lookup
returns detached Torch derivative mappings keyed by original batch
index. The collection is empty when no differentiable inputs are
bound.
"""
return TorchBatchFieldDerivativeCollection(self)
[docs]
def select(self, index: int | None = None) -> "TorchBatchFieldExportPayload":
"""Select a field position across available batch entries.
Parameters
----------
index : int | None, optional
Field position. ``None`` selects all field positions.
Returns
-------
TorchBatchFieldExportPayload
Selected fields with original batch indices.
"""
return self._view("select", index)
[docs]
def __getitem__(self, key: object) -> "TorchBatchFieldExportPayload":
"""Select a named field quantity across the batch.
Parameters
----------
key : object
Field quantity name or nested mapping key.
Returns
-------
TorchBatchFieldExportPayload
Selected fields with original batch indices.
"""
return TorchBatchFieldExportPayload(
self._payload[key], # type: ignore[index]
self._bindings,
self._inputs,
self._torch,
self._transforms,
)
[docs]
class TorchBatchIntensityFieldExportPayload:
"""Provide a non-transformable Torch intensity view across a batch.
This wrapper mirrors :class:`TorchIntensityFieldExportPayload` over the
ordinary :class:`jcmsuite.results.BatchIntensityFieldExportPayload`.
Dictionary exports retain original batch indices and connect each entry to
its matching input when solver derivatives are available.
:attr:`TorchBatchFieldExportPayload.intensity` returns this class. Do not
construct it directly.
"""
def __init__(self, view: TorchBatchFieldExportPayload) -> None:
self._view = view
def __getattr__(self, name: str) -> object:
if name in {"intensity", "transform"}:
raise AttributeError(f"{type(self).__name__!s} does not support {name}().")
return getattr(self._view, name)
@property
def base(self) -> "TorchBatchIntensityFieldExportPayload":
"""Return the intensity view without solver derivative branches.
Returns
-------
TorchBatchIntensityFieldExportPayload
Base intensity fields for available batch entries.
"""
return TorchBatchIntensityFieldExportPayload(self._view.base)
@property
def derivatives(self) -> "TorchBatchFieldDerivativeCollection":
"""Return binding-aware derivatives for the batch intensity.
Returns
-------
TorchBatchFieldDerivativeCollection
Derivative lookup keyed by differentiable project key name. Each
payload retains original batch indices.
"""
return self._view.derivatives
[docs]
def select(
self, index: int | None = None
) -> "TorchBatchIntensityFieldExportPayload":
"""Select field positions across the batch.
Parameters
----------
index : int | None, optional
Field position. ``None`` selects all positions.
Returns
-------
TorchBatchIntensityFieldExportPayload
Selected intensity fields with original batch indices.
"""
return TorchBatchIntensityFieldExportPayload(self._view.select(index))
[docs]
def to_dict(self) -> Mapping[int, Mapping[object, object]]:
"""Return Torch intensity dictionaries keyed by original batch index.
Returns
-------
Mapping[int, Mapping[object, object]]
Available intensity mappings. Solver derivatives connect each
intensity tensor to its matching input tensor.
"""
return self._view.to_dict()
[docs]
def __getitem__(self, key: object) -> "TorchBatchIntensityFieldExportPayload":
"""Select a named intensity field quantity across the batch.
Parameters
----------
key : object
Field quantity name or nested mapping key.
Returns
-------
TorchBatchIntensityFieldExportPayload
Selected intensity fields with original batch indices.
"""
return TorchBatchIntensityFieldExportPayload(self._view[key])
[docs]
def to_df(self, orient: str | None = None) -> object:
"""Raise because Torch intensity fields do not support DataFrame export.
Parameters
----------
orient : str | None, optional
DataFrame orientation. The value does not change the error.
Returns
-------
object
This method does not return.
Raises
------
UnsupportedExportError
Always. Use the ordinary batch result for DataFrame export.
"""
return self._view.to_df(orient=orient)
[docs]
def to_xarray(self) -> object:
"""Raise because Torch intensity fields do not support xarray export.
Returns
-------
object
This method does not return.
Raises
------
UnsupportedExportError
Always. Use the ordinary batch result for xarray export.
"""
return self._view.to_xarray()
def _context_binding(context: BindingContext, index: int) -> BindingMap:
return context[index] if isinstance(context, tuple) else context
def _context_inputs(context: InputContext, index: int) -> tuple[TorchTensor, ...]:
return (
cast(tuple[tuple[TorchTensor, ...], ...], context)[index]
if context and isinstance(context[0], tuple)
else context
)
class _TorchFieldView(_TorchRecordData):
"""Provide shared selection and derivative navigation for Torch field views."""
def _view(
self,
record: object,
*,
transforms: tuple[_TransformName, ...] | None = None,
) -> Self:
return type(self)(
record,
self._bindings,
self._inputs,
self._torch,
transforms=self._transforms if transforms is None else transforms,
)
@property
def base(self) -> Self:
"""Return the current field view without solver derivative branches.
Returns
-------
Self
New view with the current field selection and transforms, but
without solver derivative branches.
"""
return self._view(getattr(self._record, "base"))
@property
def derivatives(self) -> "TorchFieldDerivativeCollection":
"""Return field derivatives for bound project keys.
A lookup on the returned collection gives a
:class:`TorchFieldDerivativePayload` for a real input or a
:class:`TorchComplexFieldDerivativePayload` for a complex input. The
collection is empty when no differentiable inputs are bound.
Returns
-------
TorchFieldDerivativeCollection
Torch-specific derivative lookup keyed by differentiable project key.
"""
return TorchFieldDerivativeCollection(self)
def select(self, index: int | None = None) -> Self:
"""Select field positions while retaining this view's operations.
Parameters
----------
index : int | None, optional
Field position. ``None`` selects all field positions.
Returns
-------
Self
New view with the requested field selection.
"""
return self._view(getattr(self._record, "select")(index))
def __getitem__(self, key: object) -> Self:
"""Select a field quantity or nested mapping entry.
Parameters
----------
key : object
Field quantity name or nested mapping key.
Returns
-------
Self
New view for the selected field data.
"""
return self._view(self._record[key]) # type: ignore[index]
[docs]
class TorchFieldExportPayload(_TorchFieldView):
"""Provide Torch-aware views of ordinary field-export data.
The class mirrors :class:`jcmsuite.results.FieldExportPayload`. Its views
retain the current field selection and transformation chain. Derivative
lookup returns Torch derivative payloads for bound project keys. It returns
an empty collection when no differentiable inputs are bound.
"""
@property
def base(self) -> "TorchFieldExportPayload":
"""Return a base-only field payload.
Returns
-------
TorchFieldExportPayload
Field view without solver derivative branches.
"""
return super().base
@property
def derivatives(
self,
) -> "TorchFieldDerivativeCollection":
"""Return Torch-specific derivative lookup.
Returns
-------
TorchFieldDerivativeCollection
Derivative lookup keyed by differentiable project key name. The
collection is empty when no differentiable inputs are bound.
"""
return super().derivatives
[docs]
def select(self, index: int | None = None) -> "TorchFieldExportPayload":
"""Return a field payload with the requested field positions.
Parameters
----------
index : int | None, optional
Field position. ``None`` selects all field positions.
Returns
-------
TorchFieldExportPayload
New field payload with the requested selection.
"""
return super().select(index)
[docs]
def __getitem__(self, key: object) -> "TorchFieldExportPayload":
"""Return a field payload for a named or nested field value.
Parameters
----------
key : object
Field quantity name or nested mapping key.
Returns
-------
TorchFieldExportPayload
New field payload for the selected value.
"""
return super().__getitem__(key)
@property
def intensity(self) -> TorchIntensityFieldExportPayload:
"""Return a real-valued squared-norm intensity view.
Returns
-------
TorchIntensityFieldExportPayload
Non-transformable intensity view. Its field values retain Torch
connections to bound input tensors when solver derivatives exist.
"""
return TorchIntensityFieldExportPayload(
self._record,
self._bindings,
self._inputs,
self._torch,
transforms=(*self._transforms, "intensity"),
)
[docs]
class TorchIntensityFieldExportPayload(_TorchFieldView):
"""Export squared-norm intensity for a Torch field.
The view supports base-field access, derivative lookup, field selection, and
dictionary export. It does not support field transforms. Transform the field
before you request intensity.
"""
@property
def base(self) -> "TorchIntensityFieldExportPayload":
"""Return a base-only intensity payload.
Returns
-------
TorchIntensityFieldExportPayload
Intensity view without solver derivative branches.
"""
return super().base
@property
def derivatives(
self,
) -> "TorchFieldDerivativeCollection":
"""Return Torch-specific intensity-derivative lookup.
Returns
-------
TorchFieldDerivativeCollection
Derivative lookup keyed by differentiable project key name. The
collection is empty when no differentiable inputs are bound.
"""
return super().derivatives
[docs]
def select(self, index: int | None = None) -> "TorchIntensityFieldExportPayload":
"""Return an intensity payload with the requested field positions.
Parameters
----------
index : int | None, optional
Field position. ``None`` selects all field positions.
Returns
-------
TorchIntensityFieldExportPayload
New intensity payload with the requested selection.
"""
return super().select(index)
[docs]
def __getitem__(self, key: object) -> "TorchIntensityFieldExportPayload":
"""Return an intensity payload for a named or nested field value.
Parameters
----------
key : object
Field quantity name or nested mapping key.
Returns
-------
TorchIntensityFieldExportPayload
New intensity payload for the selected value.
"""
return super().__getitem__(key)
def __getattr__(self, name: str) -> object:
if name in {"intensity", "transform"}:
raise AttributeError(f"{type(self).__name__!s} does not support {name}().")
return super().__getattr__(name)
[docs]
class TorchFieldDerivativeCollection:
"""Look up solver field derivatives by differentiable project key name."""
def __init__(self, owner: _TorchFieldView) -> None:
self._owner = owner
[docs]
def __getitem__(
self, name: str
) -> TorchFieldDerivativePayload | TorchComplexFieldDerivativePayload:
"""Return the field derivative for one bound project key.
Parameters
----------
name : str
Differentiable project key name.
Returns
-------
TorchFieldDerivativePayload | TorchComplexFieldDerivativePayload
Detached field derivatives for the selected input.
Raises
------
KeyError
If ``name`` is not a bound differentiable input.
"""
if name not in self.keys():
raise KeyError(name)
binding = self._owner._bindings[name]
if isinstance(binding, RealDerivative):
derivative = self._owner._derivative_branch(RealDerivative(binding.label))
return TorchFieldDerivativePayload(
self._owner,
derivative,
input_name=name,
)
real_branch = self._owner._derivative_branch(RealDerivative(binding.real))
imaginary_branch = self._owner._derivative_branch(
RealDerivative(binding.imaginary)
)
base_value: object = _convert_numeric(
self._owner._base_mapping().get("field"), self._owner._torch
)
has_imaginary_output: bool = _is_complex_tensor(base_value, self._owner._torch)
return TorchComplexFieldDerivativePayload(
real=TorchFieldDerivativePayload(
self._owner,
real_branch,
input_name=name,
complex_direction=imaginary_branch,
),
imag=(
TorchFieldDerivativePayload(
self._owner,
real_branch,
input_name=name,
complex_direction=imaginary_branch,
output_component="imag",
)
if has_imaginary_output
else None
),
)
[docs]
def keys(self) -> tuple[str, ...]:
"""Return bound project key names in binding order.
Returns
-------
tuple[str, ...]
Names of gradient-bearing inputs with solver bindings.
"""
return tuple(
name
for name, input_value in zip(
self._owner._bindings, self._owner._inputs, strict=False
)
if getattr(input_value, "requires_grad", False)
)
[docs]
@dataclass(frozen=True, slots=True)
class TorchComplexFieldDerivativePayload:
"""Store packed sensitivities for one complex project key.
A complex project key has separate solver derivatives for its real and
imaginary input directions. The
:attr:`~jcmsuite.torch.results.TorchComplexFieldDerivativePayload.real` and
:attr:`~jcmsuite.torch.results.TorchComplexFieldDerivativePayload.imag` records
expose the corresponding packed gradients of the real and imaginary output
components. The ``imag`` record is ``None`` when the output field is not
complex.
Attributes
----------
real : TorchFieldDerivativePayload
Packed gradient of the real output component with respect to the complex
project key.
imag : TorchFieldDerivativePayload | None
Packed gradient of the imaginary output component, or ``None`` for a real
output field.
Notes
-----
The records contain detached Torch tensors. Use
:meth:`~jcmsuite.torch.results.TorchFieldDerivativePayload.to_dict` on each record to
access the field derivatives. The lookup name is the differentiable project key
name, not either solver derivative label.
"""
real: TorchFieldDerivativePayload
imag: TorchFieldDerivativePayload | None
def to_dict(self) -> Mapping[object, object]:
"""Reject export until the complex output component is selected.
Returns
-------
Mapping[object, object]
This method does not return; select ``real`` or ``imag`` first.
Raises
------
ValueError
Always, because a complex field derivative has two output components.
"""
raise ValueError(
"Select the 'real' or 'imag' output component before exporting "
"a complex field derivative."
)
[docs]
def select(self, index: int | None = None) -> "TorchComplexFieldDerivativePayload":
"""Select the same field position from both output components.
Parameters
----------
index : int | None, optional
Field position. ``None`` selects all field positions.
Returns
-------
TorchComplexFieldDerivativePayload
New complex derivative payload with both components selected.
"""
return type(self)(
real=self.real.select(index),
imag=None if self.imag is None else self.imag.select(index),
)
@dataclass(frozen=True, slots=True)
class _FieldSelection:
connection: Literal["sensitivity", "inspection"]
topology: Literal["pending", "applied"]
output_component: Literal["real", "imag"] | None
[docs]
class TorchFieldDerivativePayload:
"""Represent a solver field sensitivity or second-order inspection value.
Complete first-order real sensitivities can connect to bound inputs when
solver second-order pairs are available. Second-order inspection values are
detached. The payload supports nested derivative selection, field selection,
and dictionary export. It does not support field transforms because a
transform on derivative values does not compute a transformed-field
derivative.
"""
def __init__(
self,
owner: _TorchFieldView,
derivative: Mapping[object, object],
*,
input_name: str,
complex_direction: Mapping[object, object] | None = None,
output_component: Literal["real", "imag"] | None = None,
inspection_only: bool = False,
selection_applied: bool = False,
) -> None:
self._owner = owner
self._derivative = derivative
self._input_name = input_name
self._complex_direction = complex_direction
self._selection = _FieldSelection(
"inspection" if inspection_only else "sensitivity",
"applied" if selection_applied else "pending",
output_component,
)
[docs]
def select(self, index: int | None = None) -> "TorchFieldDerivativePayload":
"""Select one field entry from this derivative payload.
The derivative keeps the same project key and output-component meaning.
Parameters
----------
index : int | None, optional
Field position. ``None`` selects all field positions.
Returns
-------
TorchFieldDerivativePayload
New derivative payload with the requested field selection.
"""
owner: _TorchFieldView = self._owner.select(index)
return type(self)(
owner,
self._derivative,
input_name=self._input_name,
complex_direction=self._complex_direction,
output_component=self._selection.output_component,
inspection_only=self._selection.connection == "inspection",
selection_applied=self._selection.topology == "applied",
)
@property
def derivatives(self) -> "TorchNestedFieldDerivativeCollection":
"""Return nested field derivatives by bound project key name.
The collection selects second-order inspection values from a first-order
sensitivity. Selecting another derivative from a second-order value
raises because third-order solver derivatives are unavailable.
"""
return TorchNestedFieldDerivativeCollection(self)
def _mapping_for_selected_owner(
self, mapping: Mapping[object, object]
) -> Mapping[object, object]:
if self._selection.topology == "applied":
return mapping
selected_indices: tuple[int, ...] = tuple(
getattr(self._owner._record, "indices", ())
)
if len(selected_indices) != 1:
return mapping
selected_index: int = selected_indices[0]
nested_field: object = mapping.get("field")
coordinate_names: tuple[str, ...] = ("X", "Y", "Z", "R", "Theta", "Phi")
nested_coordinates: bool = isinstance(nested_field, Mapping) and any(
isinstance(key, str) and key.upper() in coordinate_names
for key in nested_field
)
has_coordinates: bool = any(
isinstance(key, str) and key.upper() in coordinate_names for key in mapping
)
if not nested_coordinates and not has_coordinates:
# Older derivative records can provide only the selected numeric
# field tensor, without repeating the base coordinate grid.
return mapping
field_mapping: Mapping[object, object] = (
cast(Mapping[object, object], nested_field)
if nested_coordinates
else mapping
)
# Solver derivative payloads can wrap the complete coordinate-bearing
# field mapping under an outer ``field`` key. Select inside that mapping
# so FieldExportPayload sees the coordinates at its expected root.
payload: FieldExportPayload = FieldExportPayload(field_mapping)
if selected_index not in payload.indices and len(payload.indices) == 1:
# The ordinary selected field view already projected this branch.
return mapping
selected_mapping: Mapping[object, object] = payload.select(
selected_index
).to_dict()
if not nested_coordinates:
return selected_mapping
result: dict[object, object] = dict(mapping)
result["field"] = selected_mapping
return result
[docs]
def to_dict(self) -> Mapping[object, object]:
"""Return the detached sensitivity field and its metadata.
Returns
-------
Mapping[object, object]
A mapping whose ``field`` value is a detached Torch tensor.
"""
base = self._owner._base_mapping()
derivative_mapping: Mapping[object, object] = self._mapping_for_selected_owner(
self._derivative
)
derivative = self._field_value(derivative_mapping)
if self._complex_direction is not None:
imaginary_mapping: Mapping[object, object] = (
self._mapping_for_selected_owner(self._complex_direction)
)
other = self._field_value(imaginary_mapping)
if self._owner._transforms and self._selection.connection != "inspection":
binding: DerivativeBinding | None = self._owner._bindings.get(
self._input_name
)
if binding is not None and isinstance(binding, ComplexDerivative):
derivative = self._connected_transformed_direction(
base, derivative_mapping, binding.real
)
other = self._connected_transformed_direction(
base, imaginary_mapping, binding.imaginary
)
if self._owner._transforms and self._selection.connection != "inspection":
derivative = _pack_numeric_directions(
derivative, other, None, self._owner._torch
)
else:
derivative = self._packed_gradient(base, derivative, other)
else:
if self._owner._transforms and self._selection.connection != "inspection":
binding = self._owner._bindings.get(self._input_name)
if isinstance(binding, RealDerivative):
derivative = self._connected_transformed_direction(
base, derivative_mapping, binding.label
)
else:
derivative = self._real_derivative(base, derivative)
else:
derivative = self._real_derivative(base, derivative)
result: dict[object, object] = {
key: value for key, value in base.items() if key not in {"field", "header"}
}
if (
self._selection.connection != "inspection"
and not self._owner._transforms
and isinstance(self._owner._record, FieldExportPayload)
):
sensitivity_binding: DerivativeBinding | None = self._owner._bindings.get(
self._input_name
)
labels: tuple[str, ...] = (
(sensitivity_binding.label,)
if isinstance(sensitivity_binding, RealDerivative)
else (
(sensitivity_binding.real, sensitivity_binding.imaginary)
if sensitivity_binding is not None
else ()
)
)
pairs: Mapping[str, Mapping[str, object]] = (
self._owner._field_second_derivatives()
)
has_second_order_data: bool = any(bool(row) for row in pairs.values())
if labels and has_second_order_data:
input_labels: tuple[str, ...] = coordinate_labels(self._owner._bindings)
unavailable: tuple[str, str] | None = missing_pair(
labels, pairs, input_labels
)
if unavailable is not None:
raise ValueError(
"Second-order solver data is incomplete for pair "
f"{unavailable[0]!r}, {unavailable[1]!r}, payload 'field'."
)
if self._complex_direction is None:
second_mapping: Mapping[str, object] = pairs[labels[0]]
else:
second_mapping = self._packed_sensitivity_derivatives(
labels, input_labels, pairs
)
derivative = connect_value(
derivative,
second_mapping,
self._owner._bindings,
self._owner._inputs,
self._owner._torch,
third_order_boundary=True,
)
result["field"] = (
derivative
if getattr(derivative, "requires_grad", False)
else _detach(derivative)
)
return result
def _connected_transformed_direction(
self,
base: Mapping[object, object],
derivative_mapping: Mapping[object, object],
direction_label: str,
) -> object:
"""Build a transformed sensitivity graph from solver first/second data."""
pair_map: Mapping[str, Mapping[str, object]] = (
self._owner._field_second_derivatives()
)
if not pair_map:
return self._real_derivative(base, self._field_value(derivative_mapping))
bound_labels: tuple[str, ...] = coordinate_labels(self._owner._bindings)
unavailable: tuple[str, str] | None = missing_pair(bound_labels, pair_map)
if unavailable is not None:
raise ValueError(
"Second-order solver data is incomplete for transformed sensitivity "
f"pair {unavailable[0]!r}, {unavailable[1]!r}, payload 'field'."
)
first_values: dict[str, object] = {}
for binding in self._owner._bindings.values():
labels: tuple[str, ...] = binding_labels(binding)
for label in labels:
branch: Mapping[object, object] = self._owner._derivative_branch(
RealDerivative(label)
)
selected_branch: Mapping[object, object] = (
self._mapping_for_selected_owner(branch)
)
first_values[label] = self._field_value(selected_branch)
base_value: object = self._field_value(base)
connected_base: object = connect_value(
base_value,
first_values,
self._owner._bindings,
self._owner._inputs,
self._owner._torch,
pair_map,
)
direction_value: object = self._field_value(derivative_mapping)
connected_direction: object = connect_value(
direction_value,
pair_map.get(direction_label, {}),
self._owner._bindings,
self._owner._inputs,
self._owner._torch,
third_order_boundary=True,
)
_, transformed_direction = _jvp(
connected_base,
connected_direction,
self._owner._transforms,
self._owner._torch,
grid_rank=self._grid_rank(base),
)
return _project_numeric_component(
transformed_direction, self._selection.output_component, self._owner._torch
)
def _packed_sensitivity_derivatives(
self,
direction_labels: tuple[str, ...],
input_labels: tuple[str, ...],
pairs: Mapping[str, Mapping[str, object]],
) -> Mapping[str, object]:
"""Pack second field pairs as gradients of this component sensitivity."""
if len(direction_labels) != 2:
raise ValueError("Complex sensitivity requires both coordinate labels.")
packed: dict[str, object] = {}
for input_label in input_labels:
components: list[object] = []
for direction in direction_labels:
raw_pair: object = pairs[direction][input_label]
if not isinstance(raw_pair, Mapping):
raise ValueError(
f"Second-order field pair {direction!r}, {input_label!r} "
"has no field mapping."
)
pair_value: object = self._field_value(raw_pair)
components.append(pair_value)
packed[input_label] = _pack_numeric_directions(
components[0],
components[1],
self._selection.output_component or "real",
self._owner._torch,
)
return packed
def to_xarray(self) -> object:
"""Raise because Torch derivative records support dictionary export only.
Returns
-------
object
This method does not return because Torch derivative records do not
support xarray export.
"""
raise UnsupportedExportError("Torch derivative records support to_dict() only.")
def _field_value(self, mapping: Mapping[object, object]) -> object:
value: object = mapping.get("field")
while isinstance(value, Mapping) and "field" in value:
value = value["field"]
converted: object = _convert_numeric(value, self._owner._torch)
if (
self._selection.topology == "applied"
and isinstance(self._owner._record, FieldExportPayload)
and len(self._owner._record.indices) == 1
):
indices: list[int] = list(self._owner._record.indices)
shape: Sequence[object] = cast(
Sequence[object], getattr(converted, "shape", ())
)
first_axis: int = cast(int, shape[0]) if shape else 0
if shape and max(indices) < first_axis:
return getattr(converted, "__getitem__")(indices)
return converted
def _real_derivative(
self, base: Mapping[object, object], derivative: object
) -> object:
value: object = _convert_numeric(base.get("field"), self._owner._torch)
derivative_value: object
_, derivative_value = _jvp(
value,
derivative,
self._owner._transforms,
self._owner._torch,
grid_rank=_field_grid_rank(base),
)
return _project_numeric_component(
derivative_value, self._selection.output_component, self._owner._torch
)
def _packed_gradient(
self, base: Mapping[object, object], real: object, imaginary: object
) -> object:
value: object = _convert_numeric(base.get("field"), self._owner._torch)
real_derivative: object
imaginary_derivative: object
_, real_derivative = _jvp(
value,
real,
self._owner._transforms,
self._owner._torch,
grid_rank=self._grid_rank(base),
)
_, imaginary_derivative = _jvp(
value,
imaginary,
self._owner._transforms,
self._owner._torch,
grid_rank=self._grid_rank(base),
)
return _pack_numeric_directions(
real_derivative,
imaginary_derivative,
self._selection.output_component or "real",
self._owner._torch,
)
@staticmethod
def _grid_rank(base: Mapping[object, object]) -> int:
return _field_grid_rank(base)
class TorchNestedFieldDerivativeCollection:
"""Select second-order field values by bound project key name."""
def __init__(self, owner: TorchFieldDerivativePayload) -> None:
self._owner = owner
def keys(self) -> tuple[str, ...]:
"""Return available second-order project-key names."""
if self._owner._selection.connection == "inspection" or not isinstance(
self._owner._owner._record, FieldExportPayload
):
return ()
binding: DerivativeBinding | None = self._owner._owner._bindings.get(
self._owner._input_name
)
if binding is None:
return ()
first_labels: tuple[str, ...] = binding_labels(binding)
pairs: Mapping[str, Mapping[str, object]] = (
self._owner._owner._field_second_derivatives()
)
return tuple(
name
for name, other in self._owner._owner._bindings.items()
if all(
label in pairs.get(first, {})
for first in first_labels
for label in binding_labels(other)
)
)
def __getitem__(
self, name: str
) -> TorchFieldDerivativePayload | TorchComplexFieldDerivativePayload:
"""Return a detached second-order field inspection payload."""
if self._owner._selection.connection == "inspection":
raise ValueError("Third-order field derivatives are not available.")
if name not in self.keys():
first: DerivativeBinding | None = self._owner._owner._bindings.get(
self._owner._input_name
)
second: DerivativeBinding | None = self._owner._owner._bindings.get(name)
first_label: str = (
first.label
if isinstance(first, RealDerivative)
else self._owner._input_name
)
second_label: str = (
second.label if isinstance(second, RealDerivative) else name
)
raise KeyError(
f"Second-order derivative pair {first_label!r}, {second_label!r} is unavailable."
)
bindings: BindingMap = self._owner._owner._bindings
first_binding: DerivativeBinding = bindings[self._owner._input_name]
second_binding: DerivativeBinding = bindings[name]
first_labels: tuple[str, ...] = (
(first_binding.label,)
if isinstance(first_binding, RealDerivative)
else (first_binding.real, first_binding.imaginary)
)
second_labels: tuple[str, ...] = (
(second_binding.label,)
if isinstance(second_binding, RealDerivative)
else (second_binding.real, second_binding.imaginary)
)
pairs: Mapping[str, Mapping[str, object]] = (
self._owner._owner._field_second_derivatives()
)
if isinstance(first_binding, RealDerivative) and isinstance(
second_binding, RealDerivative
):
record: object = self._owner._owner._record
if not isinstance(record, FieldExportPayload):
raise KeyError(name)
first_view: object = record.derivatives[first_binding.label]
second_collection: object = getattr(first_view, "derivatives")
pair_view: object = second_collection[second_binding.label] # type: ignore[index]
pair_mapping: Mapping[object, object] = cast(
Mapping[object, object], getattr(pair_view, "to_dict")()
)
return TorchFieldDerivativePayload(
self._owner._owner,
pair_mapping,
input_name=name,
inspection_only=True,
)
if len(first_labels) == 2:
packed_by_second: list[object] = []
for second_label in second_labels:
derivative_mapping: Mapping[str, object] = (
self._owner._packed_sensitivity_derivatives(
first_labels, (second_label,), pairs
)
)
packed_by_second.append(derivative_mapping[second_label])
if len(second_labels) == 2:
return TorchComplexFieldDerivativePayload(
real=self._inspection_value(name, packed_by_second[0]),
imag=self._inspection_value(name, packed_by_second[1]),
)
return self._inspection_value(name, packed_by_second[0])
selected_first_label: str = first_labels[0]
second_values: list[object] = []
for second_label in second_labels:
raw_pair: object = pairs[selected_first_label][second_label]
if not isinstance(raw_pair, Mapping):
raise ValueError(
f"Second-order field pair {selected_first_label!r}, {second_label!r} "
"has no field mapping."
)
pair_value: object = self._owner._field_value(raw_pair)
second_values.append(
_project_numeric_component(
pair_value,
self._owner._selection.output_component,
self._owner._owner._torch,
)
)
if len(second_values) == 2:
if self._owner._selection.output_component is None and _is_complex_tensor(
_convert_numeric(
self._owner._owner._base_mapping().get("field"),
self._owner._owner._torch,
),
self._owner._owner._torch,
):
real_values: object = _pack_numeric_directions(
second_values[0],
second_values[1],
"real",
self._owner._owner._torch,
)
imaginary_values: object = _pack_numeric_directions(
second_values[0],
second_values[1],
"imag",
self._owner._owner._torch,
)
return TorchComplexFieldDerivativePayload(
real=self._inspection_value(name, real_values),
imag=self._inspection_value(name, imaginary_values),
)
packed: object = _pack_numeric_directions(
second_values[0], second_values[1], None, self._owner._owner._torch
)
return self._inspection_value(name, packed)
return self._inspection_value(name, second_values[0])
def _inspection_value(
self, name: str, value: object
) -> TorchFieldDerivativePayload:
"""Wrap one detached nested field tensor without changing its packing."""
explicitly_selected: bool = (
isinstance(self._owner._owner._record, FieldExportPayload)
and self._owner._owner._record._selected_index is not None
)
if explicitly_selected:
value = getattr(value, "unsqueeze")(0)
return TorchFieldDerivativePayload(
self._owner._owner,
{"field": value},
input_name=name,
inspection_only=True,
selection_applied=not explicitly_selected,
)
[docs]
class TorchBatchFieldDerivativeCollection:
"""Look up solver field derivatives by bound project key across a batch.
This collection composes the lookup behavior of
:class:`TorchFieldDerivativeCollection` with the original-index alignment of
ordinary batch field payloads. Each lookup collects the corresponding
single-entry Torch derivative and retains only entries with available field
data and bindings.
A Torch batch field payload returns this collection. Do not construct it
directly.
"""
def __init__(self, owner: TorchBatchFieldExportPayload) -> None:
self._owner = owner
[docs]
def keys(self) -> tuple[str, ...]:
"""Return bound project key names available in the batch.
Returns
-------
tuple[str, ...]
Bound names in first-seen order across available batch field entries.
"""
names: list[str] = []
seen: set[str] = set()
for record in cast(Sequence[object], getattr(self._owner._payload, "records")):
payload: object = getattr(record, "payload", None)
if payload is None:
continue
index: int = cast(int, getattr(record, "index"))
field: TorchFieldExportPayload = TorchFieldExportPayload(
payload,
_context_binding(self._owner._bindings, index),
_context_inputs(self._owner._inputs, index),
self._owner._torch,
)
for name in field.derivatives.keys():
if name not in seen:
seen.add(name)
names.append(name)
return tuple(names)
[docs]
def __getitem__(
self, name: str
) -> "TorchBatchFieldDerivativePayload | TorchBatchComplexFieldDerivativePayload":
"""Return one bound solver derivative for each available batch entry.
Parameters
----------
name : str
Differentiable project key name.
Returns
-------
TorchBatchFieldDerivativePayload | TorchBatchComplexFieldDerivativePayload
Detached field derivatives keyed by original batch index.
Raises
------
KeyError
If ``name`` is not bound to a differentiable input.
"""
if name not in self.keys():
raise KeyError(name)
real_entries: list[tuple[int, TorchFieldDerivativePayload]] = []
imag_entries: list[tuple[int, TorchFieldDerivativePayload]] = []
complex_output: bool | None = None
records: Sequence[object] = cast(
Sequence[object], getattr(self._owner._payload, "records")
)
for record in records:
payload: object = getattr(record, "payload", None)
if payload is None:
continue
index: int = cast(int, getattr(record, "index"))
field: TorchFieldExportPayload = TorchFieldExportPayload(
payload,
_context_binding(self._owner._bindings, index),
_context_inputs(self._owner._inputs, index),
self._owner._torch,
)
for operation in self._owner._transforms:
field = (
cast(TorchFieldExportPayload, field.intensity)
if operation == "intensity"
else field.transform(operation)
)
if name not in field.derivatives.keys():
continue
derivative: (
TorchFieldDerivativePayload | TorchComplexFieldDerivativePayload
) = field.derivatives[name]
is_complex: bool = isinstance(
derivative, TorchComplexFieldDerivativePayload
)
if complex_output is None:
complex_output = is_complex
elif complex_output != is_complex:
raise ValueError(
"Batch field-derivative outputs must have a consistent complex topology."
)
if isinstance(derivative, TorchComplexFieldDerivativePayload):
real_entries.append((index, derivative.real))
if derivative.imag is not None:
imag_entries.append((index, derivative.imag))
else:
real_entries.append((index, derivative))
real_payload: TorchBatchFieldDerivativePayload = (
TorchBatchFieldDerivativePayload(tuple(real_entries))
)
if complex_output:
imag_payload: TorchBatchFieldDerivativePayload | None = (
TorchBatchFieldDerivativePayload(tuple(imag_entries))
if imag_entries
else None
)
return TorchBatchComplexFieldDerivativePayload(real_payload, imag_payload)
return real_payload
[docs]
class TorchBatchFieldDerivativePayload:
"""Provide field sensitivities keyed by original batch index.
This payload composes the dictionary and selection behavior of
:class:`TorchFieldDerivativePayload` across available batch entries. Its
``to_dict()`` method returns each single-entry derivative mapping under the
original batch index.
First sensitivities remain differentiable when all required second-order
pairs are available. Without second-order data, they are detached values.
Partial pair data raises an error when exporting a first sensitivity.
Selected second-order values are detached.
A lookup in :class:`TorchBatchFieldDerivativeCollection` returns this payload
for a real input. Do not construct it directly.
"""
def __init__(
self, entries: tuple[tuple[int, TorchFieldDerivativePayload], ...]
) -> None:
self._entries = entries
[docs]
def to_dict(self) -> Mapping[int, Mapping[object, object]]:
"""Return derivative mappings for available batch entries.
Returns
-------
Mapping[int, Mapping[object, object]]
Derivative mappings keyed by original batch index.
"""
return {index: derivative.to_dict() for index, derivative in self._entries}
@property
def derivatives(self) -> "TorchNestedBatchFieldDerivativeCollection":
"""Return nested solver derivatives aligned by original batch index.
Each available entry is navigated independently. Missing and failed
entries remain absent; they are never filled from a neighboring entry.
"""
return TorchNestedBatchFieldDerivativeCollection(self._entries)
[docs]
def select(self, index: int | None = None) -> "TorchBatchFieldDerivativePayload":
"""Select one field position in every available batch entry.
Parameters
----------
index : int | None, optional
Field position. ``None`` selects all positions.
Returns
-------
TorchBatchFieldDerivativePayload
Selected derivatives with original batch indices.
"""
return TorchBatchFieldDerivativePayload(
tuple(
(batch_index, derivative.select(index))
for batch_index, derivative in self._entries
)
)
def to_xarray(self) -> object:
"""Raise because Torch batch derivative records support dictionary export only.
Returns
-------
object
This method does not return.
Raises
------
UnsupportedExportError
Always. Batch Torch derivative records support ``to_dict()`` only.
"""
raise UnsupportedExportError("Torch derivative records support to_dict() only.")
class TorchNestedBatchFieldDerivativeCollection:
"""Navigate second-order derivatives for independently bound batch entries."""
def __init__(
self, entries: tuple[tuple[int, TorchFieldDerivativePayload], ...]
) -> None:
self._entries = entries
def keys(self) -> tuple[str, ...]:
"""Return second-order key names present in at least one entry."""
names: list[str] = []
for _, derivative in self._entries:
for name in derivative.derivatives.keys():
if name not in names:
names.append(name)
return tuple(names)
def __getitem__(
self, name: str
) -> "TorchBatchFieldDerivativePayload | TorchBatchComplexFieldDerivativePayload":
"""Return independently selected pair payloads by original batch index."""
if any(
derivative._selection.connection == "inspection"
for _, derivative in self._entries
):
raise ValueError("Third-order field derivatives are not available.")
if name not in self.keys():
raise KeyError(name)
real: list[tuple[int, TorchFieldDerivativePayload]] = []
imag: list[tuple[int, TorchFieldDerivativePayload]] = []
complex_output: bool = False
for index, derivative in self._entries:
if name not in derivative.derivatives.keys():
continue
selected: object = derivative.derivatives[name]
if isinstance(selected, TorchComplexFieldDerivativePayload):
complex_output = True
real.append((index, selected.real))
if selected.imag is not None:
imag.append((index, selected.imag))
else:
real.append((index, cast(TorchFieldDerivativePayload, selected)))
real_payload: TorchBatchFieldDerivativePayload = (
TorchBatchFieldDerivativePayload(tuple(real))
)
if complex_output:
return TorchBatchComplexFieldDerivativePayload(
real_payload,
TorchBatchFieldDerivativePayload(tuple(imag)) if imag else None,
)
return real_payload
[docs]
@dataclass(frozen=True, slots=True)
class TorchBatchComplexFieldDerivativePayload:
"""Store packed output-component derivatives across a batch.
This payload composes the component behavior of
:class:`TorchComplexFieldDerivativePayload` across batch entries. The ``real``
and optional ``imag`` values are batch derivative payloads. Selection applies
to both components.
A lookup in :class:`TorchBatchFieldDerivativeCollection` returns this payload
for a complex input.
Attributes
----------
real : TorchBatchFieldDerivativePayload
Packed gradient of the real output component by original batch index.
imag : TorchBatchFieldDerivativePayload | None
Packed gradient of the imaginary output component, or ``None`` when the field
output is real.
"""
real: TorchBatchFieldDerivativePayload
imag: TorchBatchFieldDerivativePayload | None
@property
def derivatives(self) -> "TorchNestedBatchComplexFieldDerivativeCollection":
"""Return nested derivatives for both output components."""
return TorchNestedBatchComplexFieldDerivativeCollection(self)
[docs]
def select(
self, index: int | None = None
) -> "TorchBatchComplexFieldDerivativePayload":
"""Select the same field position from both output components.
Parameters
----------
index : int | None, optional
Field position. ``None`` selects all positions.
Returns
-------
TorchBatchComplexFieldDerivativePayload
Complex derivative payload with both components selected.
"""
return TorchBatchComplexFieldDerivativePayload(
self.real.select(index),
None if self.imag is None else self.imag.select(index),
)
class TorchNestedBatchComplexFieldDerivativeCollection:
"""Navigate nested derivative pairs while preserving output components."""
def __init__(self, owner: TorchBatchComplexFieldDerivativePayload) -> None:
self._owner = owner
def keys(self) -> tuple[str, ...]:
"""Return second-order names available in either component."""
names: list[str] = list(self._owner.real.derivatives.keys())
if self._owner.imag is not None:
names.extend(
name
for name in self._owner.imag.derivatives.keys()
if name not in names
)
return tuple(names)
def __getitem__(self, name: str) -> "TorchBatchNestedComplexFieldDerivativePayload":
"""Return nested real and imaginary outputs without positional alignment."""
derivative_entries: tuple[tuple[int, TorchFieldDerivativePayload], ...] = (
self._owner.real._entries
+ (() if self._owner.imag is None else self._owner.imag._entries)
)
if any(
derivative._selection.connection == "inspection"
for _, derivative in derivative_entries
):
raise ValueError("Third-order field derivatives are not available.")
if name not in self.keys():
raise KeyError(name)
real: object = self._owner.real.derivatives[name]
imaginary: object | None = (
None
if self._owner.imag is None
or name not in self._owner.imag.derivatives.keys()
else self._owner.imag.derivatives[name]
)
return TorchBatchNestedComplexFieldDerivativePayload(
real=cast(
TorchBatchFieldDerivativePayload
| TorchBatchComplexFieldDerivativePayload,
real,
),
imag=cast(
TorchBatchFieldDerivativePayload
| TorchBatchComplexFieldDerivativePayload
| None,
imaginary,
),
)
@dataclass(frozen=True, slots=True)
class TorchBatchNestedComplexFieldDerivativePayload:
"""Represent nested output components, each retaining its input packing."""
real: TorchBatchFieldDerivativePayload | TorchBatchComplexFieldDerivativePayload
imag: (
TorchBatchFieldDerivativePayload
| TorchBatchComplexFieldDerivativePayload
| None
)
def _transform_mapping(
mapping: Mapping[object, object],
transforms: tuple[_TransformName, ...],
torch_module: object,
*,
grid_rank: int,
) -> Mapping[object, object]:
if not transforms:
return mapping
transformed: dict[object, object] = {}
for key, value in mapping.items():
if key == "field":
transformed[key] = _transform_field_value(
value, transforms, torch_module, grid_rank
)
elif isinstance(value, Mapping):
transformed[key] = _transform_mapping(
value,
transforms,
torch_module,
grid_rank=grid_rank,
)
else:
transformed[key] = value
return transformed
def _field_grid_rank(mapping: Mapping[object, object]) -> int:
"""Return the active spatial rank using the ordinary field topology rules."""
raw_field: object = mapping.get("field")
if isinstance(raw_field, (list, tuple)) and raw_field:
raw_field = raw_field[0]
field_shape: tuple[int, ...] = tuple(
int(size) for size in np.asarray(cast(Sequence[object], raw_field)).shape
)
return len(resolve_coordinates(mapping, field_shape=field_shape).grid_shape)
def _convert_numeric(value: object, torch_module: object) -> object:
converted: TorchTensor | None = numeric_tensor(value, torch_module, device="cpu")
return value if converted is None else converted
def _detach(value: object) -> object:
detach: object = getattr(value, "detach", None)
return detach() if callable(detach) else value
def _is_complex_tensor(value: object, torch_module: object) -> bool:
is_complex: object = getattr(torch_module, "is_complex", None)
if callable(is_complex):
return bool(is_complex(value))
return "complex" in str(getattr(value, "dtype", ""))
def _jvp(
value: object,
tangent: object,
transforms: tuple[_TransformName, ...],
torch_module: object,
*,
grid_rank: int,
) -> tuple[object, object]:
"""Apply field operations and their forward directional derivatives."""
current: object = value
current_tangent: object = tangent
for operation in transforms:
if operation == "real":
current = getattr(torch_module, "real")(current)
current_tangent = getattr(torch_module, "real")(current_tangent)
elif operation == "imag":
current = getattr(torch_module, "imag")(current)
current_tangent = getattr(torch_module, "imag")(current_tangent)
elif operation == "abs":
magnitude: object = getattr(torch_module, "abs")(current)
numerator: object = getattr(torch_module, "real")(
getattr(torch_module, "conj")(current) * current_tangent
)
current_tangent = getattr(torch_module, "where")(
magnitude == 0,
getattr(torch_module, "zeros_like")(magnitude),
getattr(numerator, "__truediv__")(magnitude),
)
current = magnitude
elif operation == "phase":
phase_magnitude: object = getattr(torch_module, "abs")(current)
numerator = getattr(torch_module, "imag")(
getattr(torch_module, "conj")(current) * current_tangent
)
current_tangent = getattr(torch_module, "where")(
phase_magnitude == 0,
getattr(torch_module, "zeros_like")(phase_magnitude),
getattr(numerator, "__truediv__")(
getattr(phase_magnitude, "__mul__")(phase_magnitude)
),
)
current = getattr(torch_module, "angle")(current)
elif operation == "intensity":
magnitude = getattr(torch_module, "abs")(current)
intensity: object = getattr(magnitude, "__mul__")(magnitude)
current_tangent = getattr(
getattr(torch_module, "real")(
getattr(torch_module, "conj")(current) * current_tangent
),
"__mul__",
)(2)
if getattr(current, "ndim") == grid_rank + 1:
current_tangent = getattr(current_tangent, "sum")(dim=-1)
intensity = getattr(intensity, "sum")(dim=-1)
current = intensity
return current, current_tangent
def _transform_field_value(
value: object,
transforms: tuple[_TransformName, ...],
torch_module: object,
grid_rank: int,
) -> object:
if is_tensor(value, torch_module):
transformed: object = value
for operation in transforms:
if operation == "intensity":
magnitude: object = getattr(torch_module, "abs")(transformed)
magnitude_squared: object = getattr(magnitude, "__mul__")(magnitude)
if getattr(transformed, "ndim") == grid_rank + 1:
transformed = getattr(magnitude_squared, "sum")(dim=-1)
else:
transformed = magnitude_squared
else:
transformed = _apply_torch_transform(
operation, transformed, torch_module
)
return transformed
if isinstance(value, list):
return [
_transform_field_value(item, transforms, torch_module, grid_rank)
for item in value
]
if isinstance(value, tuple):
return tuple(
_transform_field_value(item, transforms, torch_module, grid_rank)
for item in value
)
return value
def _apply_torch_transform(
operation: _TransformName, value: object, torch_module: object
) -> object:
if operation != "phase":
return getattr(torch_module, operation)(value)
magnitude: object = getattr(torch_module, "abs")(value)
phase: object = getattr(torch_module, "angle")(value)
return getattr(torch_module, "where")(
magnitude == 0,
getattr(torch_module, "zeros_like")(phase),
phase,
)
[docs]
class TorchPostprocessCollection:
"""Provide Torch-aware access to a result's postprocess records.
Indexing or iteration returns :class:`TorchPostprocessRecord` values. For
the navigation and export contract shared with ordinary results, see
:class:`jcmsuite.results.PostprocessCollection`.
This class is returned by result accessors. Do not construct it directly.
"""
def __init__(
self,
collection: object,
bindings: BindingMap,
inputs: tuple[TorchTensor, ...],
torch_module: object,
) -> None:
self._collection, self._bindings, self._inputs, self._torch = (
collection,
bindings,
inputs,
torch_module,
)
[docs]
def __len__(self) -> int:
"""Return the number of postprocess records.
Returns
-------
int
Number of postprocess records.
"""
return len(cast(Sequence[object], self._collection))
[docs]
def __iter__(self) -> Iterator[TorchPostprocessRecord]:
"""Iterate over Torch postprocess records in project order.
Returns
-------
Iterator[TorchPostprocessRecord]
Torch-aware records in postprocess order.
"""
return (self[index] for index in range(len(self)))
[docs]
def __getitem__(self, index: int) -> TorchPostprocessRecord:
"""Return one Torch postprocess record by its integer position.
Parameters
----------
index : int
Postprocess position.
Returns
-------
TorchPostprocessRecord
Selected Torch-aware record.
"""
return TorchPostprocessRecord(self._collection[index], self._bindings, self._inputs, self._torch) # type: ignore[index]
[docs]
def titles(self) -> tuple[str, ...]:
"""Return postprocess titles in project order.
Returns
-------
tuple[str, ...]
Titles in postprocess order.
"""
return cast(tuple[str, ...], getattr(self._collection, "titles")())
def __getattr__(self, name: str) -> object:
return getattr(self._collection, name)
[docs]
class TorchBatchPostprocessCollection:
"""Provide Torch-aware access to postprocess streams across a batch.
The ordinary :class:`jcmsuite.results.BatchPostprocessCollection` defines
the batch navigation. This wrapper adds the Torch semantics of
:class:`TorchPostprocessCollection` to each selected record.
A Torch batch solve result returns this class. Do not construct it directly.
"""
def __init__(
self,
collection: object,
bindings: BindingContext,
inputs: InputContext,
torch_module: object,
) -> None:
self._collection, self._bindings, self._inputs, self._torch = (
collection,
bindings,
inputs,
torch_module,
)
[docs]
def __len__(self) -> int:
"""Return the number of postprocess streams.
Returns
-------
int
Number of postprocess streams.
"""
return len(cast(Sequence[object], self._collection))
[docs]
def __iter__(self) -> Iterator[TorchBatchPostprocessRecord]:
"""Iterate over batch postprocess streams in project order.
Returns
-------
Iterator[TorchBatchPostprocessRecord]
Torch-aware records in postprocess order.
"""
return (self[index] for index in range(len(self)))
[docs]
def __getitem__(self, index: int) -> TorchBatchPostprocessRecord:
"""Return one batch postprocess stream.
Parameters
----------
index : int
Postprocess position.
Returns
-------
TorchBatchPostprocessRecord
Selected batch record with entry-specific input contexts.
"""
return TorchBatchPostprocessRecord(
self._collection[index], self._bindings, self._inputs, self._torch # type: ignore[index]
)
[docs]
def titles(self) -> tuple[str, ...]:
"""Return postprocess titles in project order.
Returns
-------
tuple[str, ...]
Titles from the ordinary batch collection.
"""
return cast(tuple[str, ...], getattr(self._collection, "titles")())
def __getattr__(self, name: str) -> object:
return getattr(self._collection, name)
class _TorchResultBase:
"""Implement shared Torch-aware access for solve-result wrappers.
The wrapper preserves the ordinary result returned by the shared solve
implementation. Use :meth:`~jcmsuite.torch.results.TorchSolveResult.untorch`
on a public wrapper when ordinary result and payload behavior is required
instead of Torch-connected values.
"""
def __init__(
self,
result: object,
bindings: BindingContext,
inputs: InputContext,
torch_module: object,
) -> None:
self._result, self._bindings, self._inputs, self._torch = (
result,
bindings,
inputs,
torch_module,
)
def untorch(
self,
) -> SolveResult | BatchSolveResult | BundledSolveResult | BundledBatchSolveResult:
"""Return the underlying ordinary solve result without recomputing it.
Returns
-------
SolveResult | BatchSolveResult | BundledSolveResult | BundledBatchSolveResult
The ordinary result produced by the shared solve implementation.
"""
return cast(
SolveResult
| BatchSolveResult
| BundledSolveResult
| BundledBatchSolveResult,
self._result,
)
def _entry_bindings(self, index: int) -> BindingMap:
return (
self._bindings[index]
if isinstance(self._bindings, tuple)
else self._bindings
)
def _entry_inputs(self, index: int) -> tuple[TorchTensor, ...]:
return (
cast(tuple[tuple[TorchTensor, ...], ...], self._inputs)[index]
if self._inputs and isinstance(self._inputs[0], tuple)
else self._inputs
)
@property
def postprocesses(
self,
) -> TorchPostprocessCollection | TorchBatchPostprocessCollection:
"""Return Torch-aware access to the ordinary postprocess collection."""
collection: object = getattr(self._result, "postprocesses")
if isinstance(self._result, BatchSolveResult):
return TorchBatchPostprocessCollection(
collection, self._bindings, self._inputs, self._torch
)
return TorchPostprocessCollection(
collection,
self._entry_bindings(0),
self._entry_inputs(0),
self._torch,
)
def _select(self, index: int | slice) -> object:
selected: object = self._result[index] # type: ignore[index]
if isinstance(self._result, BundledBatchSolveResult):
project_index: int = cast(int, index)
project_inputs: tuple[tuple[TorchTensor, ...], ...] = cast(
tuple[tuple[tuple[TorchTensor, ...], ...], ...], self._inputs
)[project_index]
return wrap_result(
selected,
self._entry_bindings(project_index),
project_inputs,
self._torch,
)
if isinstance(index, slice) and isinstance(self._result, BatchSolveResult):
return wrap_result(selected, self._bindings, self._inputs, self._torch)
if hasattr(selected, "result"):
return TorchBatchEntry(
selected,
self._entry_bindings(index if isinstance(index, int) else 0),
self._entry_inputs(index if isinstance(index, int) else 0),
self._torch,
)
selected_index: int = index if isinstance(index, int) else 0
return wrap_result(
selected,
self._entry_bindings(selected_index),
self._entry_inputs(selected_index),
self._torch,
)
def __getattr__(self, name: str) -> object:
return getattr(self._result, name)
[docs]
class TorchSolveResult(_TorchResultBase):
"""Wrap a :class:`~jcmsuite.results.SolveResult` with Torch-aware access."""
@property
def postprocesses(self) -> TorchPostprocessCollection:
"""Return the Torch-aware single-result postprocess collection."""
return cast(TorchPostprocessCollection, super().postprocesses)
[docs]
def untorch(self) -> SolveResult:
"""Return the underlying single-project result without recomputing it.
Returns
-------
SolveResult
The ordinary :class:`~jcmsuite.results.SolveResult`.
"""
return cast(SolveResult, super().untorch())
[docs]
class TorchBatchSolveResult(_TorchResultBase):
"""Wrap a :class:`~jcmsuite.results.BatchSolveResult` with Torch-aware access."""
@property
def postprocesses(self) -> TorchBatchPostprocessCollection:
"""Return the Torch-aware aggregate batch postprocess collection."""
return cast(TorchBatchPostprocessCollection, super().postprocesses)
[docs]
def untorch(self) -> BatchSolveResult:
"""Return the underlying batched result without recomputing it.
Returns
-------
BatchSolveResult
The ordinary :class:`~jcmsuite.results.BatchSolveResult`.
"""
return cast(BatchSolveResult, super().untorch())
def __len__(self) -> int:
"""Return the number of batch entries.
Returns
-------
int
Number of batch entries.
"""
return len(cast(Sequence[object], self._result))
def __iter__(self) -> Iterator[object]:
"""Iterate over Torch-aware batch entries in input order.
Returns
-------
Iterator[object]
Torch-aware batch entries.
"""
return (self[index] for index in range(len(self)))
def __getitem__(self, index: int | slice) -> object:
"""Return one Torch-aware batch entry or a sliced batch result.
Parameters
----------
index : int | slice
Batch entry position or slice.
Returns
-------
object
A Torch-aware batch entry or batch result.
"""
return self._select(index)
[docs]
class TorchBundledSolveResult(_TorchResultBase):
"""Wrap a :class:`~jcmsuite.results.BundledSolveResult` with Torch-aware access."""
[docs]
def untorch(self) -> BundledSolveResult:
"""Return the underlying ordered-bundle result without recomputing it.
Returns
-------
BundledSolveResult
The ordinary :class:`~jcmsuite.results.BundledSolveResult`.
"""
return cast(BundledSolveResult, super().untorch())
def __len__(self) -> int:
"""Return the number of projects in the ordered bundle.
Returns
-------
int
Number of projects.
"""
return len(cast(Sequence[object], self._result))
def __iter__(self) -> Iterator[object]:
"""Iterate over project results in ordered bundle order.
Returns
-------
Iterator[object]
Torch-aware project results.
"""
return (self[index] for index in range(len(self)))
def __getitem__(self, index: int | slice) -> object:
"""Return one project result by integer position.
Parameters
----------
index : int | slice
Project position or slice.
Returns
-------
object
A Torch-aware project result or selected bundle result.
"""
return self._select(index)
[docs]
class TorchBundledBatchSolveResult(_TorchResultBase):
"""Wrap a :class:`~jcmsuite.results.BundledBatchSolveResult` with Torch-aware access."""
[docs]
def untorch(self) -> BundledBatchSolveResult:
"""Return the underlying bundled-batch result without recomputing it.
Returns
-------
BundledBatchSolveResult
The ordinary :class:`~jcmsuite.results.BundledBatchSolveResult`.
"""
return cast(BundledBatchSolveResult, super().untorch())
def __len__(self) -> int:
"""Return the number of projects in the bundled batch.
Returns
-------
int
Number of projects.
"""
return len(cast(Sequence[object], self._result))
def __iter__(self) -> Iterator[object]:
"""Iterate over project batch results in bundle order.
Returns
-------
Iterator[object]
Torch-aware project batch results.
"""
return (self[index] for index in range(len(self)))
def __getitem__(self, index: int | slice) -> object:
"""Return one project batch result by integer position.
Parameters
----------
index : int | slice
Project position or slice.
Returns
-------
object
A Torch-aware project batch result.
"""
return self._select(index)
class TorchBatchEntry:
"""Expose one batch entry and wrap its successful result when present."""
def __init__(
self,
entry: object,
bindings: BindingMap,
inputs: tuple[TorchTensor, ...],
torch_module: object,
) -> None:
self._entry, self._bindings, self._inputs, self._torch = (
entry,
bindings,
inputs,
torch_module,
)
@property
def result(self) -> object | None:
result: object = getattr(self._entry, "result")
return (
None
if result is None
else wrap_result(result, self._bindings, self._inputs, self._torch)
)
def __getattr__(self, name: str) -> object:
return getattr(self._entry, name)
class TorchSubmission(Generic[_TorchResultType]):
"""Wrap a daemon submission and Torch-wrap the result returned by ``wait``."""
def __init__(
self,
submission: object,
bindings: BindingContext,
inputs: InputContext,
torch_module: object,
) -> None:
self._submission, self._bindings, self._inputs, self._torch = (
submission,
bindings,
inputs,
torch_module,
)
def __getattr__(self, name: str) -> object:
return getattr(self._submission, name)
def untorch(self) -> object:
"""Return the underlying ordinary submission without recomputing it."""
return self._submission
def _entry_bindings(self, index: int) -> BindingMap:
return (
self._bindings[index]
if isinstance(self._bindings, tuple)
else self._bindings
)
def _entry_inputs(self, index: int) -> tuple[TorchTensor, ...]:
return (
cast(tuple[tuple[TorchTensor, ...], ...], self._inputs)[index]
if self._inputs and isinstance(self._inputs[0], tuple)
else self._inputs
)
def _select(self, index: int | slice) -> object:
selected: object = self._submission[index] # type: ignore[index]
selected_index: int = index if isinstance(index, int) else 0
return wrap_result(
selected,
self._entry_bindings(selected_index),
self._entry_inputs(selected_index),
self._torch,
)
@overload
def wait(
self, *, asynchronous: Literal[False] = False, **kwargs: object
) -> _TorchResultType: ...
@overload
def wait(
self, *, asynchronous: Literal[True], **kwargs: object
) -> Coroutine[object, object, _TorchResultType]: ...
def wait(
self, **kwargs: object
) -> _TorchResultType | Coroutine[object, object, _TorchResultType]:
"""Wait for completion and return the shape-specific Torch result wrapper.
Parameters
----------
kwargs : object
Options accepted by the corresponding ordinary submission wait
method, such as :meth:`~jcmsuite.results.SolveSubmission.wait`. Set
``asynchronous=True`` to receive a coroutine.
Returns
-------
_TorchResultType | Coroutine[object, object, _TorchResultType]
The Torch result wrapper, or a coroutine that resolves to it.
"""
return self._wait_impl(**kwargs)
def _wait_impl(
self, **kwargs: object
) -> _TorchResultType | Coroutine[object, object, _TorchResultType]:
"""Delegate ordinary waiting and wrap the returned result."""
waited: object = getattr(self._submission, "wait")(**kwargs)
if asyncio.iscoroutine(waited):
async def bind() -> _TorchResultType:
return cast(
_TorchResultType,
wrap_result(
await waited, self._bindings, self._inputs, self._torch
),
)
return bind()
return cast(
_TorchResultType,
wrap_result(waited, self._bindings, self._inputs, self._torch),
)
[docs]
class TorchSolveSubmission(TorchSubmission["TorchSolveResult"]):
"""Wrap a :class:`~jcmsuite.results.SolveSubmission`."""
[docs]
def untorch(self) -> SolveSubmission:
"""Return the ordinary single-project submission without recomputing it.
Returns
-------
SolveSubmission
The underlying :class:`~jcmsuite.results.SolveSubmission`.
"""
return cast(SolveSubmission, super().untorch())
@overload
def wait(
self, *, asynchronous: Literal[False] = False, **kwargs: object
) -> TorchSolveResult: ...
@overload
def wait(
self, *, asynchronous: Literal[True], **kwargs: object
) -> Coroutine[object, object, TorchSolveResult]: ...
[docs]
def wait(
self, **kwargs: object
) -> TorchSolveResult | Coroutine[object, object, TorchSolveResult]:
"""Wait for a single-project Torch result.
Parameters
----------
kwargs : object
Options accepted by :meth:`~jcmsuite.results.SolveSubmission.wait`.
Use ``asynchronous=True`` to receive a coroutine.
Returns
-------
TorchSolveResult | Coroutine[object, object, TorchSolveResult]
The :class:`~jcmsuite.torch.results.TorchSolveResult`, or a
coroutine that resolves to it.
"""
return self._wait_impl(**kwargs)
[docs]
class TorchBatchSolveSubmission(TorchSubmission["TorchBatchSolveResult"]):
"""Wrap a :class:`~jcmsuite.results.BatchSolveSubmission`."""
[docs]
def untorch(self) -> BatchSolveSubmission:
"""Return the ordinary batched submission without recomputing it.
Returns
-------
BatchSolveSubmission
The underlying :class:`~jcmsuite.results.BatchSolveSubmission`.
"""
return cast(BatchSolveSubmission, super().untorch())
@overload
def wait(
self, *, asynchronous: Literal[False] = False, **kwargs: object
) -> TorchBatchSolveResult: ...
@overload
def wait(
self, *, asynchronous: Literal[True], **kwargs: object
) -> Coroutine[object, object, TorchBatchSolveResult]: ...
[docs]
def wait(
self, **kwargs: object
) -> TorchBatchSolveResult | Coroutine[object, object, TorchBatchSolveResult]:
"""Wait for a batched Torch result.
Parameters
----------
kwargs : object
Options accepted by :meth:`~jcmsuite.results.BatchSolveSubmission.wait`.
Use ``asynchronous=True`` to receive a coroutine.
Returns
-------
TorchBatchSolveResult | Coroutine[object, object, TorchBatchSolveResult]
The :class:`~jcmsuite.torch.results.TorchBatchSolveResult`, or a
coroutine that resolves to it.
"""
return self._wait_impl(**kwargs)
def __len__(self) -> int:
"""Return the number of batch submissions.
Returns
-------
int
Number of batch submissions.
"""
return len(cast(Sequence[object], self._submission))
def __iter__(self) -> Iterator[object]:
"""Iterate over batch submissions in input order.
Returns
-------
Iterator[object]
Torch-aware batch submissions.
"""
return (self[index] for index in range(len(self)))
def __getitem__(self, index: int | slice) -> object:
"""Return one Torch-aware batch submission entry or a slice.
Parameters
----------
index : int | slice
Batch submission position or slice.
Returns
-------
object
A Torch-aware batch submission entry or batch submission.
"""
return self._select(index)
[docs]
class TorchBundledSolveSubmission(TorchSubmission["TorchBundledSolveResult"]):
"""Wrap a :class:`~jcmsuite.results.BundledSolveSubmission`."""
[docs]
def untorch(self) -> BundledSolveSubmission:
"""Return the ordinary ordered-bundle submission without recomputing it.
Returns
-------
BundledSolveSubmission
The underlying :class:`~jcmsuite.results.BundledSolveSubmission`.
"""
return cast(BundledSolveSubmission, super().untorch())
@overload
def wait(
self, *, asynchronous: Literal[False] = False, **kwargs: object
) -> TorchBundledSolveResult: ...
@overload
def wait(
self, *, asynchronous: Literal[True], **kwargs: object
) -> Coroutine[object, object, TorchBundledSolveResult]: ...
[docs]
def wait(
self, **kwargs: object
) -> TorchBundledSolveResult | Coroutine[object, object, TorchBundledSolveResult]:
"""Wait for an ordered-bundle Torch result.
Parameters
----------
kwargs : object
Options accepted by :meth:`~jcmsuite.results.BundledSolveSubmission.wait`.
Use ``asynchronous=True`` to receive a coroutine.
Returns
-------
TorchBundledSolveResult | Coroutine[object, object, TorchBundledSolveResult]
The :class:`~jcmsuite.torch.results.TorchBundledSolveResult`, or a
coroutine that resolves to it.
"""
return self._wait_impl(**kwargs)
[docs]
class TorchBundledBatchSolveSubmission(TorchSubmission["TorchBundledBatchSolveResult"]):
"""Wrap a :class:`~jcmsuite.results.BundledBatchSolveSubmission`."""
[docs]
def untorch(self) -> BundledBatchSolveSubmission:
"""Return the ordinary bundled-batch submission without recomputing it.
Returns
-------
BundledBatchSolveSubmission
The underlying :class:`~jcmsuite.results.BundledBatchSolveSubmission`.
"""
return cast(BundledBatchSolveSubmission, super().untorch())
@overload
def wait(
self, *, asynchronous: Literal[False] = False, **kwargs: object
) -> TorchBundledBatchSolveResult: ...
@overload
def wait(
self, *, asynchronous: Literal[True], **kwargs: object
) -> Coroutine[object, object, TorchBundledBatchSolveResult]: ...
[docs]
def wait(
self, **kwargs: object
) -> (
TorchBundledBatchSolveResult
| Coroutine[object, object, TorchBundledBatchSolveResult]
):
"""Wait for a bundled-batch Torch result.
Parameters
----------
kwargs : object
Options accepted by :meth:`~jcmsuite.results.BundledBatchSolveSubmission.wait`.
Use ``asynchronous=True`` to receive a coroutine.
Returns
-------
TorchBundledBatchSolveResult | Coroutine[object, object, TorchBundledBatchSolveResult]
The :class:`~jcmsuite.torch.results.TorchBundledBatchSolveResult`,
or a coroutine that resolves to it.
"""
return self._wait_impl(**kwargs)
def __len__(self) -> int:
"""Return the number of projects in the bundled batch submission.
Returns
-------
int
Number of projects.
"""
return len(cast(Sequence[object], self._submission))
def __iter__(self) -> Iterator[object]:
"""Iterate over project batch submissions in bundle order.
Returns
-------
Iterator[object]
Torch-aware project batch submissions.
"""
return (self[index] for index in range(len(self)))
def __getitem__(self, index: int | slice) -> object:
"""Return one project batch submission by position.
Parameters
----------
index : int | slice
Project batch submission position or slice.
Returns
-------
object
A Torch-aware project batch submission.
"""
return self._select(index)
def wrap_result(
result: object, bindings: BindingContext, inputs: InputContext, torch_module: object
) -> object:
result_wrappers: tuple[tuple[type[object], type[_TorchResultBase]], ...] = (
(SolveResult, TorchSolveResult),
(BatchSolveResult, TorchBatchSolveResult),
(BundledSolveResult, TorchBundledSolveResult),
(BundledBatchSolveResult, TorchBundledBatchSolveResult),
)
for result_type, result_wrapper_type in result_wrappers:
if isinstance(result, result_type):
return result_wrapper_type(result, bindings, inputs, torch_module)
submission_wrappers: tuple[
tuple[type[object], type[TorchSubmission[object]]], ...
] = (
(SolveSubmission, TorchSolveSubmission),
(BatchSolveSubmission, TorchBatchSolveSubmission),
(BundledSolveSubmission, TorchBundledSolveSubmission),
(BundledBatchSolveSubmission, TorchBundledBatchSolveSubmission),
)
for submission_type, submission_wrapper_type in submission_wrappers:
if isinstance(result, submission_type):
return submission_wrapper_type(result, bindings, inputs, torch_module)
return result