Source code for jcmsuite.results.resultbag

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

"""Persistent Resultbag storage for solve/result workflows."""

from __future__ import annotations

import sqlite3
from collections.abc import Iterator, Mapping, Sequence
from pathlib import Path

from .internal.resultbag.access import (
    EntrySelector,
    ResultbagEntry,
    ResultbagKeys,
    ResultbagView,
)
from .internal.resultbag.query import ResultbagQuery
from .internal.resultbag.store import _ResultbagStore
from .internal.resultbag.utils import FilterInput, between
from .resultbag_management import ResultbagManagement


[docs] class Resultbag: """Store and query solve results in a persistent Resultbag. .. warning:: Open Resultbag files only from trusted sources. Loading stored results or logs uses Python pickle and can execute code from the file. Parameters ---------- filepath : str | Path Resultbag storage path. When the path has no suffix, `.jcmrb` is appended automatically. keys : Mapping[str, object] | Sequence[str] | None, optional project keys or a sequence of project key names that defines the stored fields. When you reopen a Resultbag, `None` preserves its existing fields. If stored data exists, call `resultbag.management.reset()` before you change the fields. Notes ----- Use one Resultbag for one logical project and one set of source files. Source-file checks determine whether stored results can be reused. """ management: ResultbagManagement """Provide advanced Resultbag maintenance and solve integration. Use this namespace to add, inspect, remove, or reset stored entries, manage attempt logs, and connect daemon submissions to Resultbag storage. These operations access persisted data directly. Use `Resultbag.get_results(...)` for normal result selection and the current typed result interfaces. """
[docs] def __init__( self, filepath: str | Path, keys: Mapping[str, object] | Sequence[str] | None = None, ) -> None: """Open or create a Resultbag. Parameters ---------- filepath : str | Path Resultbag storage path. When the path has no suffix, `.jcmrb` is appended automatically. keys : Mapping[str, object] | Sequence[str] | None, optional project keys or a sequence of project key names that defines the stored fields. When you reopen a Resultbag, `None` preserves its existing fields. If stored data exists, call `resultbag.management.reset()` before you change the fields. Raises ------ InvalidConfigurationError If the parent directory does not exist, or if stored data exists and the requested project key fields differ. """ self._store: _ResultbagStore = _ResultbagStore(filepath, keys) self.management: ResultbagManagement = ResultbagManagement(self._store)
@property def _filepath(self) -> Path: """Expose the normalized path for existing internal diagnostics.""" return self._store._filepath @property def _connection(self) -> sqlite3.Connection: """Expose the connection for existing internal diagnostics.""" return self._store._connection @property def _closed(self) -> bool: """Expose closure state for existing internal diagnostics.""" return self._store._closed @classmethod def _close_open_instances_for_exit(cls) -> None: """Close still-open Resultbag stores during process teardown.""" _ResultbagStore._close_open_instances_for_exit()
[docs] def close(self) -> None: """Close the Resultbag file. Repeated calls have no effect. """ self._store.close()
[docs] def __enter__(self) -> Resultbag: """Return this Resultbag for context-managed usage. Returns ------- Resultbag This Resultbag instance. """ return self
[docs] def __exit__( self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: object | None, ) -> None: """Close the Resultbag when the context-managed block exits. Parameters ---------- exc_type : type[BaseException] | None Exception type raised in the managed block, if any. exc : BaseException | None Exception instance raised in the managed block, if any. tb : object | None Traceback object associated with `exc`, if any. """ del exc_type, exc, tb self.close()
@property def keys(self) -> ResultbagKeys: """Return stored project keys without loading result payloads. Returns ------- ResultbagKeys project keys in stable order. The collection cannot be changed. """ return self._store.keys @property def suffixes(self) -> tuple[str | None, ...]: """Return stored JCMT patterns in stable order. Returns ------- tuple[str | None, ...] Available JCMT patterns. `None` identifies entries without a JCMT pattern. """ return self._store.suffixes
[docs] def items(self) -> Iterator[tuple[dict[str, object], object]]: """Iterate over stored project keys and result payloads. Returns ------- Iterator[tuple[dict[str, object], object]] project keys and stored raw result pairs in storage order. Notes ----- Only iterate over a Resultbag file that you trust. This method loads serialized raw result data. """ yield from self._store.items()
[docs] def filter( self, key: str | None = None, filter_value: FilterInput | None = None, /, **criteria: FilterInput, ) -> ResultbagQuery: """Return a read-only view filtered by project keys. Parameters ---------- key : str | None, optional project key name for a positional filter. filter_value : FilterInput | None, optional Exact value or an inclusive range created by `between(...)`. **criteria : FilterInput project key filters. An entry must match all filters. Returns ------- ResultbagQuery Read-only access to matching Resultbag entries. Raises ------ InvalidConfigurationError If the filter is incomplete, empty, duplicated, or cannot compare its bounds with a stored value. """ return self._store.filter(key, filter_value, **criteria)
[docs] def get_results( self, keys: Mapping[str, object] | Sequence[Mapping[str, object]] | None = None, *, jcmt_pattern: str | None = None, ) -> object: """Load selected entries as their supported solve result shape. Parameters ---------- keys : Mapping[str, object] | Sequence[Mapping[str, object]] | None, optional One set or a sequence of project keys to load. `None` loads all entries in the Resultbag. jcmt_pattern : str | None, optional JCMT pattern to select. `None` selects entries without a pattern. Returns ------- SolveResult | BatchSolveResult | BundledSolveResult | BundledBatchSolveResult Solve result shape for the selected entries. Raises ------ InvalidConfigurationError If no entry matches, the selection is ambiguous, the supplied project keys are empty, or stored result shapes are incompatible. Notes ----- When project keys are provided, batch positions follow their supplied sequence. With no selection, entries retain Resultbag storage order. Only load results from a Resultbag file that you trust. This method uses Python pickle to load stored results. """ return self._store.get_results(keys, jcmt_pattern=jcmt_pattern)
[docs] def has_results(self) -> bool: """Return whether at least one stored result exists. Returns ------- bool `True` when the Resultbag contains a stored result. Otherwise, `False`. """ return self._store.has_results()
def _iter_access_entries( self, selector: EntrySelector | None = None ) -> Iterator[ResultbagEntry]: """Provide the internal read seam used by filtered views.""" yield from self._store._iter_access_entries(selector)
__all__ = [ "FilterInput", "Resultbag", "ResultbagQuery", "ResultbagView", "between", ]