Source code for jcmsuite.results.postprocess_payloads

# SPDX-License-Identifier: MIT
# Copyright (c) 2001-{{ COPYRIGHT_END_YEAR }} JCMwave GmbH

"""Typed payload adapters used by single-result postprocess records."""

from __future__ import annotations

from collections.abc import Iterator, Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, cast

import numpy as np

from ..exceptions import InvalidConfigurationError
from ..loaders.table import TableCollection
from .field_exports import FieldExportPayload
from .internal.export.pandas.payload import (
    flatten_payload,
    is_numeric_key_mapping,
    payload_to_tabular_rows,
)
from .payloads import (
    DictionaryExportMixin,
    PostprocessRecordPayload,
    Source,
    StructuredPayload,
    TableCollectionPayload,
    TablePayload,
)

if TYPE_CHECKING:
    import pandas as pd

    from .internal.export.xarray.types import XarrayDataTree


@dataclass(slots=True, frozen=True)
class _TableRecordPayload(TablePayload):
    """Typed table payload adapter for one discovered postprocess record."""

    table: Mapping[object, object]
    source: Source = None  # pyright: ignore

    def to_dict(self) -> Mapping[object, object]:
        return dict(self.table)

    def _value_mapping(self) -> Mapping[object, object]:
        values: dict[object, object] = dict(self.table)
        values.pop("title", None)
        values.pop("header", None)
        return values

    def _to_df_wide(self) -> "pd.DataFrame":
        from .internal.export.companion import require_pandas_companion

        require_pandas_companion()
        from jcmsuite_pandas.value_tables import value_table_wide

        return value_table_wide(self._value_mapping(), name="Postprocess")

    def _to_df_long(self) -> "pd.DataFrame":
        from .internal.export.companion import require_pandas_companion

        require_pandas_companion()
        from jcmsuite_pandas.value_tables import value_table_long

        return value_table_long(self._value_mapping(), name="Postprocess")

    def to_xarray(self) -> "XarrayDataTree":
        from .internal.export.companion_xarray import require_xarray_companion

        require_xarray_companion()
        from jcmsuite_xarray.export import postprocess_payload_to_xarray_dataset

        title_object: object | None = self.table.get("title")
        title: str | None = title_object if isinstance(title_object, str) else None
        return postprocess_payload_to_xarray_dataset(
            self._value_mapping(), postprocess_title=title, source_file=self.source
        )


@dataclass(slots=True, frozen=True)
class _StructuredRecordPayload(StructuredPayload):
    """Typed structured payload adapter for restored postprocess records."""

    mapping: Mapping[object, object]
    source: Source = None  # pyright: ignore

    def _value_mapping(self) -> Mapping[object, object]:
        values: dict[object, object] = dict(self.mapping)
        values.pop("title", None)
        values.pop("header", None)
        return values

    def to_dict(self) -> Mapping[object, object]:
        return dict(self.mapping)

    def _to_df_long(self) -> "pd.DataFrame":
        from .internal.export.companion import require_pandas_companion

        require_pandas_companion()
        from jcmsuite_pandas.single import structured_payload_to_dataframe

        return structured_payload_to_dataframe(self._value_mapping())

    def to_xarray(self) -> "XarrayDataTree":
        from .internal.export.companion_xarray import require_xarray_companion

        require_xarray_companion()
        from jcmsuite_xarray.export import postprocess_payload_to_xarray_dataset

        title_object: object | None = self.mapping.get("title")
        title: str | None = title_object if isinstance(title_object, str) else None
        return postprocess_payload_to_xarray_dataset(
            self._value_mapping(), postprocess_title=title, source_file=self.source
        )


@dataclass(slots=True, frozen=True)
class _TableCollectionRecordPayload(TableCollectionPayload):
    """Typed table-collection payload adapter for one discovered record."""

    collection: TableCollection
    source: Source = None  # pyright: ignore

    def to_dict(self) -> Mapping[object, object]:
        names: tuple[str, ...] = self.collection.table_names()
        result: dict[str, object] = {}
        for name, table in zip(names, self.collection, strict=True):
            if not isinstance(table, Mapping):
                raise InvalidConfigurationError(
                    "Table-collection mapping export requires named table payloads."
                )
            result[name] = dict(table)
        return cast(Mapping[object, object], result)

    def _to_df_long(self) -> "pd.DataFrame":
        return self.collection.to_df()

    def to_xarray(self) -> "XarrayDataTree":
        return self.collection.to_xarray()


