# SPDX-License-Identifier: MIT
# Copyright (c) 2001-{{ COPYRIGHT_END_YEAR }} JCMwave GmbH
"""Postprocess-specific batch result view helpers."""
from __future__ import annotations
from collections.abc import Callable, Mapping
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Protocol, Self, cast
from ....exceptions import InvalidConfigurationError, UnsupportedExportError
from ...artifacts import PostprocessCollection, PostprocessHeader, PostprocessRecord
from ...field_exports import FieldExportPayload, FieldExportView
from ...field_payloads import resolve_coordinates
from ...payloads import (
DataFrameLongExportMixin,
DictionaryExportMixin,
Source,
StructuredPayload,
TableCollectionPayload,
TablePayload,
)
from ..export.pandas.payload import flatten_payload
from ..export.xarray.types import XarrayDataTree
from .batch import (
BatchExportRecord,
BatchFieldPayloadBase,
BatchMetadataPayload,
BatchStructuredPayload,
BatchTableCollectionPayload,
BatchTablePayload,
)
if TYPE_CHECKING:
import pandas as pd # pyright: ignore[reportMissingImports]
from jcmsuite_xarray.runtime import _DataTreeModule, _XarrayModule
class _XarrayExportLoaderModule(Protocol):
"""Typed access to the historical xarray_export loader seam."""
def _load_xarray_module(self) -> _XarrayModule: ...
def _load_datatree_module(self) -> _DataTreeModule: ...
[docs]
@dataclass(slots=True, frozen=True, repr=False)
class BatchPostprocessCollection:
"""Select one postprocess result across a batch.
Parameters
----------
records : tuple[BatchExportRecord, ...]
Postprocess results in batched project keys order.
Notes
-----
Application code receives this collection from
`BatchSolveResult.postprocesses`; it does not need to construct the
collection directly.
Select a postprocess result by its integer position. Export data from the
returned `BatchPostprocessRecord`.
"""
records: tuple[BatchExportRecord, ...]
def __repr__(self) -> str:
"""Return indexed streams with aligned batch availability states."""
from ..export.preview import format_table_preview
stream_count: int = max(
(
len(record.payload)
for record in self.records
if isinstance(record.payload, PostprocessCollection)
),
default=0,
)
titles_preview: list[str] = []
entries_preview: list[int] = []
available_preview: list[int] = []
missing_preview: list[int] = []
status_preview: list[str] = []
for index in range(stream_count):
titles: set[str] = set()
available_count: int = 0
for record in self.records:
if not isinstance(record.payload, PostprocessCollection):
continue
if not 0 <= index < len(record.payload):
continue
selected: PostprocessRecord = record.payload[index]
titles.add("<untitled>" if selected.title is None else selected.title)
if selected.available:
available_count += 1
title: str = (
"<untitled>"
if not titles
else next(iter(titles)) if len(titles) == 1 else "<mixed>"
)
missing_count: int = len(self.records) - available_count
status: str = (
"available"
if missing_count == 0
else "unavailable" if available_count == 0 else "partial"
)
titles_preview.append(title)
entries_preview.append(len(self.records))
available_preview.append(available_count)
missing_preview.append(missing_count)
status_preview.append(status)
preview_values: dict[object, object] = {
"index": list(range(stream_count)),
"title": titles_preview,
"entries": entries_preview,
"available": available_preview,
"missing": missing_preview,
"status": status_preview,
}
preview: str = format_table_preview(
preview_values,
include_row_index=False,
quote_strings=False,
)
return f"BatchPostprocessCollection(\n{preview}\n)"
[docs]
def titles(self) -> tuple[str, ...]:
"""Return postprocess titles from the first available batch entry.
Returns
-------
tuple[str, ...]
Titles in postprocess order. Duplicate titles remain in the result.
An empty batch or a batch without a successful entry returns an
empty tuple.
"""
record: BatchExportRecord
for record in self.records:
if isinstance(record.payload, PostprocessCollection):
return record.payload.titles()
return ()
[docs]
def __getitem__(
self, selector: int
) -> BatchPostprocessRecord | _BatchPostprocessSelection:
"""Select one postprocess result across the batch.
Parameters
----------
selector : int
Postprocess position shared across all batch entries. Negative
positions are not supported.
Returns
-------
BatchPostprocessRecord | _BatchPostprocessSelection
Batch record when available entries have compatible result data.
Older result data can return a read-only selection with the same
export operations.
Raises
------
TypeError
If `selector` is not an integer or is a Boolean value.
InvalidConfigurationError
If available entries have incompatible result data.
"""
if isinstance(selector, bool):
raise TypeError("Postprocess selector must be int, not bool.")
if isinstance(selector, int):
try:
return _build_batch_postprocess_record(self.records, selector)
except InvalidConfigurationError as exc:
if "field payloads are deferred" in str(exc):
return _BatchPostprocessSelection(
records=self.records, index=selector
)
if "payload families" in str(exc) or "schemas" in str(exc):
raise
return _BatchPostprocessSelection(records=self.records, index=selector)
raise TypeError("Postprocess selector must be int.")
@dataclass(slots=True, frozen=True, repr=False)
class _BatchPostprocessTablePayload(BatchTablePayload):
"""Aligned table payload for one homogeneous postprocess stream."""
records: tuple[BatchExportRecord, ...]
postprocess_index: int
def __post_init__(self) -> None:
sources: tuple[Source, ...] = tuple(record.source for record in self.records)
object.__setattr__(self, "_sources", sources)
@property
def sources(self) -> tuple[Source, ...]:
"""Return source paths aligned with the current batch entries."""
return self._sources
def to_dict(self) -> Mapping[object, object]:
"""Return available table mappings keyed by original batch index."""
return {
record.index: cast(DictionaryExportMixin, record.payload).to_dict()
for record in self.records
if record.payload is not None
}
def _to_df_long(self) -> pd.DataFrame:
"""Export available table rows with batch and postprocess identity."""
from ...pandas_export import _load_pandas_module
from ..export.companion import require_pandas_companion
require_pandas_companion()
from jcmsuite_pandas.batch_postprocess import (
batch_postprocess_table_payload_to_df,
)
return batch_postprocess_table_payload_to_df(
self.records, self.postprocess_index, _load_pandas_module
)
def to_xarray(self) -> XarrayDataTree:
"""Export aligned tables with validity and padding masks."""
available_mapping: Mapping[object, object] | None = next(
(
cast(DictionaryExportMixin, record.payload).to_dict()
for record in self.records
if record.payload is not None
),
None,
)
if available_mapping is None:
raise InvalidConfigurationError(
"No batch postprocess payloads are available for to_xarray()."
)
from ..export.companion_xarray import require_xarray_companion
require_xarray_companion()
from jcmsuite_xarray import export as xarray_export_module
from jcmsuite_xarray.export import (
_stack_batch_postprocess_payloads_to_data_tree,
)
loader = cast(_XarrayExportLoaderModule, xarray_export_module)
payloads: list[Mapping[object, object]] = []
availability: list[bool] = []
for record in self.records:
if record.payload is None:
payloads.append(_nan_structure(available_mapping))
availability.append(False)
else:
payloads.append(cast(DictionaryExportMixin, record.payload).to_dict())
availability.append(True)
return _stack_batch_postprocess_payloads_to_data_tree(
self.records,
payloads,
index=self.postprocess_index,
title=None,
xarray_module=loader._load_xarray_module(),
datatree_module=loader._load_datatree_module(),
batch_axis_name="batch_index",
available=availability,
)
@dataclass(slots=True, frozen=True)
class _BatchStructuredPayload(BatchStructuredPayload):
"""Aligned structured payload for one homogeneous postprocess stream."""
records: tuple[BatchExportRecord, ...]
postprocess_index: int
def __post_init__(self) -> None:
object.__setattr__(
self, "_sources", tuple(record.source for record in self.records)
)
@property
def sources(self) -> tuple[Source, ...]:
"""Return source paths aligned with current batch entries."""
return self._sources
def to_dict(self) -> Mapping[object, object]:
"""Return available structured mappings keyed by batch index."""
return {
record.index: cast(DictionaryExportMixin, record.payload).to_dict()
for record in self.records
if record.payload is not None
}
def _to_df_long(self) -> pd.DataFrame:
"""Export structured paths with batch and postprocess identity."""
from ...pandas_export import _load_pandas_module
from ..export.companion import require_pandas_companion
require_pandas_companion()
from jcmsuite_pandas.batch_postprocess import (
batch_postprocess_structured_payload_to_df,
)
return batch_postprocess_structured_payload_to_df(
self.records, self.postprocess_index, _load_pandas_module
)
def to_xarray(self) -> XarrayDataTree:
"""Export the structured tree with batch availability masks."""
available_payload: Mapping[object, object] | None = next(
(
cast(DictionaryExportMixin, record.payload).to_dict()
for record in self.records
if record.payload is not None
),
None,
)
if available_payload is None:
raise InvalidConfigurationError(
"No structured batch postprocess payloads are available for to_xarray()."
)
from ..export.companion_xarray import require_xarray_companion
require_xarray_companion()
from jcmsuite_xarray import export as xarray_export_module
from jcmsuite_xarray.export import (
_stack_batch_postprocess_payloads_to_data_tree,
)
payloads: list[Mapping[object, object]] = []
availability: list[bool] = []
for record in self.records:
if record.payload is None:
payloads.append(_nan_structure(available_payload))
availability.append(False)
else:
payloads.append(cast(DictionaryExportMixin, record.payload).to_dict())
availability.append(True)
loader = cast(_XarrayExportLoaderModule, xarray_export_module)
return _stack_batch_postprocess_payloads_to_data_tree(
self.records,
payloads,
index=self.postprocess_index,
title=None,
xarray_module=loader._load_xarray_module(),
datatree_module=loader._load_datatree_module(),
batch_axis_name="batch_index",
available=availability,
)
def _nan_structure(payload: Mapping[object, object]) -> Mapping[object, object]:
"""Create a schema-preserving NaN placeholder for an unavailable entry."""
import numpy as np
result: dict[object, object] = {}
for key, value in payload.items():
if isinstance(value, Mapping):
result[key] = _nan_structure(value)
elif isinstance(value, np.ndarray):
result[key] = np.full(value.shape, np.nan)
elif isinstance(value, (int, float, complex)):
result[key] = np.nan
else:
result[key] = value
return result
@dataclass(slots=True, frozen=True)
class _BatchTableCollectionPayload(BatchTableCollectionPayload):
"""Aligned collection of named batch table payloads."""
records: tuple[BatchExportRecord, ...]
postprocess_index: int
def __post_init__(self) -> None:
object.__setattr__(
self, "_sources", tuple(record.source for record in self.records)
)
@property
def sources(self) -> tuple[Source, ...]:
"""Return source paths aligned with current batch entries."""
return self._sources
def to_dict(self) -> Mapping[object, object]:
"""Return available child-table mappings keyed by batch index."""
return {
record.index: cast(DictionaryExportMixin, record.payload).to_dict()
for record in self.records
if record.payload is not None
}
def _to_df_long(self) -> pd.DataFrame:
"""Export child tables with batch, table, and row identity."""
from ...pandas_export import _load_pandas_module
from ..export.companion import require_pandas_companion
require_pandas_companion()
from jcmsuite_pandas.batch_postprocess import (
batch_postprocess_collection_payload_to_df,
)
return batch_postprocess_collection_payload_to_df(
self.records,
self.postprocess_index,
self._table_names(),
_load_pandas_module,
)
def to_xarray(self) -> XarrayDataTree:
"""Export named child tables as batch-aligned xarray nodes."""
names = self._table_names()
from ..export.companion_xarray import require_xarray_companion
require_xarray_companion()
from jcmsuite_xarray import export as xarray_export_module
from jcmsuite_xarray.runtime import _create_data_tree
from jcmsuite_xarray.tabular import (
_stack_batch_tabular_tables,
tabular_payload_to_xarray_table,
)
loader = cast(_XarrayExportLoaderModule, xarray_export_module)
children: dict[str, XarrayDataTree] = {}
for table_name in names:
first_table = self._first_table(table_name)
tables = []
valid: list[bool] = []
for record in self.records:
table = (
None
if record.payload is None
else cast(DictionaryExportMixin, record.payload)
.to_dict()
.get(table_name)
)
if not isinstance(table, Mapping):
tables.append(
tabular_payload_to_xarray_table(
_nan_table(first_table), payload_name="Batch table"
)
)
valid.append(False)
else:
tables.append(
tabular_payload_to_xarray_table(
table, payload_name="Batch table"
)
)
valid.append(True)
dataset = _stack_batch_tabular_tables(
self.records,
tables,
xarray_module=loader._load_xarray_module(),
batch_axis_name="batch_index",
valid_entries=valid,
)
children[table_name] = _create_data_tree(
datatree_module=loader._load_datatree_module(),
dataset=dataset,
name=table_name,
)
root = loader._load_xarray_module().Dataset(
data_vars={}, attrs={"tables": names, "table_count": len(names)}
)
return _create_data_tree(
datatree_module=loader._load_datatree_module(),
dataset=root,
children=children,
)
def _table_names(self) -> tuple[str, ...]:
for record in self.records:
if record.payload is not None:
return tuple(
str(name)
for name in cast(DictionaryExportMixin, record.payload).to_dict()
)
raise InvalidConfigurationError("No table-collection payloads are available.")
def _first_table(self, table_name: str) -> Mapping[object, object]:
for record in self.records:
if record.payload is not None:
table = cast(DictionaryExportMixin, record.payload).to_dict()[
table_name
]
if isinstance(table, Mapping):
return table
raise InvalidConfigurationError(f"Table {table_name!r} is unavailable.")
def _nan_table(table: Mapping[object, object]) -> Mapping[object, object]:
"""Return a schema-preserving NaN table for an unavailable entry."""
import numpy as np
return {
key: (
np.full(value.shape, np.nan)
if isinstance(value, np.ndarray)
else np.nan if isinstance(value, (int, float, complex)) else value
)
for key, value in table.items()
}
@dataclass(slots=True, frozen=True, repr=False)
class _BatchFieldViewPayload(BatchFieldPayloadBase):
"""Store and export field data for a batch.
Parameters
----------
records : tuple[BatchExportRecord, ...]
Field data in batch order.
postprocess_index : int
Position of the postprocess result in each project result.
Notes
-----
Application code receives this object from `BatchPostprocessRecord.fields`;
it does not need to construct the object directly.
"""
records: tuple[BatchExportRecord, ...]
postprocess_index: int
def __post_init__(self) -> None:
object.__setattr__(
self, "_sources", tuple(record.source for record in self.records)
)
@property
def sources(self) -> tuple[Source, ...]:
"""Return one source file for each batch entry.
An unavailable source file is `None`. The order matches the current
batch entries.
Returns
-------
tuple[Path | None, ...]
Source files in batched project keys order.
"""
return self._sources
def _project_fields(
self, projection: Callable[[FieldExportView], FieldExportView]
) -> Self:
"""Apply one field projection without changing batch entry alignment."""
projected_records: tuple[BatchExportRecord, ...] = tuple(
BatchExportRecord(
index=record.index,
keys=dict(record.keys),
payload=(
None
if not isinstance(record.payload, FieldExportView)
else projection(record.payload)
),
source=record.source,
)
for record in self.records
)
return type(self)(
records=projected_records,
postprocess_index=self.postprocess_index,
)
def to_dict(self) -> Mapping[object, object]:
"""Return one field dictionary for each available batch entry.
Returns
-------
Mapping[object, object]
Field dictionaries indexed by their original batch positions.
"""
exported: dict[object, object] = {}
for record in self.records:
if record.payload is None:
continue
mapping: dict[object, object] = dict(
cast(DictionaryExportMixin, record.payload).to_dict()
)
field_value: object = mapping.get("field")
if field_value is not None and not isinstance(field_value, (list, tuple)):
mapping["field"] = [field_value]
exported[record.index] = mapping
return exported
def to_xarray(self) -> XarrayDataTree:
"""Return the batch field data as an xarray `DataTree`.
The root node contains the selected fields. Derivatives are in child
nodes. `batch_index` contains the original batch positions.
Returns
-------
xarray.DataTree
Batch field data with validity and padding information.
Raises
------
InvalidConfigurationError
If no field data is available or the field shapes cannot be
combined.
"""
available = [record.payload is not None for record in self.records]
trees: list[XarrayDataTree] = []
first_payload: FieldExportView | None = None
for record in self.records:
if isinstance(record.payload, FieldExportView):
first_payload = record.payload
break
if first_payload is None:
raise InvalidConfigurationError(
"No field batch postprocess payloads are available for to_xarray()."
)
from ..export.companion_xarray import require_xarray_companion
require_xarray_companion()
from jcmsuite_xarray import export as xarray_export_module
from jcmsuite_xarray.export import stack_batch_field_trees
loader = cast(_XarrayExportLoaderModule, xarray_export_module)
for record in self.records:
payload = record.payload
if not isinstance(payload, FieldExportView):
payload = first_payload
trees.append(payload.to_xarray())
return stack_batch_field_trees(
trees,
available=available,
batch_indices=[record.index for record in self.records],
xarray_module=loader._load_xarray_module(),
datatree_module=loader._load_datatree_module(),
)
[docs]
@dataclass(slots=True, frozen=True, repr=False)
class BatchFieldExportPayload(_BatchFieldViewPayload):
"""Store and export transformable field data for a batch."""
@property
def intensity(self) -> "BatchIntensityFieldExportPayload":
"""Return the squared-norm intensity view for available fields.
Returns
-------
BatchIntensityFieldExportPayload
Non-transformable field-intensity view. The view retains batch
entry identity, availability information, and field navigation.
"""
projected: _BatchFieldViewPayload = self._project_fields(
lambda field: cast(FieldExportPayload, field).intensity
)
return BatchIntensityFieldExportPayload(
records=projected.records,
postprocess_index=self.postprocess_index,
)
[docs]
@dataclass(slots=True, frozen=True, repr=False)
class BatchIntensityFieldExportPayload(_BatchFieldViewPayload):
"""Store and export squared-norm field intensity across a batch.
:attr:`BatchFieldExportPayload.intensity` returns this payload. Each
available entry contains real-valued intensity fields, identified by its original
batch index. The payload supports base-field and field-position selection,
dictionary export, and xarray export. It does not support further intensity
or field transforms. Solver derivative access is not available for intensity
values.
Do not construct this payload directly.
"""
@property
def derivatives(self) -> Self:
"""Reject solver-derivative access for intensity fields.
Returns
-------
Self
This property does not return.
Raises
------
UnsupportedExportError
Always. Intensity fields do not expose solver derivatives.
"""
raise UnsupportedExportError(
"Derivatives are not available for intensity field views."
)
[docs]
@dataclass(slots=True, frozen=True, repr=False)
class BatchPostprocessRecord(DictionaryExportMixin):
"""Provide one type of postprocess result across a batch.
Parameters
----------
records : tuple[BatchExportRecord, ...]
Postprocess results in batched project keys order.
index : int
Position of the selected postprocess result in each project result.
payload : BatchTablePayload | BatchStructuredPayload | BatchTableCollectionPayload | BatchFieldExportPayload
Data for the selected postprocess result.
Notes
-----
Application code receives this object after selecting a batch postprocess
result; it does not need to construct the object directly.
Available entries must contain the same type and structure of result data.
"""
records: tuple[BatchExportRecord, ...]
index: int
payload: (
BatchTablePayload
| BatchStructuredPayload
| BatchTableCollectionPayload
| BatchFieldExportPayload
)
def __repr__(self) -> str:
"""Return stream identity, availability, and a payload preview."""
titles: set[str] = set()
available_count: int = 0
for record in self.records:
if not isinstance(record.payload, PostprocessCollection):
continue
if not 0 <= self.index < len(record.payload):
continue
selected: PostprocessRecord = record.payload[self.index]
titles.add("<untitled>" if selected.title is None else selected.title)
if selected.available:
available_count += 1
title: str = (
"<untitled>"
if not titles
else next(iter(titles)) if len(titles) == 1 else "<mixed>"
)
missing_count: int = len(self.records) - available_count
status: str = (
"available"
if missing_count == 0
else "unavailable" if available_count == 0 else "partial"
)
lines: list[str] = [
"BatchPostprocessRecord(",
f" index: {self.index}",
f" title: {title}",
f" status: {status} ({available_count}/{len(self.records)})",
]
if isinstance(self.payload, (BatchTablePayload, BatchFieldExportPayload)):
lines.append(" preview:")
lines.extend(f" {line}" for line in self.payload._preview().splitlines())
return "\n".join((*lines, ")"))
@property
def sources(self) -> tuple[Source, ...]:
"""Return one source file for each batch entry.
An unavailable source file is `None`. The order matches the Batched
project keys.
Returns
-------
tuple[Path | None, ...]
Source files in batched project keys order.
"""
return self.payload.sources
[docs]
def is_field_export(self) -> bool:
"""Check whether the selected postprocess result contains field data.
Returns
-------
bool
`True` if the result contains field data. Otherwise, `False`.
"""
return isinstance(self.payload, BatchFieldExportPayload)
@property
def header(self) -> BatchMetadataPayload:
"""Return the postprocess headers in batched project keys order.
Returns
-------
BatchMetadataPayload
Header information for each batch entry.
"""
header_records: list[BatchExportRecord] = []
record: BatchExportRecord
for record in self.records:
header_mapping: dict[str, object] = {}
if isinstance(
record.payload, PostprocessCollection
) and 0 <= self.index < len(record.payload):
selected = record.payload[self.index]
header = selected.header
if header is not None:
header_mapping = {
str(key): value for key, value in header.to_dict().items()
}
header_records.append(
BatchExportRecord(
index=record.index,
keys=header_mapping,
source=(
None
if not isinstance(record.payload, PostprocessCollection)
or not 0 <= self.index < len(record.payload)
else record.payload[self.index].source_file
),
)
)
return BatchPostprocessHeaderPayload(
tuple(header_records), source_records=self.records, index=self.index
)
[docs]
def to_dict(self) -> Mapping[object, object]:
"""Return result dictionaries for the available batch entries.
Returns
-------
Mapping[object, object]
Result dictionaries indexed by their original batch positions.
"""
return cast(DictionaryExportMixin, self.payload).to_dict()
[docs]
def to_df(self, orient: str | None = None) -> pd.DataFrame:
"""Return the selected batch postprocess stream as a DataFrame.
Parameters
----------
orient : {None, "wide", "long"}, optional
Select the table layout. Batch postprocess data supports only the
long layout. `None` selects the long layout.
Returns
-------
pandas.DataFrame
Selected postprocess data in long form.
Raises
------
UnsupportedExportError
If the selected postprocess contains field data or `orient` is
`"wide"`.
ValueError
If `orient` is not `None`, `"wide"`, or `"long"`.
"""
if orient not in (None, "wide", "long"):
raise ValueError("orient must be None, 'wide', or 'long'")
if isinstance(self.payload, BatchFieldExportPayload):
raise UnsupportedExportError(
"to_df is not supported for `BatchFieldExportPayload`."
)
if orient == "wide":
raise UnsupportedExportError(
"to_df is not supported for wide batch postprocess exports."
)
return self.payload.to_df(orient="long")
def _to_df_long(self) -> pd.DataFrame:
"""Return available result data as a long-form DataFrame.
Returns
-------
pandas.DataFrame
Rows that include the original batch position and postprocess
position.
Raises
------
UnsupportedExportError
If the selected postprocess result contains field data.
"""
if isinstance(self.payload, BatchFieldExportPayload):
raise UnsupportedExportError(
"to_df is not supported for `BatchFieldExportPayload`."
)
return cast(DataFrameLongExportMixin, self.payload)._to_df_long()
[docs]
def to_xarray(self) -> XarrayDataTree:
"""Return the selected batch result as an xarray `DataTree`.
Returns
-------
xarray.DataTree
Result data in batched project keys order.
Raises
------
InvalidConfigurationError
If available result data cannot be combined in one tree.
"""
payload_mapping: Mapping[object, object] = cast(
DictionaryExportMixin, self.payload
).to_dict()
is_powerflux: bool = any(
isinstance(table, Mapping)
and any("PowerFluxDensity" in str(key) for key in table)
for table in payload_mapping.values()
)
if is_powerflux:
# Preserve the established PowerFlux tree topology while the
# record keeps the BatchPostprocessRecord return type.
return _BatchPostprocessSelection(
records=self.records, index=self.index
).to_xarray()
return self.payload.to_xarray()
[docs]
def to_powerflux(self) -> BatchPostprocessRecord:
"""Convert the selected result to PowerFlux data.
Returns
-------
BatchPostprocessRecord
Converted data in batched project keys order.
Raises
------
InvalidConfigurationError
If an available entry does not contain the required Fourier table
data.
"""
converted_records: list[BatchExportRecord] = []
batch_record: BatchExportRecord
for batch_record in self.records:
payload: PostprocessCollection | None = None
if isinstance(batch_record.payload, PostprocessCollection):
collection: PostprocessCollection = batch_record.payload
if 0 <= self.index < len(collection):
converted_record: PostprocessRecord = collection[
self.index
].to_powerflux()
converted_collection_records: tuple[PostprocessRecord, ...] = (
*collection.records[: self.index],
converted_record,
)
payload = PostprocessCollection(
records=converted_collection_records
)
else:
payload = collection
converted_records.append(
BatchExportRecord(
index=batch_record.index,
keys=dict(batch_record.keys),
payload=payload,
source=batch_record.source,
)
)
return _build_batch_postprocess_record(tuple(converted_records), self.index)
@property
def fields(self) -> BatchFieldExportPayload:
"""Return field data for the selected batch result.
Returns
-------
BatchFieldExportPayload
Field data in batched project keys order.
Raises
------
UnsupportedExportError
If the selected postprocess result does not contain field data.
"""
if isinstance(self.payload, BatchFieldExportPayload):
return self.payload
raise UnsupportedExportError(
f"fields is not supported for `{type(self.payload).__name__}`."
)
class BatchPostprocessHeaderPayload(BatchMetadataPayload):
"""Batch metadata payload retaining the selected-header export seam."""
def __init__(
self,
records: tuple[BatchExportRecord, ...],
*,
source_records: tuple[BatchExportRecord, ...],
index: int,
) -> None:
super().__init__(records)
self._source_records = source_records
self._index = index
def to_xarray(self) -> XarrayDataTree:
"""Export selected headers with the established xarray schema."""
from ..export.companion_xarray import require_xarray_companion
require_xarray_companion()
from jcmsuite_xarray.export import (
batch_selected_postprocess_headers_to_xarray_dataset,
)
return batch_selected_postprocess_headers_to_xarray_dataset(
self._source_records, index=self._index
)
def _build_batch_postprocess_record(
records: tuple[BatchExportRecord, ...], index: int
) -> BatchPostprocessRecord:
"""Normalize one selected stream and reject family/schema mismatches."""
selected_records: list[BatchExportRecord] = []
first_family: str | None = None
first_schema: tuple[object, ...] | None = None
for batch_record in records:
selected: PostprocessRecord | None = None
if isinstance(batch_record.payload, PostprocessCollection) and 0 <= index < len(
batch_record.payload
):
selected = batch_record.payload[index]
payload: object | None = None
if selected is not None and selected.available:
schema: tuple[object, ...]
if isinstance(selected.payload, TableCollectionPayload):
family = "collection"
collection_mapping = cast(
DictionaryExportMixin, selected.payload
).to_dict()
schema = tuple(
(str(name), tuple(cast(Mapping[object, object], table)))
for name, table in collection_mapping.items()
)
elif isinstance(selected.payload, TablePayload):
family = "table"
schema = tuple(
str(key)
for key in cast(DictionaryExportMixin, selected.payload).to_dict()
)
elif isinstance(selected.payload, StructuredPayload):
family = "structured"
schema = tuple(
path
for path, _ in flatten_payload(
cast(DictionaryExportMixin, selected.payload).to_dict(),
path_prefix="",
)
)
elif isinstance(selected.payload, FieldExportPayload):
family = "field"
schema = _field_schema(selected.payload)
else:
raise InvalidConfigurationError(
"Selected batch postprocess stream mixes incompatible payload families."
)
payload = selected.payload
if first_family is None:
first_family = family
first_schema = schema
elif family != first_family or schema != first_schema:
raise InvalidConfigurationError(
"Selected batch postprocess stream mixes incompatible payload schemas."
)
selected_records.append(
BatchExportRecord(
index=batch_record.index,
keys=dict(batch_record.keys),
payload=payload,
source=(None if selected is None else selected.source_file),
)
)
if first_family is None:
raise InvalidConfigurationError(
f"No supported postprocess records found for index {index!r}."
)
payload_type: type[
BatchTablePayload
| BatchStructuredPayload
| BatchTableCollectionPayload
| BatchFieldExportPayload
]
if first_family == "table":
payload_type = _BatchPostprocessTablePayload
elif first_family == "structured":
payload_type = _BatchStructuredPayload
elif first_family == "collection":
payload_type = _BatchTableCollectionPayload
else:
payload_type = BatchFieldExportPayload
payload_object: (
BatchTablePayload
| BatchStructuredPayload
| BatchTableCollectionPayload
| BatchFieldExportPayload
) = payload_type(tuple(selected_records), postprocess_index=index)
return BatchPostprocessRecord(
records=records,
index=index,
payload=payload_object,
)
def _field_schema(payload: FieldExportPayload) -> tuple[object, ...]:
"""Return the compatible field topology without fixing varying axis sizes."""
import numpy as np
base_mapping: Mapping[object, object] = payload.base.to_dict()
coordinate_topology = resolve_coordinates(base_mapping)
coordinate_names: tuple[str, ...] = coordinate_topology.names
coordinate_ranks: tuple[int, ...] = tuple(
int(np.asarray(base_mapping[name]).ndim) for name in coordinate_names
)
field_value: object = base_mapping["field"]
field_entries: tuple[object, ...] = (
tuple(field_value) if isinstance(field_value, (list, tuple)) else (field_value,)
)
field_ranks: tuple[int, ...] = tuple(
int(np.asarray(entry).ndim) for entry in field_entries
)
base_names: tuple[str, ...] = tuple(
str(name)
for name in base_mapping
if name not in {*coordinate_names, "field", "title"}
)
# Solver derivative availability is entry-specific. Batch navigation keeps
# each payload intact and performs derivative lookup per original index, so
# derivative branch differences do not make otherwise compatible field
# topologies incompatible.
return (
coordinate_names,
coordinate_ranks,
base_names,
len(field_entries),
field_ranks,
)
@dataclass(slots=True, frozen=True)
class _BatchPostprocessSelection(DictionaryExportMixin):
"""Selected batch postprocess dataframe accessor.
Notes
-----
Internal API: fallback helper for streams that cannot be normalized into a
typed ``BatchPostprocessRecord``.
This view is DataFrame-first: use ``to_df(...)`` for aligned batch exports.
It intentionally does not expose a dense numeric ``values`` vector because
selected payloads can be heterogeneous across entries.
"""
records: tuple[BatchExportRecord, ...]
index: int
_resolved_records: tuple[_ResolvedBatchPostprocessRecord, ...] | None = field(
default=None,
repr=False,
)
def to_dict(self) -> Mapping[object, object]:
"""Return the selected postprocess payloads keyed by batch entry index."""
selected_mapping: dict[object, object] = {}
resolved_record: _ResolvedBatchPostprocessRecord
for resolved_record in self._resolve_selected_records():
payload_mapping: Mapping[object, object] | None = (
resolved_record.record.to_dict()
)
selected_mapping[resolved_record.entry.index] = payload_mapping
return selected_mapping
@property
def header(self) -> _BatchPostprocessHeaderSelection:
"""Return a selected batch-postprocess header export view."""
return _BatchPostprocessHeaderSelection(
records=self.records,
index=self.index,
_resolved_records=self._resolve_selected_records(),
)
def to_df(
self,
*,
orient: str | None = None,
warn_skipped: bool = True,
expand_rows: bool = False,
) -> pd.DataFrame:
"""Export selected batch postprocess values as a DataFrame.
Parameters
----------
warn_skipped : bool, optional
Emit warnings when non-tabular or field-export payloads are skipped.
expand_rows : bool, optional
Compatibility flag retained for API stability. Postprocess dataframe
exports now use the same long-form row model regardless of this value.
Returns
-------
pandas.DataFrame
DataFrame export for the selected batch postprocess stream.
"""
if orient not in (None, "wide", "long"):
raise ValueError("orient must be None, 'wide', or 'long'")
if orient == "wide":
raise UnsupportedExportError(
"to_df is not supported for wide batch postprocess exports."
)
if self._resolved_records is not None:
from ...pandas_export import _load_pandas_module
from ..export.companion import require_pandas_companion
require_pandas_companion()
from jcmsuite_pandas.batch_postprocess import (
selected_batch_postprocess_to_df,
)
return selected_batch_postprocess_to_df(
self._resolved_records, _load_pandas_module()
)
from ...pandas_export import batch_postprocesses_to_df
return batch_postprocesses_to_df(
self.records,
index=self.index,
warn_skipped=warn_skipped,
expand_rows=expand_rows,
)
def to_xarray(self) -> XarrayDataTree:
"""Export the selected batch postprocess stream as one `DataTree`.
Returns
-------
xarray.DataTree
Uniform stacked tree with leading ``index`` dimension inside each
node dataset plus the grouped postprocess dimensions inherited from
``PostprocessRecord.to_xarray()``.
Raises
------
InvalidConfigurationError
If the selected stream is missing on a successful batch entry, or
the grouped payloads cannot be stacked under one tensor contract.
"""
if self._resolved_records is not None:
from ..export.companion_xarray import require_xarray_companion
require_xarray_companion()
from jcmsuite_xarray import export as _xarray_export_module
from jcmsuite_xarray.export import (
_record_xarray_payload,
_stack_batch_postprocess_payloads_to_data_tree,
)
xarray_export_module = cast(
_XarrayExportLoaderModule,
_xarray_export_module,
)
xarray_module = xarray_export_module._load_xarray_module()
datatree_module = xarray_export_module._load_datatree_module()
selected_entries: list[BatchExportRecord] = []
payloads: list[Mapping[object, object]] = []
selected_title: str | None = None
resolved_record: _ResolvedBatchPostprocessRecord
for resolved_record in self._resolved_records:
postprocess_record = resolved_record.record
if not postprocess_record.available:
raise InvalidConfigurationError(
f"Selected postprocess index {resolved_record.postprocess_index!r} is unavailable for batch entry {resolved_record.entry.index}."
)
if selected_title is None:
selected_title = postprocess_record.title
payload_object: object = _record_xarray_payload(postprocess_record)
if not isinstance(payload_object, Mapping):
raise InvalidConfigurationError(
"Postprocess payload is not mapping-like and cannot be exported via to_xarray()."
)
payloads.append(payload_object)
selected_entries.append(resolved_record.entry)
if not payloads:
raise InvalidConfigurationError(
"No successful batch entries with the selected postprocess payload are available for to_xarray()."
)
return _stack_batch_postprocess_payloads_to_data_tree(
selected_entries,
payloads,
index=self.index,
title=selected_title,
xarray_module=xarray_module,
datatree_module=datatree_module,
)
from ..export.companion_xarray import require_xarray_companion
require_xarray_companion()
from jcmsuite_xarray.export import (
batch_selected_postprocesses_to_xarray_dataset,
)
return batch_selected_postprocesses_to_xarray_dataset(
self.records,
index=self.index,
)
def to_powerflux(self) -> _BatchPostprocessSelection:
"""Convert the selected batch postprocess stream to power-flux records."""
resolved_records: tuple[_ResolvedBatchPostprocessRecord, ...] = (
self._resolve_selected_records()
)
converted_records: list[_ResolvedBatchPostprocessRecord] = []
resolved_record: _ResolvedBatchPostprocessRecord
for resolved_record in resolved_records:
if not resolved_record.record.available:
raise InvalidConfigurationError(
f"Selected postprocess index {resolved_record.postprocess_index!r} is unavailable for batch entry {resolved_record.entry.index}."
)
converted_records.append(
_ResolvedBatchPostprocessRecord(
entry=resolved_record.entry,
postprocess_index=resolved_record.postprocess_index,
record=resolved_record.record.to_powerflux(),
)
)
return _BatchPostprocessSelection(
records=self.records,
index=self.index,
_resolved_records=tuple(converted_records),
)
def _resolve_selected_records(self) -> tuple[_ResolvedBatchPostprocessRecord, ...]:
"""Resolve the selected postprocess record on each successful batch entry."""
if self._resolved_records is not None:
return self._resolved_records
resolved_records: list[_ResolvedBatchPostprocessRecord] = []
batch_record: BatchExportRecord
for batch_record in self.records:
if not isinstance(batch_record.payload, PostprocessCollection):
continue
postprocess_index = self.index
if postprocess_index < 0 or postprocess_index >= len(batch_record.payload):
raise InvalidConfigurationError(
f"Selected postprocess index {postprocess_index!r} is missing for batch entry {batch_record.index}."
)
selected_record = batch_record.payload[postprocess_index]
resolved_records.append(
_ResolvedBatchPostprocessRecord(
entry=batch_record,
postprocess_index=postprocess_index,
record=selected_record,
)
)
return tuple(resolved_records)
@dataclass(slots=True, frozen=True)
class _ResolvedBatchPostprocessRecord:
"""Internal resolved selected postprocess record for one batch entry."""
entry: BatchExportRecord
postprocess_index: int
record: PostprocessRecord
@dataclass(slots=True, frozen=True)
class _BatchPostprocessHeaderSelection(DictionaryExportMixin):
"""Header export view for one selected batch postprocess stream."""
records: tuple[BatchExportRecord, ...]
index: int
_resolved_records: tuple[_ResolvedBatchPostprocessRecord, ...] = field(
default_factory=tuple,
repr=False,
)
def to_dict(self) -> Mapping[object, object]:
"""Return the batch-aligned header rows as a mapping by entry index."""
header_mapping: dict[object, object] = {}
resolved_record: _ResolvedBatchPostprocessRecord
for resolved_record in self._resolved_records:
header_payload: PostprocessHeader | None = resolved_record.record.header
header_mapping[resolved_record.entry.index] = {
"title": resolved_record.record.title,
"header": (
None if header_payload is None else header_payload.to_dict()
),
}
return header_mapping
def items(
self,
) -> tuple[tuple[int, dict[str, object], PostprocessHeader | None], ...]:
"""Return selected headers in batch-entry order."""
return tuple(
(
resolved_record.entry.index,
resolved_record.entry.keys,
resolved_record.record.header,
)
for resolved_record in self._resolved_records
)
def to_df(self, orient: str | None = None) -> pd.DataFrame:
"""Export selected batch postprocess headers as a long-form DataFrame."""
if orient not in (None, "wide", "long"):
raise ValueError("orient must be None, 'wide', or 'long'")
if orient == "wide":
raise UnsupportedExportError(
"to_df is not supported for wide batch postprocess headers."
)
from ...pandas_export import _load_pandas_module
from ..export.companion import require_pandas_companion
require_pandas_companion()
from jcmsuite_pandas.batch_postprocess import (
selected_batch_postprocess_headers_to_df,
)
return selected_batch_postprocess_headers_to_df(
self._resolved_records, _load_pandas_module()
)
def to_xarray(self) -> XarrayDataTree:
"""Export selected batch postprocess headers as a `DataTree`."""
from ..export.companion_xarray import require_xarray_companion
require_xarray_companion()
from jcmsuite_xarray.export import (
batch_selected_postprocess_headers_to_xarray_dataset,
)
return batch_selected_postprocess_headers_to_xarray_dataset(
self.records,
index=self.index,
)