Source code for osprey_connectors.simulation.values

"""Channel value coercion and zero values per ``value_type``.

One function set shared by the connectors package and the facility build, so
both accept and refuse exactly the same values. The module imports only the
standard library: no framework enters through it.

Stored representations:

* ``float`` -> ``float``; ``int`` -> ``int``;
* ``bool`` / ``enum`` -> the label (``str``) from ``options``;
* ``string`` -> ``str``;
* ``waveform`` -> a flat, row-major ``list[float]`` whose length is the
  product of ``shape``.
"""

from __future__ import annotations

import math
import numbers
from collections.abc import Mapping, Sequence
from typing import Any, Literal, SupportsFloat, SupportsIndex, TypeAlias, TypeGuard, overload

_VALUE_TYPES = ("float", "int", "bool", "enum", "string", "waveform")
#: The value types whose channels carry labels.
LABELLED_TYPES = ("bool", "enum")
#: The value types a seed's ``gate`` applies to.
GATED_TYPES = ("float", "int", *LABELLED_TYPES)
DEFAULT_VALUE_TYPE = "float"
DEFAULT_BOOL_OPTIONS = ("FALSE", "TRUE")
#: The value type of a channel that carries a flat ``list[float]`` trace.
_WAVEFORM = "waveform"

#: A channel value in its stored representation.
StoredValue: TypeAlias = float | int | str | list[float]

__all__ = [
    "DEFAULT_BOOL_OPTIONS",
    "DEFAULT_VALUE_TYPE",
    "GATED_TYPES",
    "LABELLED_TYPES",
    "StoredValue",
    "channel_labels",
    "coerce",
    "is_waveform",
    "zero",
]