class _StandaloneTablePayload(TablePayload, Mapping[object, object]):
    """Standalone named table payload."""

    def __init__(self, table: Mapping[object, object], *, source: Source) -> None:
        self._delegate = _TableRecordPayload(table=table, source=source)

    @property
    def source(self) -> Source:
        return self._delegate.source

    def to_dict(self) -> Mapping[object, object]:
        return self._delegate.to_dict()

    def __getitem__(self, key: object) -> object:
        return self.to_dict()[key]

    def __iter__(self) -> Iterator[object]:
        return iter(self.to_dict())

    def __len__(self) -> int:
        return len(self.to_dict())

    def _to_df_wide(self) -> "pd.DataFrame":
        return self._delegate._to_df_wide()

    def _to_df_long(self) -> "pd.DataFrame":
        return self._delegate._to_df_long()

    def to_xarray(self) -> "XarrayDataTree":
        return self._delegate.to_xarray()


class _StandaloneTableCollectionPayload(TableCollectionPayload):
    """Standalone named table collection payload."""

    def __init__(self, collection: TableCollection) -> None:
        self._delegate = _TableCollectionRecordPayload(
            collection=collection, source=collection.source_file
        )

    @property
    def source(self) -> Source:
        return self._delegate.source

    def to_dict(self) -> Mapping[object, object]:
        return self._delegate.to_dict()

    def __getitem__(self, index: int) -> Mapping[object, object]:
        table: object = self._delegate.collection[index]
        if not isinstance(table, Mapping):
            raise InvalidConfigurationError(
                "Table-collection payload contains a non-mapping table."
            )
        return cast(Mapping[object, object], table)

    def __iter__(self) -> Iterator[Mapping[object, object]]:
        return (
            cast(Mapping[object, object], table) for table in self._delegate.collection
        )

    def __len__(self) -> int:
        return len(self._delegate.collection)

    def _to_df_long(self) -> "pd.DataFrame":
        return self._delegate._to_df_long()

    def to_xarray(self) -> "XarrayDataTree":
        return self._delegate.to_xarray()


