Source code for jcmsuite.results.payloads

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

"""Class-based export payload foundations for single solve results."""

from __future__ import annotations

import warnings
from abc import ABC, abstractmethod
from collections.abc import Iterator, Mapping
from pathlib import Path
from typing import TYPE_CHECKING, TypeAlias, cast

from ..exceptions import UnsupportedExportError

if TYPE_CHECKING:
    import pandas as pd

    from .internal.export.xarray.types import XarrayDataTree
    from .postprocess_payloads import (
        TableCollectionDerivativeCollection,
        TableDerivativeCollection,
    )

Source: TypeAlias = str | Path | None


[docs] class ExportablePayload(ABC): """Common provenance state for a single-result export payload.""" @property @abstractmethod def source(self) -> Source: """Return the source path or storage origin for the payload."""
[docs] class DictionaryExportMixin(ABC): """Capability for schema-faithful mapping export.""" @abstractmethod def to_dict(self) -> Mapping[object, object]: """Return the result data as a dictionary. Returns ------- Mapping[object, object] Result data as a dictionary that keeps the original field names. """ def to_mapping(self) -> Mapping[object, object]: """Return result data using the deprecated mapping export name. .. deprecated:: 7.2 Use :meth:`to_dict` instead. Returns ------- Mapping[object, object] Result data as a dictionary that keeps the original field names. """ warnings.warn( "to_mapping() is deprecated; use to_dict() instead.", DeprecationWarning, stacklevel=2, ) return self.to_dict()
[docs] class DataFrameWideExportMixin(ABC): """Capability for rectangular, wide DataFrame export.""" @abstractmethod def _to_df_wide(self) -> "pd.DataFrame": """Return a DataFrame with one column for each value name."""
[docs] class DataFrameLongExportMixin(ABC): """Capability for normalized, long DataFrame export.""" @abstractmethod def _to_df_long(self) -> "pd.DataFrame": """Return a DataFrame with one row for each named value."""
[docs] class XarrayExportMixin(ABC): """Capability for xarray tree export.""" @abstractmethod def to_xarray(self) -> "XarrayDataTree": """Return the result data as an xarray `DataTree`. Returns ------- xarray.DataTree Result data in an xarray tree. See the user documentation for xarray export details. """
[docs] class MetadataPayload( ExportablePayload, DictionaryExportMixin, DataFrameWideExportMixin, DataFrameLongExportMixin, XarrayExportMixin, ABC, ): """Base class for metadata mappings.""" def _preview(self) -> str: """Return internal bounded one-row metadata preview text. Returns ------- str A text table containing at most six metadata fields. """ from .internal.export.preview import format_mapping_preview return format_mapping_preview(self.to_dict()) def to_df(self, orient: str | None = None) -> "pd.DataFrame": """Return metadata in the requested DataFrame orientation. Metadata uses long form by default. Subclasses may support wide form when their schema has a meaningful rectangular representation. """ if orient is None or orient == "long": return self._to_df_long() if orient == "wide": return self._to_df_wide() raise ValueError("orient must be None, 'wide', or 'long'") def __repr__(self) -> str: """Return the payload class name with its bounded data preview.""" return f"{type(self).__name__}(\n preview=\n{self._preview()}\n)"
[docs] class SolveKeys(MetadataPayload, Mapping[str, object]): """Store and export the project keys for one solve. A list used as a project key remains one value. It does not create Batched project keys. Parameters ---------- values : Mapping[str, object] | None, optional project keys. If omitted, use an empty dictionary. source : Path | None, optional project file associated with the project keys. """ def __init__( self, values: Mapping[str, object] | None = None, *, source: Path | None = None, ) -> None: self._values: dict[str, object] = {} if values is None else dict(values) self._source: Path | None = source @property def source(self) -> Path | None: """Return the project path associated with these keys, if available.""" return self._source def __getitem__(self, key: str) -> object: return self._values[key] def __iter__(self) -> Iterator[str]: return iter(self._values) def __len__(self) -> int: return len(self._values)
[docs] def to_dict(self) -> Mapping[object, object]: """Return a new dictionary that contains the project keys. Returns ------- Mapping[object, object] Copy of the project keys. """ return cast(Mapping[object, object], dict(self._values))
def _preview(self) -> str: """Return internal bounded text preview with one value per project key. Returns ------- str A one-row text table containing at most six project keys. """ from .internal.export.preview import format_mapping_preview return format_mapping_preview(self._values) def __repr__(self) -> str: """Return the payload class name with its bounded data preview.""" return f"SolveKeys(\n preview=\n{self._preview()}\n)" def _to_df_wide(self) -> "pd.DataFrame": """Return one DataFrame row with one column for each project key. Returns ------- pandas.DataFrame One-row table of project keys. """ from .internal.export.companion import require_pandas_companion require_pandas_companion() from jcmsuite_pandas.keys import keys_wide return keys_wide(self._values) def _to_df_long(self) -> "pd.DataFrame": """Return one DataFrame row for each project key. The DataFrame has `key` and `value` columns. Returns ------- pandas.DataFrame Long-form table of project keys. """ from .internal.export.companion import require_pandas_companion require_pandas_companion() from jcmsuite_pandas.keys import keys_long return keys_long(self._values)
[docs] def to_df(self, orient: str | None = None) -> "pd.DataFrame": """Return the project keys as a DataFrame. Parameters ---------- orient : {"wide", "long"} | None, optional Table layout. `"wide"` gives one row with one column for each project key. `"long"` gives one row for each project key. If omitted, use `"wide"`. Returns ------- pandas.DataFrame project keys in the selected layout. Raises ------ ValueError If `orient` is not `"wide"`, `"long"`, or `None`. """ if orient is None or orient == "wide": return self._to_df_wide() if orient == "long": return self._to_df_long() raise ValueError("orient must be None, 'wide', or 'long'")
[docs] def to_xarray(self) -> "XarrayDataTree": """Return the project keys as an xarray `DataTree`. The root node stores project key values that xarray can represent. Returns ------- xarray.DataTree project keys stored as attributes on the root node. Raises ------ ValueError If a project key value cannot be stored by xarray. """ from .internal.export.companion_xarray import require_xarray_companion require_xarray_companion() from jcmsuite_xarray.single import solve_keys_to_xarray_dataset return solve_keys_to_xarray_dataset(self._values, source=self._source)
[docs] class PostprocessRecordPayload(ExportablePayload, ABC): """Payload family permitted inside a postprocess record façade."""
[docs] class TablePayload( PostprocessRecordPayload, DictionaryExportMixin, DataFrameWideExportMixin, DataFrameLongExportMixin, XarrayExportMixin, ABC, ): """Result data stored as one table.""" @property def derivatives(self) -> "TableDerivativeCollection": """Return name-based derivative navigation for numeric table values. Derivative names are solver parameter names. The selected values keep the table's quantity names and export conventions. """ from .postprocess_payloads import TableDerivativeCollection return TableDerivativeCollection(self) def _preview(self) -> str: """Return internal bounded text preview of the table values. Returns ------- str A text table containing at most five rows and six columns. """ from .internal.export.preview import format_table_preview preview_values: dict[object, object] = dict(self.to_dict()) preview_values.pop("header", None) return format_table_preview(preview_values) def __repr__(self) -> str: """Return the payload class name with its bounded data preview.""" return f"{type(self).__name__}(\n preview=\n{self._preview()}\n)"
[docs] def to_df(self, orient: str | None = None) -> "pd.DataFrame": """Return table data in the requested DataFrame orientation. Parameters ---------- orient : {"wide", "long"} | None, optional Table layout. If omitted, use the natural wide form. Returns ------- pandas.DataFrame Table data in the selected layout. Raises ------ ValueError If `orient` is not `None`, `"wide"`, or `"long"`. """ if orient is None or orient == "wide": return self._to_df_wide() if orient == "long": return self._to_df_long() raise ValueError("orient must be None, 'wide', or 'long'")
[docs] class TableCollectionPayload( PostprocessRecordPayload, DictionaryExportMixin, DataFrameLongExportMixin, XarrayExportMixin, ABC, ): """Result data stored as multiple tables with different shapes.""" @property def derivatives(self) -> "TableCollectionDerivativeCollection": """Return solver-parameter derivative navigation for collection members. Each selected view retains the original table names. Members without the requested derivative are omitted; they are never replaced or zero-filled. """ from .postprocess_payloads import TableCollectionDerivativeCollection return TableCollectionDerivativeCollection(self)
[docs] def to_df(self, orient: str | None = None) -> "pd.DataFrame": """Return the table collection in its supported long form. Parameters ---------- orient : {None, "long"}, optional Select the table layout. The collection supports only long form. Returns ------- pandas.DataFrame Table rows in long form. Raises ------ UnsupportedExportError If `orient` is `"wide"`. ValueError If `orient` is not `None` or `"long"`. """ if orient is None or orient == "long": return self._to_df_long() if orient == "wide": raise UnsupportedExportError( "to_df is not supported for wide `TableCollectionPayload`." ) raise ValueError("orient must be None, 'wide', or 'long'")
[docs] class StructuredPayload( PostprocessRecordPayload, DictionaryExportMixin, DataFrameLongExportMixin, XarrayExportMixin, ABC, ): """Deprecated base class for nested scientific payloads. No supported file-backed loader produces this family. It remains only for in-memory mappings and restored state and is marked for removal. """
[docs] def to_df(self, orient: str | None = None) -> "pd.DataFrame": """Return structured data as path/value rows. Parameters ---------- orient : str | None, optional DataFrame orientation. Use `None` or `"long"`; `"wide"` is not supported for structured data. Returns ------- pandas.DataFrame Structured data in path/value rows. """ if orient is None or orient == "long": return self._to_df_long() if orient == "wide": raise UnsupportedExportError( "to_df is not supported for wide `StructuredPayload`." ) raise ValueError("orient must be None, 'wide', or 'long'")
class FieldExportPayload( PostprocessRecordPayload, DictionaryExportMixin, XarrayExportMixin, ABC ): """Base class for non-tabular field payloads."""