Source code for jcmsuite.results.artifacts

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

"""Typed result-file discovery and access models."""

from __future__ import annotations

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

from ..exceptions import InvalidConfigurationError, UnsupportedExportError
from ..loaders import load_cartesian_fields, load_table
from .payloads import DictionaryExportMixin, MetadataPayload, Source, TablePayload

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

from .discovery import load_postprocess_payload, project_postprocess_output_files
from .postprocess import PostprocessCollection as PostprocessCollection
from .postprocess_payloads import payload_mapping as _payload_mapping_helper
from .postprocess_record import PostprocessRecord as PostprocessRecord

if TYPE_CHECKING:
    from .internal.export.xarray.types import XarrayDataTree


[docs] @dataclass(slots=True, frozen=True, repr=False) class ComputationalCosts(TablePayload): """Store and export computational-cost data. Parameters ---------- table : Mapping[object, object] Dictionary read from `computational_costs.jcm`. source : str | Path | None, optional Source file or storage origin for the computational-cost data. """ table: Mapping[object, object] source: Source = None # pyright: ignore @property def _raw(self) -> Mapping[object, object]: """Return the original computational-cost payload.""" return self.table @property def title(self) -> str | None: """Return the table title. Returns ------- str | None Table title, or `None` if the table has no title. """ title_object: object | None = self.table.get("title") if isinstance(title_object, str): return title_object return None @property def header(self) -> "ComputationalCostsHeader | None": """Return the table header. Returns ------- ComputationalCostsHeader | None Header information, or `None` if no header is available. """ header_object: object | None = self.table.get("header") if isinstance(header_object, Mapping): return ComputationalCostsHeader(table=header_object, source=self.source) return None
[docs] def to_dict(self) -> Mapping[object, object]: """Return the computational-cost data as a dictionary. Returns ------- Mapping[object, object] Computational-cost values and header information. """ return dict(self.table)
def _value_mapping(self) -> Mapping[object, object]: """Return computational values without title or header metadata.""" normalized_mapping: dict[object, object] = dict(self.table) normalized_mapping.pop("title", None) normalized_mapping.pop("header", None) return normalized_mapping def _to_df_wide(self) -> "pd.DataFrame": """Return a DataFrame with one column for each cost value. Returns ------- pandas.DataFrame Wide computational-cost table. """ 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="Computational-cost") def _to_df_long(self) -> "pd.DataFrame": """Return a DataFrame with one row for each cost value. Returns ------- pandas.DataFrame Long-form computational-cost table. """ 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="Computational-cost")
[docs] def to_xarray(self) -> XarrayDataTree: """Return the computational-cost data as an xarray `DataTree`. The root node contains the cost values. Returns ------- xarray.DataTree Computational-cost data in the root node. """ from .internal.export.companion_xarray import require_xarray_companion require_xarray_companion() from jcmsuite_xarray.single import computational_costs_to_xarray_dataset return computational_costs_to_xarray_dataset(self.table)
[docs] @dataclass(slots=True, frozen=True, repr=False) class ComputationalCostsHeader(MetadataPayload, Mapping[object, object]): """Store and export information from a computational-cost header. Parameters ---------- table : Mapping[object, object] Header information from `computational_costs.jcm`. source : str | Path | None, optional Source file or storage origin for the computational-cost header. """ table: Mapping[object, object] source: Source = None # pyright: ignore @property def _raw(self) -> Mapping[object, object]: """Return the original computational-cost header payload.""" return self.table
[docs] def to_dict(self) -> Mapping[object, object]: """Return the header information as a dictionary. Returns ------- Mapping[object, object] Copy of the computational-cost header. """ return dict(self.table)
def __getitem__(self, key: object) -> object: return self.table[key] def __iter__(self) -> Iterator[object]: return iter(self.table) def __len__(self) -> int: return len(self.table) def _to_df_long(self) -> "pd.DataFrame": """Return one DataFrame row for each header value. Returns ------- pandas.DataFrame Long-form computational-cost header. """ from .internal.export.companion import require_pandas_companion require_pandas_companion() from jcmsuite_pandas.single import postprocess_header_to_dataframe return postprocess_header_to_dataframe( self.table, invalid_payload_message=( "Computational-cost header payload is not tabular and cannot be exported via to_df()." ), ) def _to_df_wide(self) -> "pd.DataFrame": """Reject wide export for general header metadata.""" raise UnsupportedExportError( "Computational-cost header metadata only supports long DataFrame export." )
[docs] def to_df(self, orient: str | None = None) -> "pd.DataFrame": """Return header metadata in the requested DataFrame orientation. Parameters ---------- orient : {None, "long"}, optional Select the table layout. Header metadata supports only long form. Returns ------- pandas.DataFrame Long-form computational-cost header. Raises ------ UnsupportedExportError If `orient` is `"wide"`. ValueError If `orient` is not `None`, `"wide"`, or `"long"`. """ 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'")
[docs] def to_xarray(self) -> XarrayDataTree: """Return the header information as an xarray `DataTree`. The root node contains the header values. Returns ------- xarray.DataTree Header information in the root node. """ from .internal.export.companion_xarray import require_xarray_companion require_xarray_companion() from jcmsuite_xarray.export import header_payload_to_xarray_dataset return header_payload_to_xarray_dataset(self.table)
[docs] @dataclass(slots=True, frozen=True, repr=False) class Eigenvalues(TablePayload): """Store and export eigenvalue data. Parameters ---------- table : Mapping[object, object] Dictionary read from `eigenvalues.jcm`. source : str | Path | None, optional Source file or storage origin for the eigenvalue data. """ table: Mapping[object, object] source: Source = None # pyright: ignore @property def _raw(self) -> Mapping[object, object]: """Return the original eigenvalue payload.""" return self.table
[docs] def to_dict(self) -> Mapping[object, object]: """Return the eigenvalue data as a dictionary. Returns ------- Mapping[object, object] Eigenvalue values and table information. """ return dict(self.table)
def _value_mapping(self) -> Mapping[object, object]: """Return eigenvalue values without title metadata.""" normalized_mapping: dict[object, object] = dict(self.table) normalized_mapping.pop("title", None) return normalized_mapping def __getitem__(self, key: object) -> object: return self.table[key] def __iter__(self) -> Iterator[object]: return iter(self.table) def __len__(self) -> int: return len(self.table) def _to_df_wide(self) -> "pd.DataFrame": """Return a DataFrame with one column for each eigenvalue property. Returns ------- pandas.DataFrame Wide eigenvalue table. """ 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="Eigenvalue") def _to_df_long(self) -> "pd.DataFrame": """Return a DataFrame with one row for each eigenvalue property. Returns ------- pandas.DataFrame Long-form eigenvalue table. """ 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="Eigenvalue")
[docs] def to_xarray(self) -> XarrayDataTree: """Return the eigenvalue data as an xarray `DataTree`. Returns ------- xarray.DataTree Tree with all eigenvalue data in the root node. The `row_index` coordinate identifies each eigenvalue row. Raises ------ InvalidConfigurationError If the eigenvalue data cannot form a table. """ from .internal.export.companion_xarray import require_xarray_companion require_xarray_companion() from jcmsuite_xarray.export import eigenvalues_payload_to_xarray_dataset return eigenvalues_payload_to_xarray_dataset(self.table)
[docs] @dataclass(slots=True, frozen=True, repr=False) class PostprocessHeader(DictionaryExportMixin, Mapping[object, object]): """Store and export information from a postprocess header. Parameters ---------- table : Mapping[object, object] Header information from a postprocess result. """ table: Mapping[object, object] @property def _raw(self) -> Mapping[object, object]: """Return the original postprocess header payload.""" return self.table
[docs] def to_dict(self) -> Mapping[object, object]: """Return the header information as a dictionary. Returns ------- Mapping[object, object] Copy of the postprocess header. """ return dict(self.table)
def _preview(self) -> str: """Return internal bounded one-row header preview text. Returns ------- str A text table containing at most six header fields. """ from .internal.export.preview import format_mapping_preview return format_mapping_preview(self.to_dict()) def __repr__(self) -> str: """Return the header class name with its bounded data preview.""" return f"PostprocessHeader(\n preview=\n{self._preview()}\n)" @property def title(self) -> str | None: """Return the postprocess title stored in the header payload.""" title_object: object | None = self.table.get("title") if isinstance(title_object, str): return title_object return None def __getitem__(self, key: object) -> object: return self.table[key] def __iter__(self) -> Iterator[object]: return iter(self.table) def __len__(self) -> int: return len(self.table)
[docs] def to_df(self, orient: str | None = None) -> "pd.DataFrame": """Return one DataFrame row for each header value. Parameters ---------- orient : {None, "long"}, optional Select the table layout. Postprocess headers support only long form. Returns ------- pandas.DataFrame Long-form postprocess header. Raises ------ InvalidConfigurationError If the postprocess header is not tabular. UnsupportedExportError If `orient` is `"wide"`. ValueError If `orient` is not `None`, `"wide"`, or `"long"`. """ if orient not in (None, "long"): if orient == "wide": raise UnsupportedExportError( "Postprocess header metadata only supports long DataFrame export." ) raise ValueError("orient must be None, 'wide', or 'long'") from .internal.export.companion import require_pandas_companion require_pandas_companion() from jcmsuite_pandas.single import postprocess_header_to_dataframe return postprocess_header_to_dataframe( self.table, invalid_payload_message=( "Postprocess header payload is not tabular and cannot be exported via to_df()." ), )
[docs] def to_xarray(self) -> XarrayDataTree: """Return the header information as an xarray `DataTree`. The root node contains the header values. Returns ------- xarray.DataTree Header information in the root node. """ from .internal.export.companion_xarray import require_xarray_companion require_xarray_companion() from jcmsuite_xarray.export import header_payload_to_xarray_dataset return header_payload_to_xarray_dataset(self.table)
[docs] @dataclass(slots=True, frozen=True) class DiscoveredArtifacts: """Store result files and data found for one project. Attributes ---------- file : Path | None Solution fieldbag file, if available. costs : ComputationalCosts | None Computational-cost data, if available. eigenvalues : Eigenvalues | None Eigenvalue data, if available. postprocesses : PostprocessCollection Available postprocess results in project file order. """ file: Path | None costs: ComputationalCosts | None eigenvalues: Eigenvalues | None postprocesses: PostprocessCollection
[docs] def discover_artifacts_from_project(project_file: Path) -> DiscoveredArtifacts: """Find and load result data for one project file. Parameters ---------- project_file : Path Path to the rendered project file. Returns ------- DiscoveredArtifacts Solution fieldbag file and the available computational-cost, eigenvalue, and postprocess data. """ result_dir: Path = project_file.parent / f"{project_file.stem}_results" ordered_output_files: tuple[Path, ...] = _project_postprocess_output_files( project_file=project_file, result_dir=result_dir, ) return _discover_artifacts( result_dir=result_dir, ordered_output_files=ordered_output_files, allow_result_dir_scan=False, )
[docs] def discover_artifacts_from_result_dir(result_dir: Path) -> DiscoveredArtifacts: """Find and load result data from a project result directory. Parameters ---------- result_dir : Path Path to the ``*_results`` directory. Returns ------- DiscoveredArtifacts Solution fieldbag file and the available computational-cost, eigenvalue, and postprocess data. """ return _discover_artifacts( result_dir=result_dir, ordered_output_files=(), allow_result_dir_scan=True, )
def _discover_artifacts( *, result_dir: Path, ordered_output_files: tuple[Path, ...], allow_result_dir_scan: bool, ) -> DiscoveredArtifacts: """Discover result files from one result directory with optional ordering.""" resolved_result_dir: Path = result_dir.expanduser().resolve() fieldbag_file: Path = resolved_result_dir / "fieldbag.jcm" costs_file: Path = resolved_result_dir / "computational_costs.jcm" eigenvalues_file: Path = resolved_result_dir / "eigenvalues.jcm" solution_file: Path | None = ( fieldbag_file.resolve() if fieldbag_file.is_file() else None ) computational_costs: ComputationalCosts | None = None costs_payload: object if costs_file.is_file(): try: costs_payload = load_table(costs_file) except Exception: costs_payload = None costs_mapping: Mapping[object, object] | None = _payload_mapping_helper( costs_payload ) if costs_mapping is not None: computational_costs = ComputationalCosts( table=costs_mapping, source=costs_file, ) eigenvalues: Eigenvalues | None = None eigen_payload: object if eigenvalues_file.is_file(): try: eigen_payload = load_table(eigenvalues_file) except Exception: eigen_payload = None eigen_mapping: Mapping[object, object] | None = _payload_mapping_helper( eigen_payload ) if eigen_mapping is not None: eigenvalues = Eigenvalues( table=eigen_mapping, source=eigenvalues_file, ) postprocess_records: list[PostprocessRecord] = [] reserved_result_names: set[str] = { "fieldbag.jcm", "computational_costs.jcm", "eigenvalues.jcm", } ordered_result_files: list[Path] = [] seen_output_files: set[Path] = set() ordered_output: Path for ordered_output in ordered_output_files: resolved_output: Path = ordered_output.expanduser().resolve() if resolved_output in seen_output_files: continue seen_output_files.add(resolved_output) # Preserve project-declared postprocess outputs even when the backing # file never materialized as a loadable `.jcm` artifact (for example # Pinboard-formatted outputs). Those entries surface as empty records. ordered_result_files.append(resolved_output) if allow_result_dir_scan: discovered_result_files: list[Path] = sorted( ( [] if not resolved_result_dir.is_dir() else [ candidate.resolve() for candidate in resolved_result_dir.glob("*.jcm") if candidate.is_file() and candidate.name not in reserved_result_names ] ), key=lambda file_path: file_path.name.lower(), ) fallback_output: Path for fallback_output in discovered_result_files: if fallback_output not in seen_output_files: ordered_result_files.append(fallback_output) ordered_result_file: Path for ordered_result_file in ordered_result_files: try: payload: object | None = _load_postprocess_payload(ordered_result_file) except InvalidConfigurationError as exc: postprocess_records.append( PostprocessRecord( source_file=ordered_result_file, _raw=None, title=ordered_result_file.stem, available=False, failure_message=str(exc), ) ) continue payload_title: str | None = _extract_payload_title(payload) if payload_title is None: payload_title = ordered_result_file.stem if payload is None: postprocess_records.append( PostprocessRecord( source_file=ordered_result_file, _raw=None, title=payload_title, available=False, failure_message="Postprocess output file is missing.", ) ) continue postprocess_records.append( PostprocessRecord( source_file=ordered_result_file, _raw=payload, title=payload_title, ) ) postprocess_collection: PostprocessCollection = PostprocessCollection( records=tuple(postprocess_records) ) return DiscoveredArtifacts( file=solution_file, costs=computational_costs, eigenvalues=eigenvalues, postprocesses=postprocess_collection, ) def _project_postprocess_output_files( *, project_file: Path, result_dir: Path, ) -> tuple[Path, ...]: """Return postprocess output files in project-definition order. Notes ----- Internal API: this helper preserves the legacy `OutputFileName` ordering contract for project-backed result discovery. Raw result-dir opening still falls back to filesystem order when no project file is available. """ return project_postprocess_output_files( project_file=project_file, result_dir=result_dir, ) def _load_postprocess_payload(output_path: Path) -> object | None: """Load postprocess payload. Parameters ---------- output_path : Path Filesystem path supplied via `output_path`. Returns ------- object | None Computed ``object | None`` value. Notes ----- Internal API: this helper is an implementation detail and may change without notice. """ return load_postprocess_payload( output_path, load_table=load_table, load_cartesian_fields=load_cartesian_fields, ) def _extract_payload_title(payload: object | None) -> str | None: """Extract payload title. Parameters ---------- payload : object | None Internal structured data supplied via `payload`. Returns ------- str | None Computed optional string output. Notes ----- Internal API: this helper is an implementation detail and may change without notice. """ if payload is None: return None payload_mapping: Mapping[object, object] | None = _payload_mapping_helper(payload) if payload_mapping is not None: title_object: object | None = payload_mapping.get("title") if isinstance(title_object, str): return title_object return None