[docs] class TableDerivativeCollection: """Select solver derivatives from one canonical table payload.""" def __init__( self, payload: TablePayload, *, root: Mapping[object, object] | None = None, parameter: str | None = None, depth: int = 0, ) -> None: self._payload: TablePayload = payload self._root: Mapping[object, object] = ( payload.to_dict() if root is None else root ) self._parameter: str | None = parameter self._depth: int = depth
[docs] def keys(self) -> tuple[str, ...]: """Return the solver parameter names available for derivative selection. On a postprocess record's derivative collection, the names select first derivatives. After selecting a first derivative, the names select its available second derivatives. These are solver parameter names, not Torch project keys. Returns ------- tuple[str, ...] Available parameter names in table traversal order. The tuple is empty if no further derivative is available, including after a second derivative has been selected. """ if self._depth >= 2: return () names: dict[str, None] = {} if self._parameter is None: branches: Mapping[object, object] = self._root for key, value in branches.items(): if ( isinstance(key, str) and key.startswith("d_") and isinstance(value, Mapping) ): names[key[2:]] = None else: current_branch: object = self._root.get(f"d_{self._parameter}") if isinstance(current_branch, Mapping): for key, value in current_branch.items(): if ( isinstance(key, str) and key.startswith("d_") and isinstance(value, Mapping) ): names[key[2:]] = None # Some parsed second-order schemas store the same unordered pair # beneath the other first-derivative branch. Expose that pair in # both traversal orders without splitting parameter labels. for key, value in self._root.items(): if ( not isinstance(key, str) or not key.startswith("d_") or not isinstance(value, Mapping) ): continue reverse: object = value.get(f"d_{self._parameter}") if isinstance(reverse, Mapping): names[key[2:]] = None return tuple(names)
def __getitem__(self, name: str) -> "TableDerivativeView": """Select one derivative by solver parameter name.""" if not isinstance(name, str): raise TypeError("Derivative names must be strings.") if self._depth >= 2: raise KeyError(f"derivatives[{self._parameter!r}].derivatives[{name!r}]") branch: str = f"d_{name}" if self._parameter is None: selected: object = self._root.get(branch) expected_base: dict[object, object] = { key: value for key, value in self._root.items() if key not in {"title", "header"} and not ( isinstance(key, str) and key.startswith("d_") and isinstance(value, Mapping) ) } if isinstance(selected, Mapping) and not _compatible_numeric_shapes( selected, expected_base ): raise InvalidConfigurationError( f"Incompatible shapes for derivative path derivatives[{name!r}]." ) else: current: object = self._root.get(f"d_{self._parameter}") direct: object = ( current.get(branch) if isinstance(current, Mapping) else None ) reverse_parent: object = self._root.get(branch) reverse: object = ( reverse_parent.get(f"d_{self._parameter}") if isinstance(reverse_parent, Mapping) else None ) if isinstance(direct, Mapping) and isinstance(reverse, Mapping): if not _equivalent_derivative_payloads(direct, reverse): message: str = ( f"Conflicting table derivative paths d_{self._parameter}.{branch} " f"and {branch}.d_{self._parameter}." ) if not _compatible_numeric_shapes(direct, reverse): message = ( f"Incompatible shapes for table derivative paths " f"d_{self._parameter}.{branch} and {branch}.d_{self._parameter}." ) raise InvalidConfigurationError(message) selected = direct if isinstance(direct, Mapping) else reverse expected: object = current if isinstance(selected, Mapping) and isinstance(expected, Mapping): if not _compatible_numeric_shapes(selected, expected): raise InvalidConfigurationError( f"Incompatible shapes for derivative path " f"derivatives[{self._parameter!r}].derivatives[{name!r}]." ) if not isinstance(selected, Mapping): path: str = ( f"derivatives[{self._parameter!r}].derivatives[{name!r}]" if self._parameter is not None else f"derivatives[{name!r}]" ) raise KeyError(path) return TableDerivativeView( cast(Mapping[object, object], selected), source=self._payload.source, root=self._root, parameter=name, depth=self._depth + 1, )
class TableDerivativeView(TablePayload): """Table-shaped export of a selected first- or higher-order derivative.""" def __init__( self, values: Mapping[object, object], *, source: Source, root: Mapping[object, object], parameter: str, depth: int, ) -> None: self._delegate: _TableRecordPayload = _TableRecordPayload( table=values, source=source ) self._root: Mapping[object, object] = root self._parameter: str = parameter self._depth: int = depth export_values: dict[object, object] = { key: value for key, value in values.items() if not ( isinstance(key, str) and key.startswith("d_") and isinstance(value, Mapping) ) } for metadata_key in ("title", "header"): if metadata_key in root and metadata_key not in export_values: export_values[metadata_key] = root[metadata_key] self._export_delegate: _TableRecordPayload = _TableRecordPayload( table=export_values, source=source ) @property def source(self) -> Source: return self._delegate.source @property def derivatives(self) -> TableDerivativeCollection: return TableDerivativeCollection( self, root=self._root, parameter=self._parameter, depth=self._depth, ) def to_dict(self) -> Mapping[object, object]: return self._export_delegate.to_dict() def _to_df_wide(self) -> "pd.DataFrame": return self._export_delegate._to_df_wide() def _to_df_long(self) -> "pd.DataFrame": return self._export_delegate._to_df_long() def to_xarray(self) -> "XarrayDataTree": return self._export_delegate.to_xarray()
[docs] class TableCollectionDerivativeCollection: """Select derivative directions without changing table member identity.""" def __init__( self, payload: TableCollectionPayload, *, roots: Mapping[str, Mapping[object, object]] | None = None, parameter: str | None = None, depth: int = 0, ) -> None: self._payload: TableCollectionPayload = payload raw: Mapping[object, object] = payload.to_dict() self._roots: dict[str, Mapping[object, object]] = ( { str(name): cast(Mapping[object, object], table) for name, table in raw.items() if isinstance(table, Mapping) } if roots is None else dict(roots) ) self._parameter: str | None = parameter self._depth: int = depth
[docs] def keys(self) -> tuple[str, ...]: """Return solver parameter names available in at least one table. On a postprocess record's derivative collection, the names select first derivatives. After selecting a first derivative, the names select its available second derivatives. A name need not be available in every table; selecting it includes only the tables that provide it. Returns ------- tuple[str, ...] Unique parameter names in first-encounter order across the tables. The tuple is empty if no further derivative is available, including after a second derivative has been selected. """ if self._depth >= 2: return () names: dict[str, None] = {} for root in self._roots.values(): table: _TableRecordPayload = _TableRecordPayload( table=root, source=self._payload.source ) collection: TableDerivativeCollection = TableDerivativeCollection( table, root=root, parameter=self._parameter, depth=self._depth ) names.update(dict.fromkeys(collection.keys())) return tuple(names)
def __getitem__(self, name: str) -> "TableCollectionDerivativeView": """Select an available derivative from each matching collection member.""" if not isinstance(name, str): raise TypeError("Derivative names must be strings.") selected: dict[str, TableDerivativeView] = {} for member, root in self._roots.items(): table: _TableRecordPayload = _TableRecordPayload( table=root, source=self._payload.source ) derivatives: TableDerivativeCollection = TableDerivativeCollection( table, root=root, parameter=self._parameter, depth=self._depth ) if name in derivatives.keys(): selected[member] = derivatives[name] if not selected: path: str = ( f"derivatives[{self._parameter!r}].derivatives[{name!r}]" if self._parameter is not None else f"derivatives[{name!r}]" ) raise KeyError(path) selected_roots: dict[str, Mapping[object, object]] = { member: self._roots[member] for member in selected } return TableCollectionDerivativeView( payload=self._payload, members=selected, roots=selected_roots, parameter=name, depth=self._depth + 1, )
class TableCollectionDerivativeView(TableCollectionPayload): """Collection export containing only members with the selected derivative.""" def __init__( self, *, payload: TableCollectionPayload, members: Mapping[str, TableDerivativeView], roots: Mapping[str, Mapping[object, object]], parameter: str, depth: int, ) -> None: self._payload: TableCollectionPayload = payload self._members: dict[str, TableDerivativeView] = dict(members) self._roots: dict[str, Mapping[object, object]] = dict(roots) self._parameter: str = parameter self._depth: int = depth @property def source(self) -> Source: return self._payload.source @property def derivatives(self) -> TableCollectionDerivativeCollection: return TableCollectionDerivativeCollection( self._payload, roots=self._roots, parameter=self._parameter, depth=self._depth, ) def to_dict(self) -> Mapping[object, object]: return {name: view.to_dict() for name, view in self._members.items()} def _collection(self) -> TableCollection: tables: list[dict[str | int, object]] = [ cast(dict[str | int, object], dict(view.to_dict())) for view in self._members.values() ] source_file: Path | None = ( Path(self.source) if isinstance(self.source, str) else self.source ) return _NamedDerivativeTableCollection( tables, names=tuple(self._members), source_file=source_file, ) def _to_df_long(self) -> "pd.DataFrame": return self._collection().to_df() def to_xarray(self) -> "XarrayDataTree": return self._collection().to_xarray() class _NamedDerivativeTableCollection(TableCollection): """Export selected tables under their original collection member names.""" def __init__( self, tables: list[dict[str | int, object]], *, names: tuple[str, ...], source_file: Path | None, ) -> None: super().__init__(tables, source_file=source_file) self._member_names: tuple[str, ...] = names def table_names(self) -> tuple[str, ...]: """Return the member identifiers retained from the source collection.""" return self._member_names def format_postprocess_payload_preview(payload: PostprocessRecordPayload) -> str: """Return the bounded preview appropriate for one postprocess payload.""" if isinstance(payload, TablePayload): return payload._preview() if isinstance(payload, _StructuredRecordPayload): paths: list[tuple[str, object]] = flatten_payload( payload.to_dict(), path_prefix="" ) values: dict[object, object] = { "path": tuple(path for path, _ in paths), "value": tuple(value for _, value in paths), } from .internal.export.preview import format_table_preview return format_table_preview(values, quote_strings=False) if isinstance(payload, TableCollectionPayload): table_names: tuple[str, ...] = tuple(str(name) for name in payload.to_dict()) table_values: dict[object, object] = { "index": tuple(range(len(table_names))), "table": table_names, } from .internal.export.preview import format_table_preview return format_table_preview( table_values, include_row_index=False, quote_strings=False ) if isinstance(payload, FieldExportPayload): return payload._preview() return " <unsupported payload>" def payload_mapping(raw: object | None) -> Mapping[object, object] | None: """Return mapping data from a raw mapping or typed payload.""" if isinstance(raw, Mapping): return cast(Mapping[object, object], raw) if isinstance(raw, DictionaryExportMixin): return raw.to_dict() return None def is_field_export_mapping(payload_object: object | None, title: str | None) -> bool: """Return whether raw payload metadata identifies a field export.""" if isinstance(payload_object, Mapping): if any(str(mapping_key).lower() == "field" for mapping_key in payload_object): return True return title is not None and title.lower() in { "field", "fields", "fieldexport", "field_export", } def _has_structured_branch(payload: Mapping[object, object]) -> bool: value: object for value in payload.values(): if isinstance(value, Mapping): if not is_numeric_key_mapping(value) or _has_structured_branch(value): return True return False def _compatible_numeric_shapes( values: Mapping[object, object], expected: Mapping[object, object] ) -> bool: """Compare numeric leaf shapes where both tables expose the same path.""" matched_numeric_leaf: bool = False for key, value in values.items(): expected_value: object = expected.get(key) if isinstance(value, (np.ndarray, list, tuple)) and isinstance( expected_value, (np.ndarray, list, tuple) ): matched_numeric_leaf = True if np.shape(value) != np.shape(expected_value): return False elif isinstance(value, Mapping) and isinstance(expected_value, Mapping): if not _compatible_numeric_shapes(value, expected_value): return False matched_numeric_leaf = True return matched_numeric_leaf def _equivalent_derivative_payloads( first: Mapping[object, object], second: Mapping[object, object] ) -> bool: """Return whether two parsed representations contain the same pair values.""" if first.keys() != second.keys(): return False for key, first_value in first.items(): second_value: object = second[key] if isinstance(first_value, Mapping) and isinstance(second_value, Mapping): if not _equivalent_derivative_payloads(first_value, second_value): return False elif isinstance(first_value, np.ndarray) or isinstance( second_value, np.ndarray ): if not isinstance(first_value, np.ndarray) or not isinstance( second_value, np.ndarray ): return False if first_value.shape != second_value.shape: return False try: equal_values: bool = bool( np.array_equal(first_value, second_value, equal_nan=True) ) except TypeError: equal_values = bool(np.array_equal(first_value, second_value)) if not equal_values: return False elif isinstance(first_value, (list, tuple)) or isinstance( second_value, (list, tuple) ): if not isinstance(first_value, (list, tuple)) or not isinstance( second_value, type(first_value) ): return False if not _equivalent_derivative_sequences(first_value, second_value): return False elif first_value != second_value: return False return True def _equivalent_derivative_sequences( first: list[object] | tuple[object, ...], second: list[object] | tuple[object, ...] ) -> bool: if len(first) != len(second): return False for first_value, second_value in zip(first, second, strict=True): if isinstance(first_value, Mapping) and isinstance(second_value, Mapping): if not _equivalent_derivative_payloads(first_value, second_value): return False elif isinstance(first_value, np.ndarray) or isinstance( second_value, np.ndarray ): if not _equivalent_derivative_payloads( {"value": first_value}, {"value": second_value} ): return False elif isinstance(first_value, (list, tuple)) or isinstance( second_value, (list, tuple) ): if not isinstance(first_value, (list, tuple)) or not isinstance( second_value, type(first_value) ): return False if not _equivalent_derivative_sequences(first_value, second_value): return False elif first_value != second_value: return False return True def classify_payload( *, raw: object | None, source: Source, title: str | None ) -> PostprocessRecordPayload | None: """Create one typed payload from a discovered raw result value.""" if isinstance(raw, PostprocessRecordPayload): return raw if isinstance(raw, TableCollection): return _TableCollectionRecordPayload(collection=raw, source=source) if not isinstance(raw, Mapping): return None from .field_payloads import is_field_export_payload if is_field_export_mapping(raw, title) and is_field_export_payload(raw): return FieldExportPayload(mapping=raw, source=source) normalized_mapping: dict[object, object] = dict(raw) normalized_mapping.pop("title", None) normalized_mapping.pop("header", None) if payload_to_tabular_rows( normalized_mapping ) is not None and not _has_structured_branch(normalized_mapping): return _TableRecordPayload(table=raw, source=source) return _StructuredRecordPayload(mapping=raw, source=source)