# SPDX-License-Identifier: MIT
# Copyright (c) 2001-{{ COPYRIGHT_END_YEAR }} JCMwave GmbH
"""Core solve result models and result-file discovery helpers."""
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Literal, cast
from ....context.models import BackendMode
from ....exceptions import InvalidConfigurationError
from ....loaders import (
CartesianFieldFormat,
load_cartesian_fields,
load_table,
)
from ...artifacts import (
ComputationalCosts,
DiscoveredArtifacts,
Eigenvalues,
PostprocessCollection,
discover_artifacts_from_project,
discover_artifacts_from_result_dir,
)
from ...field_exports import FieldExportPayload
from ...payloads import SolveKeys, Source, TableCollectionPayload, TablePayload
if TYPE_CHECKING:
import pandas as pd
[docs]
@dataclass(slots=True, frozen=True)
class SolveExecutionLog:
"""Store the captured log for one solve.
Parameters
----------
backend : BackendMode
Execution method that produced the log.
stdout : str
Messages written to stdout.
stderr : str
Error messages written to standard error.
return_code : int | None
Completion code from JCMsuite, if available. A value of `0` indicates
success.
streamed_to_console : bool
`True` if the messages were also shown in the terminal while the solve
ran.
"""
#: Execution method that produced the log.
backend: BackendMode
#: Messages written to stdout.
stdout: str
#: Error messages written to standard error.
stderr: str
#: Completion code from JCMsuite, if available. Zero indicates success.
return_code: int | None
#: Whether the messages were also shown in the terminal during the solve.
streamed_to_console: bool
[docs]
@dataclass(slots=True, frozen=True)
class TemplateRenderInfo:
"""Store information about one template that JCMsuite converted.
Parameters
----------
source_template : Path
Source `.jcmt` or `.jcmpt` template.
rendered_project : Path
Generated `.jcm` or `.jcmp` file used by the solver.
keys : dict[str, object]
project keys used for template rendering.
"""
source_template: Path
rendered_project: Path
keys: dict[str, object]
class SolveKeysPayload(SolveKeys):
"""Deprecated bridge for deferred pre-foundation consumers."""
@property
def _raw(self) -> Mapping[str, object]:
return self
def to_dict(self) -> Mapping[object, object]:
return cast(Mapping[object, object], dict(self))
def to_df(self, orient: str | None = None) -> "pd.DataFrame":
if orient not in (None, "wide"):
return super().to_df(orient=orient)
return self._to_df_wide()
[docs]
@dataclass(slots=True)
class SolveResult:
"""Provide the result for one project and one set of project keys.
Parameters
----------
project_file : Path | None, optional
project file used for the solve.
backend_used : BackendMode | None, optional
Execution method used for the solve.
template_renders : tuple[TemplateRenderInfo, ...], optional
Template rendering operations completed during solve preparation.
daemon_job_id : int | None, optional
Daemon submission identifier, if the solve used the daemon.
log : SolveExecutionLog | None, optional
Messages and completion code from the solve.
keys : Mapping[str, object] | None, optional
project keys used for this solve result, or `None` if no project keys
were supplied.
"""
#: Project file used for the solve.
project_file: Path | None = None
backend_used: BackendMode | None = field(default=None, repr=False)
template_renders: tuple[TemplateRenderInfo, ...] = field(
default_factory=tuple, repr=False
)
daemon_job_id: int | None = None
#: Messages and completion code from :class:`~jcmsuite.results.SolveExecutionLog`.
log: SolveExecutionLog | None = field(default=None, repr=False)
#: Project keys represented by :class:`~jcmsuite.results.SolveKeys`, or ``None`` when none were supplied.
keys: Mapping[str, object] | SolveKeys | None = field(
default_factory=SolveKeys,
repr=False,
)
_post_process_only: bool = field(default=False, repr=False)
_file: Path | None = field(default=None, init=False, repr=False)
_costs: ComputationalCosts | None = field(default=None, init=False, repr=False)
_eigenvalues: Eigenvalues | None = field(default=None, init=False, repr=False)
_postprocesses: PostprocessCollection | None = field(
default=None, init=False, repr=False
)
_field_data: Mapping[object, object] | None = field(
default=None, init=False, repr=False
)
_field_source: Source = field(default=None, init=False, repr=False)
_artifact_root: Path | None = field(default=None, init=False, repr=False)
_artifacts_loaded: bool = field(default=False, init=False, repr=False)
def __post_init__(self) -> None:
"""Normalize incoming key payload to ``SolveKeys``."""
if self.keys is not None and not isinstance(self.keys, SolveKeys):
self.keys = SolveKeys(dict(self.keys), source=self.project_file)
elif (
type(self.keys) is SolveKeys
and self.keys.source is None
and self.project_file is not None
):
self.keys = SolveKeys(dict(self.keys), source=self.project_file)
[docs]
@classmethod
def from_project_file(cls, project_file: str | Path) -> SolveResult:
"""Open an existing solve result from a project file.
Parameters
----------
project_file : str | Path
Path to a rendered project file (`.jcmp` or `.jcm`). The method
loads result data from the `*_results` directory with the same
file stem.
Returns
-------
SolveResult
Solve result with its available result data loaded.
Raises
------
InvalidConfigurationError
If the project file is missing or no result data is found.
"""
resolved_project_file: Path = Path(project_file).expanduser().resolve()
if not resolved_project_file.is_file():
raise InvalidConfigurationError(
f"Project file is missing or not a file: {resolved_project_file}"
)
result: SolveResult = cls(project_file=resolved_project_file)
result.refresh_artifacts()
if not _has_discovered_artifacts(
file=result.file,
costs=result.costs,
eigenvalues=result.eigenvalues,
postprocesses=result.postprocesses,
):
expected_result_dir: Path = (
resolved_project_file.parent / f"{resolved_project_file.stem}_results"
)
raise InvalidConfigurationError(
"No result artifacts found for project file "
f"{resolved_project_file} (expected {expected_result_dir})."
)
return result
[docs]
@classmethod
def from_result_dir(
cls,
result_dir: str | Path,
*,
project_file: str | Path | None = None,
) -> SolveResult:
"""Open an existing solve result from a result directory.
Parameters
----------
result_dir : str | Path
Path to a ``*_results`` directory that contains solver results.
project_file : str | Path | None, optional
project file associated with the result directory. If omitted, the
method tries to find the project file next to the directory.
Returns
-------
SolveResult
Solve result with its available result data loaded.
Raises
------
InvalidConfigurationError
If the result directory is invalid or no result data is found.
"""
resolved_result_dir: Path = Path(result_dir).expanduser().resolve()
if not resolved_result_dir.is_dir():
raise InvalidConfigurationError(
f"Result directory is missing or not a directory: {resolved_result_dir}"
)
resolved_project_file: Path | None
if project_file is not None:
resolved_project_file = Path(project_file).expanduser().resolve()
if not resolved_project_file.is_file():
raise InvalidConfigurationError(
"Explicit `project_file` is missing or not a file: "
f"{resolved_project_file}"
)
else:
resolved_project_file = _infer_project_file_from_result_dir(
resolved_result_dir
)
discovered_artifacts: DiscoveredArtifacts = discover_artifacts_from_result_dir(
resolved_result_dir
)
if not _has_discovered_artifacts(
file=discovered_artifacts.file,
costs=discovered_artifacts.costs,
eigenvalues=discovered_artifacts.eigenvalues,
postprocesses=discovered_artifacts.postprocesses,
):
raise InvalidConfigurationError(
f"No recognizable result artifacts found in {resolved_result_dir}."
)
result = cls(project_file=resolved_project_file)
result._artifact_root = resolved_result_dir
result._file = discovered_artifacts.file
result._costs = discovered_artifacts.costs
result._eigenvalues = discovered_artifacts.eigenvalues
result._postprocesses = discovered_artifacts.postprocesses
result._artifacts_loaded = True
return result
[docs]
def load_table(
self,
table_file: str | Path,
*,
format: Literal["named"] = "named",
) -> TablePayload | TableCollectionPayload:
"""Load a table file associated with this solve result.
Parameters
----------
table_file : str | Path
Table file path. Relative paths are resolved against
`project_file.parent` when available.
format : {"named"}, optional
Output format. The only supported value is `"named"`.
Returns
-------
TablePayload | TableCollectionPayload
One table, or an ordered collection if the file contains multiple
tables.
Raises
------
InvalidConfigurationError
If the table path is not a file or `format` is not supported.
"""
resolved_table_file: Path = self._resolve_artifact_path(table_file)
return load_table(resolved_table_file, format=format)
[docs]
def load_cartesian_fields(
self,
field_file: str | Path,
*,
format: CartesianFieldFormat = "squeeze",
) -> FieldExportPayload:
"""Load a Cartesian fieldbag file associated with this solve result.
Parameters
----------
field_file : str | Path
Fieldbag file path. Relative paths are resolved against
`project_file.parent` when available.
format : {"squeeze", "full"}, optional
Shape of the returned coordinates and field values. `"squeeze"`
removes dimensions of length 1. `"full"` keeps all dimensions.
Returns
-------
FieldExportPayload
Coordinates, field values, available derivatives, and file
information.
Raises
------
InvalidConfigurationError
If the fieldbag path is not a file or `format` is not supported.
RuntimeError
If the fieldbag file is damaged or uses an unsupported storage
format.
"""
if self._field_data is not None:
return FieldExportPayload(
self._field_data,
source=(
self._field_source
if self._field_source is not None
else "resultbag"
),
)
resolved_field_file: Path = self._resolve_artifact_path(field_file)
return load_cartesian_fields(resolved_field_file, format=format)
def _resolve_artifact_path(self, artifact_file: str | Path) -> Path:
"""Resolve a result-file path relative to known solve/result roots.
Parameters
----------
artifact_file : str | Path
Result filename or path from solver payloads.
Returns
-------
pathlib.Path
Absolute resolved result-file path.
Notes
-----
Internal API: this helper is implementation detail and may change
without notice.
"""
artifact_path: Path = Path(artifact_file).expanduser()
if artifact_path.is_absolute():
return artifact_path.resolve()
if self._artifact_root is not None:
return (self._artifact_root / artifact_path).resolve()
if self.project_file is not None:
return (self.project_file.parent / artifact_path).resolve()
return artifact_path.resolve()
[docs]
def refresh_artifacts(self) -> None:
"""Read the result files again.
Returns
-------
None
The fieldbag, computational-cost, eigenvalue, and postprocess data
reflect the current files.
"""
discovered_artifacts: DiscoveredArtifacts
if self.project_file is None:
if self._artifact_root is None:
self._file = None
self._costs = None
self._eigenvalues = None
self._postprocesses = PostprocessCollection(records=())
self._artifacts_loaded = True
return
discovered_artifacts = discover_artifacts_from_result_dir(
self._artifact_root
)
else:
discovered_artifacts = discover_artifacts_from_project(self.project_file)
self._file = None if self._post_process_only else discovered_artifacts.file
self._costs = None if self._post_process_only else discovered_artifacts.costs
self._eigenvalues = (
None if self._post_process_only else discovered_artifacts.eigenvalues
)
self._postprocesses = discovered_artifacts.postprocesses
self._artifacts_loaded = True
def _ensure_artifacts_loaded(self) -> None:
"""Populate cached result-file fields on first access.
Returns
-------
None
This method mutates internal caches and returns nothing.
Notes
-----
Internal API: this helper is implementation detail and may change
without notice.
"""
if self._artifacts_loaded:
return
self.refresh_artifacts()
@property
def file(self) -> Path | None:
"""Return the solution fieldbag file.
Returns
-------
Path | None
Solution fieldbag file, or `None` if it is unavailable.
"""
self._ensure_artifacts_loaded()
return self._file
@property
def costs(self) -> ComputationalCosts | None:
"""Return computational-cost data.
Returns
-------
ComputationalCosts | None
Computational-cost data, or `None` if it is unavailable.
"""
self._ensure_artifacts_loaded()
return self._costs
@property
def postprocesses(self) -> PostprocessCollection:
"""Return the postprocess results in project file order.
Returns
-------
PostprocessCollection
Available postprocess results. An empty collection indicates that
no postprocess result is available.
"""
self._ensure_artifacts_loaded()
if self._postprocesses is None:
return PostprocessCollection(records=())
return self._postprocesses
@property
def eigenvalues(self) -> Eigenvalues | None:
"""Return eigenvalue data.
Returns
-------
Eigenvalues | None
Eigenvalue data, or `None` if it is unavailable.
"""
self._ensure_artifacts_loaded()
return self._eigenvalues
def _infer_project_file_from_result_dir(result_dir: Path) -> Path | None:
"""Infer project file next to a ``*_results`` directory.
Parameters
----------
result_dir : pathlib.Path
Candidate result directory path.
Returns
-------
pathlib.Path | None
Resolved project file path when inferable, else ``None``.
Notes
-----
Internal API: this helper is implementation detail and may change without
notice.
"""
directory_name: str = result_dir.name
if not directory_name.endswith("_results"):
return None
project_stem: str = directory_name[: -len("_results")]
if not project_stem:
return None
candidate_suffix: str
for candidate_suffix in (".jcmp", ".jcm"):
candidate_path: Path = result_dir.parent / f"{project_stem}{candidate_suffix}"
if candidate_path.is_file():
return candidate_path.resolve()
return None
def _has_discovered_artifacts(
*,
file: Path | None,
costs: ComputationalCosts | None,
eigenvalues: Eigenvalues | None,
postprocesses: PostprocessCollection,
) -> bool:
"""Determine whether discovered result-file data is non-empty.
Parameters
----------
file : pathlib.Path | None
Discovered primary solution file.
costs : ComputationalCosts | None
Discovered computational-cost payload.
eigenvalues : Eigenvalues | None
Discovered eigenvalue payload.
postprocesses : PostprocessCollection
Discovered postprocess collection.
Returns
-------
bool
``True`` if at least one result-file category is present.
Notes
-----
Internal API: this helper is implementation detail and may change without
notice.
"""
return (
file is not None
or costs is not None
or eigenvalues is not None
or len(postprocesses) > 0
)