# SPDX-License-Identifier: MIT
# Copyright (c) 2001-{{ COPYRIGHT_END_YEAR }} JCMwave GmbH
"""Single-result postprocess record façade."""
from __future__ import annotations
import warnings
from collections.abc import Mapping
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, cast
from ..exceptions import InvalidConfigurationError, UnsupportedExportError
from ..loaders import convert_to_powerflux
from .field_exports import FieldExportPayload
from .payloads import (
DictionaryExportMixin,
PostprocessRecordPayload,
Source,
TableCollectionPayload,
TablePayload,
XarrayExportMixin,
)
from .postprocess_payloads import (
_StructuredRecordPayload,
classify_payload,
format_postprocess_payload_preview,
is_field_export_mapping,
payload_mapping,
)
if TYPE_CHECKING:
import pandas as pd
from .artifacts import PostprocessHeader
from .internal.export.xarray.types import XarrayDataTree
from .postprocess_payloads import (
TableCollectionDerivativeCollection,
TableDerivativeCollection,
)
from .structured_derivatives import StructuredDerivativeCollection
[docs]
@dataclass(slots=True, frozen=True, repr=False)
class PostprocessRecord(DictionaryExportMixin):
"""Store and export one postprocess result."""
source_file: Source
_raw: object | None = field(repr=False)
title: str | None
payload: PostprocessRecordPayload | None = field(default=None, repr=False)
available: bool = True
failure_message: str | None = None
def __repr__(self) -> str:
status: str = (
"available"
if self.available
else (
"unavailable"
if self.failure_message is None
else f"unavailable: {self.failure_message}"
)
)
lines: list[str] = [
"PostprocessRecord(",
f" source_file: {self.source_file}",
f" title: {self.title if self.title is not None else '<untitled>'}",
f" status: {status}",
]
if self.available and self.payload is not None:
lines.append(" preview:")
lines.extend(
f" {line}"
for line in format_postprocess_payload_preview(
self.payload
).splitlines()
)
return "\n".join((*lines, ")"))
def __post_init__(self) -> None:
if self.payload is None:
typed_payload: PostprocessRecordPayload | None = classify_payload(
raw=self._raw, source=self.source_file, title=self.title
)
if typed_payload is not None:
object.__setattr__(self, "payload", typed_payload)
@property
def is_empty(self) -> bool:
return self._raw is None or not self.available
def _require_available(self) -> None:
if self.available:
return
record_label: str = (
str(self.source_file)
if self.title is None
else f"{self.title} ({self.source_file})"
)
warnings.warn(
(
f"Accessing unavailable postprocess output {record_label}"
if self.failure_message is None
else (
f"Accessing unavailable postprocess output {record_label}: "
f"{self.failure_message}"
)
),
stacklevel=2,
)
message: str = (
"Postprocess output is unavailable and cannot be accessed."
if self.failure_message is None
else f"Postprocess output is unavailable and cannot be accessed: {self.failure_message}"
)
raise InvalidConfigurationError(message)
def __setstate__(self, state: object) -> None:
values: dict[str, object] = {
"source_file": None,
"_raw": None,
"title": None,
"payload": None,
"available": True,
"failure_message": None,
}
if isinstance(state, dict):
for name, value in state.items():
if name in values:
values[name] = value
elif isinstance(state, (tuple, list)):
state_values: tuple[object, ...] = tuple(state)
names: tuple[str, ...] = (
"source_file",
"_raw",
"title",
"available",
"failure_message",
)
for index, name in enumerate(names):
if index < len(state_values):
values[name] = state_values[index]
else:
raise TypeError(
f"Unsupported pickled state for PostprocessRecord: {type(state)!r}"
)
for name, value in values.items():
object.__setattr__(self, name, value)
if values["payload"] is None:
restored: PostprocessRecordPayload | None = classify_payload(
raw=values["_raw"],
source=cast(Source, values["source_file"]),
title=cast(str | None, values["title"]),
)
if restored is not None:
object.__setattr__(self, "payload", restored)
def _unsupported(self, operation: str) -> UnsupportedExportError:
payload_name: str = (
type(self.payload).__name__
if self.payload is not None
else type(self._raw).__name__
)
return UnsupportedExportError(
f"{operation} is not supported for `{payload_name}`."
)
[docs]
def to_dict(self) -> Mapping[object, object]:
"""Return the postprocess data as a dictionary.
Returns
-------
Mapping[object, object]
Postprocess data as a dictionary that keeps the original field names.
"""
self._require_available()
if self.payload is None:
raise self._unsupported("to_dict")
return cast(DictionaryExportMixin, self.payload).to_dict()
@property
def header(self) -> "PostprocessHeader | None":
"""Return the optional header associated with this postprocess result.
Returns
-------
PostprocessHeader | None
Header data when the result contains a header. Otherwise, `None`.
"""
self._require_available()
raw_mapping: Mapping[object, object] | None = payload_mapping(self._raw)
if raw_mapping is None or not isinstance(raw_mapping.get("header"), Mapping):
return None
from .artifacts import PostprocessHeader
return PostprocessHeader(
table=cast(Mapping[object, object], raw_mapping["header"])
)
[docs]
def is_field_export(self) -> bool:
"""Return whether this record contains a Cartesian field export.
Returns
-------
bool
`True` when the record contains field data. Otherwise, `False`.
"""
return is_field_export_mapping(payload_mapping(self._raw), self.title)
@property
def fields(self) -> FieldExportPayload:
"""Return the field-export interface for this record.
Returns
-------
FieldExportPayload
Field data and field-navigation operations.
Raises
------
UnsupportedExportError
If the record does not contain field data.
"""
self._require_available()
if not isinstance(self.payload, FieldExportPayload):
raise self._unsupported("fields")
return self.payload
@property
def derivatives(
self,
) -> "TableDerivativeCollection | TableCollectionDerivativeCollection | StructuredDerivativeCollection":
"""Return parameter-derivative navigation for numeric postprocess data.
Returns
-------
TableDerivativeCollection | TableCollectionDerivativeCollection | StructuredDerivativeCollection
Name-based selection for canonical table or structured payloads.
"""
self._require_available()
if isinstance(self.payload, TablePayload):
return self.payload.derivatives
if isinstance(self.payload, TableCollectionPayload):
return self.payload.derivatives
if not isinstance(self.payload, _StructuredRecordPayload):
raise AttributeError("derivatives")
values: Mapping[object, object] = self.payload._value_mapping()
# Preserve established dynamic access for a user quantity named
# `derivatives` instead of shadowing it with the navigation view.
if "derivatives" in values:
raise AttributeError("derivatives")
from .structured_derivatives import (
StructuredDerivativeCollection,
_base_values,
_has_selected_numeric,
_parameter_branches,
)
base: Mapping[object, object] = _base_values(values)
branches: Mapping[str, Mapping[object, object]] = _parameter_branches(values)
return StructuredDerivativeCollection(
_branches={
name: branch
for name, branch in branches.items()
if _has_selected_numeric(branch, base)
},
_source=self.source_file,
_title=self.title,
_root=values,
)
[docs]
def to_df(self, orient: str | None = None) -> "pd.DataFrame":
"""Return tabular postprocess data as a pandas `DataFrame`.
Parameters
----------
orient : {None, "wide", "long"}, optional
Select the table layout. Structured and table-collection payloads
support only the long layout.
Raises
------
InvalidConfigurationError
If the record is unavailable or does not contain tabular data.
UnsupportedExportError
If the payload does not support the requested layout.
Returns
-------
pandas.DataFrame
Postprocess data in the selected layout.
"""
if orient not in {None, "wide", "long"}:
raise ValueError("orient must be None, 'wide', or 'long'")
self._require_available()
if isinstance(self.payload, TableCollectionPayload):
if orient == "wide":
raise self._unsupported("to_df")
return self.payload.to_df(orient=orient)
if self.is_field_export():
raise self._unsupported("to_df")
if isinstance(self.payload, _StructuredRecordPayload):
if orient == "wide":
raise self._unsupported("to_df")
from .internal.export.companion import require_pandas_companion
require_pandas_companion()
from jcmsuite_pandas.single import (
structured_postprocess_to_dataframe,
)
return structured_postprocess_to_dataframe(
self.payload._value_mapping(),
title=self.title,
source_file=str(self.source_file),
)
if not isinstance(self.payload, TablePayload):
raise self._unsupported("to_df")
if orient in (None, "wide"):
return self.payload.to_df(orient=orient)
values: dict[object, object] = dict(self.payload.to_dict())
values.pop("title", None)
values.pop("header", None)
from .internal.export.companion import require_pandas_companion
require_pandas_companion()
from jcmsuite_pandas.single import postprocess_payload_to_dataframe
return postprocess_payload_to_dataframe(
values,
title=self.title,
source_file=str(self.source_file),
)
[docs]
def to_xarray(self) -> "XarrayDataTree":
"""Return postprocess data as an xarray `DataTree`.
Returns
-------
xarray.DataTree
Postprocess data in an xarray tree.
"""
self._require_available()
if self.is_field_export():
return self.fields.to_xarray()
if isinstance(self.payload, TableCollectionPayload):
return self.payload.to_xarray()
if self.payload is None:
if self._raw is None:
raise InvalidConfigurationError(
"Postprocess payload is unavailable and cannot be exported via to_xarray()."
)
raise self._unsupported("to_xarray")
return cast(XarrayExportMixin, self.payload).to_xarray()
[docs]
def to_powerflux(self) -> PostprocessRecord:
"""Return a new record with field data converted to power flux.
Returns
-------
PostprocessRecord
New record containing converted postprocess data.
Raises
------
InvalidConfigurationError
If the postprocess data is not stored as named values.
"""
self._require_available()
raw_mapping: Mapping[object, object] | None = payload_mapping(self._raw)
if raw_mapping is None:
raise InvalidConfigurationError(
"Postprocess payload is not mapping-like and cannot be converted to power flux."
)
converted: dict[str, object] = convert_to_powerflux(
cast(Mapping[str, object], raw_mapping)
)
title_object: object | None = converted.get("title")
return PostprocessRecord(
source_file=self.source_file,
_raw=converted,
title=title_object if isinstance(title_object, str) else self.title,
)
def __getattr__(self, name: str) -> object:
self._require_available()
values: Mapping[object, object] = self.to_dict()
if name in values:
return values[name]
raise AttributeError(f"Postprocess mapping has no key {name!r}.")
def _field_payload_mapping(self, *, error_message: str) -> Mapping[object, object]:
self._require_available()
values: Mapping[object, object] | None = payload_mapping(self._raw)
if values is None:
raise InvalidConfigurationError(error_message)
return values