[docs] def is_waveform(value_type: str | None) -> bool: """Whether a channel of ``value_type`` carries a trace rather than a scalar.""" return value_type == _WAVEFORM
def _refuse(value: object, value_type: str, reason: str) -> ValueError: return ValueError(f"value {value!r} is not a valid {value_type}: {reason}") def _is_number(value: object) -> TypeGuard[numbers.Real]: return isinstance(value, numbers.Real) and not isinstance(value, bool) def _is_integer(value: object) -> TypeGuard[numbers.Integral]: return isinstance(value, numbers.Integral) and not isinstance(value, bool) def _real(value: object) -> float: """``float(value)`` of a value the type checker cannot prove ``float`` takes. A held or served value is typed by its channel, which the type checker does not see, so a reader that knows the channel holds a number converts it here. Raises: TypeError: ``value`` is not a string, a bytes object or a real number, worded as ``float`` words it. ValueError: ``value`` is a string that spells no number. """ if isinstance(value, str | bytes | bytearray | SupportsFloat | SupportsIndex): return float(value) raise TypeError( f"float() argument must be a string or a real number, not {type(value).__name__!r}" ) def _labels(value_type: str, options: Sequence[str] | None) -> list[str]: if options is None: if value_type == "bool": return list(DEFAULT_BOOL_OPTIONS) raise ValueError(f"value_type {value_type} needs options (its labels)") return [str(label) for label in options]
[docs] def channel_labels(channel: Mapping[str, Any]) -> list[str]: """The labels of a bool or enum channel record. Args: channel: The channel record. Returns: The record's ``options``, or :data:`DEFAULT_BOOL_OPTIONS` without them. """ return list(channel.get("options") or DEFAULT_BOOL_OPTIONS)
def _size(shape: Sequence[int] | None) -> int: if not shape: raise ValueError("value_type waveform needs shape (a list of positive ints)") return math.prod(shape) def _flatten(value: object, out: list[object]) -> None: if isinstance(value, (list, tuple)): for item in value: _flatten(item, out) else: out.append(value) def _coerce_label(value: object, value_type: str, labels: list[str]) -> str: if isinstance(value, str): if value in labels: return value raise _refuse(value, value_type, f"label not in {labels}") if isinstance(value, bool) or _is_integer(value): index = int(value) else: raise _refuse(value, value_type, "expected an index, a bool or a label") if 0 <= index < len(labels): return labels[index] raise _refuse(value, value_type, f"index outside 0..{len(labels) - 1}") @overload def coerce( value: object, value_type: Literal["float"], options: Sequence[str] | None = None, shape: Sequence[int] | None = None, ) -> float: ... @overload def coerce( value: object, value_type: Literal["int"], options: Sequence[str] | None = None, shape: Sequence[int] | None = None, ) -> int: ... @overload def coerce( value: object, value_type: Literal["bool", "enum", "string"], options: Sequence[str] | None = None, shape: Sequence[int] | None = None, ) -> str: ... @overload def coerce( value: object, value_type: Literal["waveform"], options: Sequence[str] | None = None, shape: Sequence[int] | None = None, ) -> list[float]: ... @overload def coerce( value: object, value_type: str | None, options: Sequence[str] | None = None, shape: Sequence[int] | None = None, ) -> StoredValue: ...
[docs] def coerce( value: object, value_type: str | None, options: Sequence[str] | None = None, shape: Sequence[int] | None = None, ) -> StoredValue: """Coerce ``value`` to the stored representation of ``value_type``. Args: value: The value to coerce. value_type: One of :data:`_VALUE_TYPES`; ``None`` means ``float``. options: The labels of a ``bool`` or ``enum`` channel; a ``bool`` without options uses :data:`DEFAULT_BOOL_OPTIONS`. shape: The dimensions of a ``waveform`` channel. Returns: The coerced value in its stored representation. Raises: ValueError: The value is refused for the type; the message names the type and the value. """ value_type = value_type or DEFAULT_VALUE_TYPE if value_type == "float": if _is_number(value) and math.isfinite(value): return float(value) raise _refuse(value, value_type, "expected a finite int or float") if value_type == "int": if _is_integer(value): return int(value) if _is_number(value) and math.isfinite(value) and float(value).is_integer(): # ``int`` truncates a real number as ``math.trunc`` does; the # typeshed ``Real`` declares only ``__trunc__``. return int(math.trunc(value)) raise _refuse(value, value_type, "expected an int or an integral float") if value_type in LABELLED_TYPES: return _coerce_label(value, value_type, _labels(value_type, options)) if value_type == "string": if isinstance(value, str): return value raise _refuse(value, value_type, "expected a str") if value_type == "waveform": size = _size(shape) if not isinstance(value, (list, tuple)): raise _refuse(value, value_type, "expected a numeric list") flat: list[object] = [] _flatten(value, flat) reals: list[numbers.Real] = [] for item in flat: if not (_is_number(item) and math.isfinite(item)): raise _refuse(value, value_type, "expected finite numbers only") reals.append(item) if len(flat) != size: raise _refuse( value, value_type, f"expected {size} values for shape {list(shape or ())}" ) return [float(item) for item in reals] raise ValueError(f"unknown value_type {value_type!r} (expected one of {list(_VALUE_TYPES)})")
[docs] def zero( value_type: str | None, options: Sequence[str] | None, shape: Sequence[int] | None, ) -> StoredValue: """Return the zero value of ``value_type`` in its stored representation. Args: value_type: One of :data:`_VALUE_TYPES`; ``None`` means ``float``. options: The labels of a ``bool`` or ``enum`` channel. shape: The dimensions of a ``waveform`` channel. Returns: ``0.0``, ``0``, ``options[0]``, ``""`` or ``product(shape)`` zeros. Raises: ValueError: ``value_type`` is unknown, or its options or shape are missing. """ value_type = value_type or DEFAULT_VALUE_TYPE if value_type == "float": return 0.0 if value_type == "int": return 0 if value_type in LABELLED_TYPES: labels = _labels(value_type, options) if not labels: raise ValueError(f"value_type {value_type} needs at least one label") return labels[0] if value_type == "string": return "" if value_type == "waveform": return [0.0] * _size(shape) raise ValueError(f"unknown value_type {value_type!r} (expected one of {list(_VALUE_TYPES)})")