Source code for jcmsuite.results.internal.resultbag.utils

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

"""Resultbag filter and key canonicalization helpers."""

from __future__ import annotations

import json
import sqlite3
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Literal, cast

import numpy as np

from ....exceptions import InvalidConfigurationError


@dataclass(frozen=True, slots=True)
class _BetweenFilter:
    """Inclusive bounds marker used by `Resultbag.filter(...)`."""

    lower: object
    upper: object


[docs] def between(lower: object, upper: object) -> _BetweenFilter: """Create an inclusive bounds filter for `Resultbag.filter(...)`. Parameters ---------- lower : object Inclusive lower bound. upper : object Inclusive upper bound. Returns ------- object Filter value that selects values from `lower` through `upper`. """ return _BetweenFilter(lower=lower, upper=upper)
FilterInput = object | _BetweenFilter def _canonicalize_key_value(value: object) -> object: """Convert key values to a deterministic, JSON-serializable structure.""" if value is None or isinstance(value, (bool, int, float, str)): return value if isinstance(value, np.generic): return { "__numpy_scalar__": { "dtype": value.dtype.str, "value": _canonicalize_key_value(value.item()), } } if isinstance(value, np.ndarray): return { "__ndarray__": { "dtype": value.dtype.str, "shape": [int(axis) for axis in value.shape], "data": _canonicalize_key_value(value.tolist()), } } if isinstance(value, Path): return {"__path__": str(value)} if isinstance(value, complex): return {"__complex__": [value.real, value.imag]} if isinstance(value, Mapping): normalized_mapping: dict[str, object] = {} raw_key: object raw_value: object for raw_key, raw_value in sorted(value.items(), key=lambda item: str(item[0])): normalized_mapping[str(raw_key)] = _canonicalize_key_value(raw_value) return normalized_mapping if isinstance(value, (list, tuple)): return [_canonicalize_key_value(item) for item in value] if isinstance(value, (set, frozenset)): # Sets are unordered by nature. We normalize each element and then sort by # its canonical JSON representation so the resulting order is stable. normalized_set_items: list[object] = [ _canonicalize_key_value(item) for item in value ] normalized_set_items.sort( key=lambda item: json.dumps(item, sort_keys=True, separators=(",", ":")) ) return {"__set__": normalized_set_items} raise InvalidConfigurationError( f"Unsupported key value type for Resultbag keys: {type(value)!r}" ) def _decanonicalize_key_value(value: object) -> object: """Convert canonical JSON structures back to Python key structures.""" if isinstance(value, list): return [_decanonicalize_key_value(item) for item in value] if isinstance(value, dict): if "__numpy_scalar__" in value and len(value) == 1: scalar_spec: object = value["__numpy_scalar__"] if isinstance(scalar_spec, dict): dtype_name: object = scalar_spec.get("dtype") scalar_value: object = scalar_spec.get("value") if isinstance(dtype_name, str): reconstructed_scalar: object = _decanonicalize_key_value( scalar_value ) scalar_array = np.asarray( reconstructed_scalar, dtype=np.dtype(dtype_name) ) return cast(object, scalar_array[()]) if "__ndarray__" in value and len(value) == 1: array_spec: object = value["__ndarray__"] if isinstance(array_spec, dict): dtype_name = array_spec.get("dtype") raw_shape = array_spec.get("shape") raw_data = array_spec.get("data") if isinstance(dtype_name, str) and isinstance(raw_shape, list): reconstructed_data: object = _decanonicalize_key_value(raw_data) shape: tuple[int, ...] = tuple(int(axis) for axis in raw_shape) array = np.asarray(reconstructed_data, dtype=np.dtype(dtype_name)) return array.reshape(shape) if "__path__" in value and len(value) == 1: return Path(str(value["__path__"])) if "__complex__" in value and len(value) == 1: complex_parts: object = value["__complex__"] if isinstance(complex_parts, list) and len(complex_parts) == 2: return complex(float(complex_parts[0]), float(complex_parts[1])) if "__set__" in value and len(value) == 1: set_items: object = value["__set__"] if isinstance(set_items, list): return {_decanonicalize_key_value(item) for item in set_items} return { key: _decanonicalize_key_value(raw_value) for key, raw_value in value.items() } return value def _safe_close_connection(connection: sqlite3.Connection) -> None: """Best-effort connection close helper used by finalizers. Finalizers may run after partial interpreter teardown or after an explicit manual close. In those cases, a second close can raise sqlite errors that should not escape cleanup code paths. """ try: connection.close() except Exception: pass @dataclass(frozen=True, slots=True) class _FilterSpec: """Normalized filter spec used by Resultbag query views.""" key: str mode: Literal["exact", "bounds"] exact_value: object | None = None lower_bound: object | None = None upper_bound: object | None = None @classmethod def from_input(cls, key: str, filter_value: FilterInput) -> _FilterSpec: """Create normalized filter spec from user-facing filter argument.""" if not key: raise InvalidConfigurationError("Filter key must be a non-empty string.") if isinstance(filter_value, _BetweenFilter): return cls( key=key, mode="bounds", lower_bound=filter_value.lower, upper_bound=filter_value.upper, ) return cls(key=key, mode="exact", exact_value=filter_value) def matches(self, keys: Mapping[str, object]) -> bool: """Return whether a key dictionary matches this filter.""" if self.key not in keys: return False candidate_value: object = keys[self.key] if self.mode == "exact": return _canonicalize_key_value(candidate_value) == _canonicalize_key_value( self.exact_value ) try: # Bounds filters are intentionally dynamic: stored key payloads may be # numeric, datetime-like, or other orderable runtime types. # We narrow to Any only at this operator boundary. lower_any: Any = self.lower_bound candidate_any: Any = candidate_value upper_any: Any = self.upper_bound return cast( bool, lower_any <= candidate_any <= upper_any, ) except TypeError as error: raise InvalidConfigurationError( "Cannot apply bounds filter for key " f"`{self.key}` to stored value of type {type(candidate_value)!r}." ) from error def _build_filter_specs( key: str | None, filter_value: FilterInput | None, criteria: Mapping[str, FilterInput], ) -> tuple[_FilterSpec, ...]: """Normalize positional/keyword filter inputs into spec tuples.""" if key is None and filter_value is not None: raise InvalidConfigurationError( "Positional filter value requires a positional filter key." ) if key is not None and filter_value is None: raise InvalidConfigurationError( "Positional filter key requires a positional filter value." ) if key is None and filter_value is None and not criteria: raise InvalidConfigurationError("Provide at least one filter criterion.") specs: list[_FilterSpec] = [] seen_keys: set[str] = set() if key is not None: if key in criteria: raise InvalidConfigurationError( f"Duplicate filter criterion for key `{key}`." ) if filter_value is None: raise InvalidConfigurationError( "Positional filter key requires a positional filter value." ) positional_spec: _FilterSpec = _FilterSpec.from_input(key, filter_value) specs.append(positional_spec) seen_keys.add(key) criterion_key: str criterion_value: FilterInput for criterion_key, criterion_value in criteria.items(): if not criterion_key: raise InvalidConfigurationError("Filter key must be a non-empty string.") if criterion_key in seen_keys: raise InvalidConfigurationError( f"Duplicate filter criterion for key `{criterion_key}`." ) seen_keys.add(criterion_key) specs.append(_FilterSpec.from_input(criterion_key, criterion_value)) return tuple(specs)