Source code for jcmsuite.results.internal.models.batch

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

"""Batch solve result models and view helpers."""

from __future__ import annotations

from abc import ABC
from collections.abc import Iterator, Mapping
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Callable, Literal, Self, cast, overload

from ....exceptions import UnsupportedExportError
from ...artifacts import ComputationalCosts, Eigenvalues
from ...field_exports import FieldExportView
from ...payloads import (
    DataFrameLongExportMixin,
    DictionaryExportMixin,
    Source,
    TablePayload,
    XarrayExportMixin,
)
from ..export.pandas.payload import payload_to_tabular_rows, value_mapping
from ..export.xarray.types import XarrayDataTree
from .core import SolveExecutionLog, SolveResult

if TYPE_CHECKING:
    import pandas as pd  # pyright: ignore[reportMissingImports]

    from .batch_postprocess import BatchPostprocessCollection


[docs] @dataclass(slots=True, frozen=True) class BatchSolveFailure: """Describe one failed entry in a `BatchSolveResult`. Parameters ---------- index : int Position in the batched project keys. keys : dict[str, object] project keys for the failed entry. exception_type : type[Exception] Exception class raised while processing the item. message : str Message from the exception. """ index: int keys: dict[str, object] exception_type: type[Exception] message: str
[docs] @dataclass(slots=True, frozen=True) class BatchSolveEntry: """Store one ordered entry in a `BatchSolveResult`. Parameters ---------- index : int Position in the batched project keys. keys : dict[str, object] project keys used for this solve entry. result : SolveResult | None Solve result if this entry succeeded. failure : BatchSolveFailure | None Failure information if this entry did not succeed and `on_error` was `"collect"`. _log : SolveExecutionLog | None, optional Stored execution log for a failed entry. Application code usually reads the public `log` property instead of setting this value. """ index: int """Position in the batched project keys.""" keys: dict[str, object] """Project keys used for this solve entry.""" result: SolveResult | None """Solve result if this entry succeeded.""" failure: BatchSolveFailure | None """Failure information if this entry did not succeed.""" _log: SolveExecutionLog | None = field(default=None, repr=False) @property def log(self) -> SolveExecutionLog | None: """Return the execution log for this batch entry. Returns ------- SolveExecutionLog | None Log from `result.log` for a successful entry, or the stored failure log. Returns `None` if no log is available. """ if self.result is not None and self.result.log is not None: return self.result.log return self._log
@dataclass(slots=True, frozen=True) class BatchExportRecord: """Aligned batch record used by metadata and result-data export views.""" index: int keys: dict[str, object] payload: object | None = None source: Source = None
[docs] class BatchExportablePayload(ABC): """Independent base for aligned batch payload provenance.""" _sources: tuple[Source, ...] def __init__(self, sources: tuple[Source, ...]) -> None: object.__setattr__(self, "_sources", tuple(sources)) @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
[docs] class BatchMetadataPayload( BatchExportablePayload, DictionaryExportMixin, DataFrameLongExportMixin, XarrayExportMixin, ABC, ): """Store and export named information for a batch.""" def __init__(self, records: tuple[BatchExportRecord, ...]) -> None: super().__init__(tuple(record.source for record in records)) self._records: tuple[BatchExportRecord, ...] = records @property def records(self) -> tuple[BatchExportRecord, ...]: """Return aligned metadata records.""" return self._records def to_dict(self) -> Mapping[object, object]: """Return one information dictionary for each original batch position. Returns ------- Mapping[object, object] Information dictionaries indexed by original batch position. """ return {record.index: dict(record.keys) for record in self.records} def _to_df_long(self) -> "pd.DataFrame": """Return one DataFrame row for each named value in each batch entry. The `batch_index` column contains the original batch position. Returns ------- pandas.DataFrame Long-form table of the batch information. """ from ...pandas_export import batch_keys_to_df_long return batch_keys_to_df_long(self.records) def to_df(self, orient: str | None = None) -> "pd.DataFrame": """Return batch table data as a long-form pandas `DataFrame`. Parameters ---------- orient : {None, "long"}, optional Select the table layout. Batch table data does not support the wide layout. Returns ------- pandas.DataFrame Batch metadata 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 batch metadata." ) raise ValueError("orient must be None, 'wide', or 'long'") def to_xarray(self) -> XarrayDataTree: """Return the information as an xarray `DataTree`. The `batch_index` coordinate contains the original batch positions. Returns ------- xarray.DataTree Batch information in the root node. """ from ..export.companion_xarray import require_xarray_companion require_xarray_companion() from jcmsuite_xarray.export import batch_keys_to_xarray_dataset return batch_keys_to_xarray_dataset(self.records) def _preview(self) -> str: """Return a bounded long-form preview of aligned metadata.""" from ..export.preview import format_table_preview rows: list[dict[str, object]] = [] record: BatchExportRecord for record in self.records: if not record.keys: rows.append({"batch_index": record.index, "name": None, "value": None}) continue for name, value in record.keys.items(): rows.append({"batch_index": record.index, "name": name, "value": value}) columns: dict[object, object] = { name: [row[name] for row in rows] for name in ("batch_index", "name", "value") } return format_table_preview(columns, compact_values=False) def __repr__(self) -> str: """Return the payload class name with its bounded metadata preview.""" return f"{type(self).__name__}(\n preview=\n{self._preview()}\n)"
[docs] class BatchSolveKeys(BatchMetadataPayload): """Store and export batched project keys with their original positions.""" def _preview(self) -> str: """Return a bounded table preview of the batch project keys.""" from ..export.preview import format_table_preview key_names: list[str] = [] for record in self.records: for key_name in record.keys: if key_name not in key_names: key_names.append(key_name) columns: dict[object, object] = { "batch_index": [record.index for record in self.records] } for key_name in key_names: columns[key_name] = [record.keys.get(key_name) for record in self.records] return format_table_preview( columns, compact_values=False, ) def __repr__(self) -> str: """Return the payload class name with its bounded data preview.""" return f"BatchSolveKeys(\n preview=\n{self._preview()}\n)"
[docs] class BatchTablePayload( BatchExportablePayload, DictionaryExportMixin, DataFrameLongExportMixin, XarrayExportMixin, ABC, ): """Base capability family for batch table payloads.""" records: tuple[BatchExportRecord, ...]
[docs] def to_df(self, orient: str | None = None) -> "pd.DataFrame": """Return batch table data as a long-form pandas `DataFrame`. Parameters ---------- orient : {None, "long"}, optional Select the table layout. Batch table data does not support the wide layout. Returns ------- pandas.DataFrame Batch table data 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 batch tables." ) raise ValueError("orient must be None, 'wide', or 'long'")
def _preview(self) -> str: """Return a bounded preview for the aligned batch tables.""" from ..export.preview import format_table_preview records: tuple[BatchExportRecord, ...] = self.records rows: list[dict[str, object]] = [] record: BatchExportRecord for record in records: if not isinstance(record.payload, TablePayload): rows.append({"batch_index": record.index, "row_index": None}) continue payload_rows: list[dict[str, object]] | None = payload_to_tabular_rows( value_mapping(record.payload.to_dict()) ) if payload_rows is None: rows.append({"batch_index": record.index, "row_index": None}) continue for row_index, payload_row in enumerate(payload_rows): row: dict[str, object] = { "batch_index": record.index, "row_index": row_index, } row.update(payload_row) rows.append(row) column_names: list[str] = [] for row in rows: for column_name in row: if column_name not in column_names: column_names.append(column_name) columns: dict[object, object] = { column_name: [row.get(column_name) for row in rows] for column_name in column_names } return format_table_preview(columns) def __repr__(self) -> str: """Return the payload class name with its bounded table preview.""" return f"{type(self).__name__}(\n preview=\n{self._preview()}\n)"
[docs] class BatchStructuredPayload( BatchExportablePayload, DictionaryExportMixin, DataFrameLongExportMixin, XarrayExportMixin, ABC, ): """Base capability family for batch structured payloads."""
[docs] def to_df(self, orient: str | None = None) -> "pd.DataFrame": """Return batch structured data as path/value rows. Parameters ---------- orient : str | None, optional DataFrame orientation. Use `None` or `"long"`; `"wide"` is not supported for batch structured data. Returns ------- pandas.DataFrame Batch 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 batch structured payloads." ) raise ValueError("orient must be None, 'wide', or 'long'")
[docs] class BatchTableCollectionPayload( BatchExportablePayload, DictionaryExportMixin, DataFrameLongExportMixin, XarrayExportMixin, ABC, ): """Base capability family for batch collections of named tables."""
[docs] def to_df(self, orient: str | None = None) -> "pd.DataFrame": """Return batch table collections as path/value rows. Parameters ---------- orient : str | None, optional DataFrame orientation. Use `None` or `"long"`; `"wide"` is not supported for batch table collections. Returns ------- pandas.DataFrame Batch table collections 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 batch table collections." ) raise ValueError("orient must be None, 'wide', or 'long'")
class BatchFieldPayloadBase( BatchExportablePayload, DictionaryExportMixin, XarrayExportMixin, ABC, ): """Base capability family for non-tabular batch field payloads.""" records: tuple[BatchExportRecord, ...] @property def base(self) -> Self: """Return only the base fields from available batch entries. Returns ------- BatchFieldExportPayload New batch field selection that excludes derivatives. """ return self._project_fields(lambda field: field.base) @property def derivatives(self) -> Self: """Return all field derivatives from available batch entries. Returns ------- BatchFieldExportPayload New batch selection that contains available derivatives. """ return self._project_fields(lambda field: field.derivatives) def keys(self) -> tuple[str, ...]: """Return the available derivative names in source-file order. Returns ------- tuple[str, ...] Derivative names from the first available batch entry. """ for record in self.records: if isinstance(record.payload, FieldExportView): return record.payload.keys() return () def __getitem__(self, name: str) -> Self: """Select one derivative by name from all available batch entries. Parameters ---------- name : str Derivative name. Returns ------- BatchFieldExportPayload New batch field selection for the derivative. Raises ------ TypeError If `name` is not a string. KeyError If the derivative is not available. """ if not isinstance(name, str): raise TypeError("Derivative names must be strings.") if name not in self.keys(): raise KeyError(name) return self._project_fields(lambda field: field[name]) @property def indices(self) -> tuple[int, ...]: """Return the positions of the selected fields in source-file order. Returns ------- tuple[int, ...] Selected field positions from the first available batch entry. """ for record in self.records: if isinstance(record.payload, FieldExportView): return record.payload.indices return () def select(self, index: int | None = None) -> Self: """Select one field position from all available batch entries. If `index` is `None`, select all field positions. Parameters ---------- index : int | None, optional Field position. `None` selects all fields. Returns ------- BatchFieldExportPayload New batch field selection. Raises ------ IndexError If the field position is not available. """ return self._project_fields(lambda field: field.select(index)) def _project_fields( self, projection: Callable[[FieldExportView], FieldExportView] ) -> Self: """Apply one field projection while retaining batch record alignment.""" raise NotImplementedError def _preview(self) -> str: """Return batch availability and field-navigation state.""" available_records: tuple[BatchExportRecord, ...] = tuple( record for record in self.records if isinstance(record.payload, FieldExportView) ) available_indices: tuple[int, ...] = tuple( record.index for record in available_records ) lines: list[str] = [ f" entries: {len(self.records)}", f" available: {len(available_records)}", f" missing: {len(self.records) - len(available_records)}", f" batch_indices: {available_indices}", ] if available_records: field_preview: str = cast( FieldExportView, available_records[0].payload )._preview() lines.extend(field_preview.splitlines()) return "\n".join(lines) def __repr__(self) -> str: """Return field navigation state without numerical field values.""" return f"{type(self).__name__}(\n{self._preview()}\n)" def _batch_export_records( entries: tuple[BatchSolveEntry, ...], ) -> tuple[BatchExportRecord, ...]: """Copy batch indices and keys while selecting no result-data payload.""" return tuple( BatchExportRecord( index=entry.index, keys=dict(entry.keys), source=(None if entry.result is None else entry.result.project_file), ) for entry in entries ) def _batch_artifact_records( entries: tuple[BatchSolveEntry, ...], artifact: Literal["costs", "eigenvalues"], ) -> tuple[BatchExportRecord, ...]: """Copy batch metadata and one selected result-data payload.""" records: list[BatchExportRecord] = [] entry: BatchSolveEntry for entry in entries: payload: TablePayload | None = None if entry.result is not None: payload_object: object = getattr(entry.result, artifact) if isinstance(payload_object, TablePayload): payload = payload_object records.append( BatchExportRecord( index=entry.index, keys=dict(entry.keys), payload=payload, source=( None if entry.result is None else ( entry.result.project_file if payload is None or payload.source is None else payload.source ) ), ) ) return tuple(records) def _batch_postprocess_records( entries: tuple[BatchSolveEntry, ...], ) -> tuple[BatchExportRecord, ...]: """Copy batch metadata and each successful postprocess collection.""" return tuple( BatchExportRecord( index=entry.index, keys=dict(entry.keys), payload=(None if entry.result is None else entry.result.postprocesses), source=_postprocess_source(entry.result), ) for entry in entries ) def _postprocess_source(result: SolveResult | None) -> Source: """Return the source marker from the first available postprocess record.""" if result is None: return None records = result.postprocesses if len(records) == 0: return result.project_file return records[0].source_file
[docs] @dataclass(slots=True) class BatchSolveResult: """Provide ordered results for batched project keys. Parameters ---------- entries : tuple[BatchSolveEntry, ...] Results in batched project keys order. Notes ----- `result[index]` returns one `BatchSolveEntry`. `result[start:stop]` returns a new `BatchSolveResult`. Iteration yields entries in batched project keys order. """ entries: tuple[BatchSolveEntry, ...] @property def project_file(self) -> Path | None: """Return the first available project file. Returns ------- pathlib.Path | None project file from the first successful entry, or `None` if the batch contains no successful result. """ entry: BatchSolveEntry for entry in self.entries: if entry.result is not None and entry.result.project_file is not None: return entry.result.project_file return None
[docs] def __len__(self) -> int: """Return the number of batch entries. Returns ------- int Number of entries. """ return len(self.entries)
[docs] def __iter__(self) -> Iterator[BatchSolveEntry]: """Iterate over entries in batched project keys order. Returns ------- Iterator[BatchSolveEntry] Iterator over the batch entries. """ return iter(self.entries)
@overload def __getitem__(self, index: int) -> BatchSolveEntry: ... @overload def __getitem__(self, index: slice) -> BatchSolveResult: ...
[docs] def __getitem__( self, index: int | slice, ) -> BatchSolveEntry | BatchSolveResult: """Return one entry or a new batch selected by a slice. Parameters ---------- index : int | slice Entry position or standard Python slice. Negative positions count from the end of the batch. Returns ------- BatchSolveEntry | BatchSolveResult One entry for an integer position, or a new batch for a slice. Raises ------ TypeError If `index` is not an integer or slice. IndexError If an integer position is outside the batch. """ if isinstance(index, slice): return BatchSolveResult(entries=self.entries[index]) if isinstance(index, bool) or not isinstance(index, int): raise TypeError("BatchSolveResult indexing requires an integer or slice.") return self.entries[index]
@property def success_indices(self) -> tuple[int, ...]: """Return the original positions of successful batch entries. Returns ------- tuple[int, ...] Original batch positions in input order. """ return tuple(entry.index for entry in self.entries if entry.result is not None) @property def failure_indices(self) -> tuple[int, ...]: """Return the original positions of failed batch entries. Returns ------- tuple[int, ...] Original batch positions in input order. """ return tuple(entry.index for entry in self.entries if entry.result is None) @property def costs(self) -> BatchComputationalCosts: """Return computational-cost data for all batch entries. Returns ------- BatchComputationalCosts Computational-cost data in batched project keys order. """ return BatchComputationalCosts( records=_batch_artifact_records(self.entries, "costs") ) @property def eigenvalues(self) -> BatchEigenvalues: """Return eigenvalue data for all batch entries. Returns ------- BatchEigenvalues Eigenvalue data in batched project keys order. """ return BatchEigenvalues( records=_batch_artifact_records(self.entries, "eigenvalues") ) @property def postprocesses(self) -> BatchPostprocessCollection: """Return the batch postprocess collection. Returns ------- BatchPostprocessCollection Postprocess results in batched project keys order. """ from .batch_postprocess import BatchPostprocessCollection return BatchPostprocessCollection( records=_batch_postprocess_records(self.entries) ) @property def keys(self) -> BatchSolveKeys: """Return the batched project keys and their original positions. Returns ------- BatchSolveKeys project keys in their original batch order. """ return BatchSolveKeys(records=_batch_export_records(self.entries))
[docs] @dataclass(slots=True, frozen=True) class BatchComputationalCosts(BatchTablePayload): """Store and export computational-cost data for a batch. Parameters ---------- records : tuple[BatchExportRecord, ...] Computational-cost data in batch order. """ records: tuple[BatchExportRecord, ...] def __post_init__(self) -> None: BatchTablePayload.__init__( self, tuple(record.source for record in self.records) ) @property def count(self) -> int: """Return the total number of batch entries. Returns ------- int Number of batch entries. """ return len(self.records) @property def available_count(self) -> int: """Return the number of entries with computational-cost data. Returns ------- int Number of available computational-cost results. """ return sum( 1 for record in self.records if isinstance(record.payload, ComputationalCosts) ) @property def missing_count(self) -> int: """Return the number of entries without computational-cost data. Returns ------- int Number of missing computational-cost results. """ return self.count - self.available_count
[docs] def to_dict(self) -> Mapping[object, object]: """Return one cost dictionary for each available batch entry. Returns ------- Mapping[object, object] Cost dictionaries indexed by their original batch positions. """ return { record.index: dict(record.payload.to_dict()) for record in self.records if isinstance(record.payload, ComputationalCosts) }
def __repr__(self) -> str: """Return a compact summary with a bounded cost-data preview.""" return ( f"{self.__class__.__name__}(entries={self.count}, " f"available={self.available_count}, missing={self.missing_count},\n" f" preview=\n{self._preview()}\n)" ) def _to_df_long(self) -> "pd.DataFrame": """Return one DataFrame row for each cost value in each batch entry. Returns ------- pandas.DataFrame Long-form batch computational-cost table. """ from ...pandas_export import batch_costs_to_df return batch_costs_to_df(self.records)
[docs] def to_xarray(self) -> XarrayDataTree: """Return the batch computational costs as an xarray `DataTree`. Returns ------- xarray.DataTree Computational-cost data in batched project keys order. """ from ..export.companion_xarray import require_xarray_companion require_xarray_companion() from jcmsuite_xarray.export import batch_costs_to_xarray_dataset return batch_costs_to_xarray_dataset(self.records)
@property def header(self) -> BatchMetadataPayload: """Return header information for all batch entries. Returns ------- BatchMetadataPayload Header information in batched project keys order. """ header_records: tuple[BatchExportRecord, ...] = tuple( BatchExportRecord( index=record.index, keys=( {} if not isinstance(record.payload, ComputationalCosts) or record.payload.header is None else { str(key): value for key, value in record.payload.header.to_dict().items() } ), source=record.source, ) for record in self.records ) return BatchMetadataPayload(header_records)
[docs] @dataclass(slots=True, frozen=True) class BatchEigenvalues(BatchTablePayload): """Store and export eigenvalue data for a batch. Parameters ---------- records : tuple[BatchExportRecord, ...] Eigenvalue data in batch order. """ records: tuple[BatchExportRecord, ...] def __post_init__(self) -> None: BatchTablePayload.__init__( self, tuple(record.source for record in self.records) ) @property def count(self) -> int: """Return the total number of batch entries. Returns ------- int Number of batch entries. """ return len(self.records)
[docs] def to_dict(self) -> Mapping[object, object]: """Return one eigenvalue dictionary for each available batch entry. Returns ------- Mapping[object, object] Eigenvalue dictionaries indexed by their original batch positions. """ return { record.index: dict(record.payload.to_dict()) for record in self.records if isinstance(record.payload, Eigenvalues) }
@property def available_count(self) -> int: """Return the number of entries with eigenvalue data. Returns ------- int Number of available eigenvalue results. """ return sum( 1 for record in self.records if isinstance(record.payload, Eigenvalues) ) @property def missing_count(self) -> int: """Return the number of entries without eigenvalue data. Returns ------- int Number of missing eigenvalue results. """ return self.count - self.available_count def __repr__(self) -> str: """Return a compact summary with a bounded eigenvalue preview.""" return ( f"{self.__class__.__name__}(entries={self.count}, " f"available={self.available_count}, missing={self.missing_count},\n" f" preview=\n{self._preview()}\n)" ) def _to_df_long(self) -> "pd.DataFrame": """Return one DataFrame row for each eigenvalue property in each entry. Returns ------- pandas.DataFrame Long-form batch eigenvalue table. """ from ...pandas_export import batch_eigenvalues_to_df return batch_eigenvalues_to_df(self.records)
[docs] def to_xarray(self) -> XarrayDataTree: """Return the batch eigenvalues as an xarray `DataTree`. Returns ------- xarray.DataTree Tree with all data in the root node. `batch_index` contains the original batch positions. `row_index` identifies table rows. `is_valid` identifies source values. `is_padded` identifies values added to make all batch tables the same length. Raises ------ InvalidConfigurationError If no eigenvalue data is available or the tables cannot be combined. """ from ..export.companion_xarray import require_xarray_companion require_xarray_companion() from jcmsuite_xarray.export import batch_eigenvalues_to_xarray_dataset return batch_eigenvalues_to_xarray_dataset(self.records)