Source code for palaestrai.agent.memory

from __future__ import annotations
from typing import (
    Any,
    List,
    Tuple,
    Optional,
    Dict,
    Set,
    Union,
    DefaultDict,
)


import itertools
import logging
from dataclasses import dataclass, field, fields
from collections import deque, OrderedDict, defaultdict
import numpy as np
import pandas as pd

from .actuator_information import ActuatorInformation
from .reward_information import RewardInformation
from .sensor_information import SensorInformation

LOG = logging.getLogger(__name__)


@dataclass
class MemoryShard:
    """Collected data from one muscle

    Attributes
    ----------

    sensor_readings : pd.DataFrame
        Column-wise (original) sensor readings as they are provided by the
        environments. Each sensor name is a column; the
        :class:`SensorInformation` objects are stored as-is.
    actuator_setpoints : pd.DataFrame
        Column-wise (original) actuator setpoints. Each actuator name is a
        column; this data frame stores the :class:`ActuatorInformation`
        objects as-is.
    rewards : pd.DataFrame
        Column-wise environment rewards; stores the :class:`RewardInformation`
        objects as-is, with each reward having its own column
    observations : np.ndarray
        Transformed observations: Any data :class:`Muscle` and :class:`Brain`
        want to store
    actions : np.ndarray
        Transformed observations: Any data :class:`Muscle` and :class:`Brain`
        want to store
    objective : np.ndarray
        Result of calling the agent's objective function
    dones : np.ndarray
        Whether the simulation was done at the respective time index or not.
    terminated : np.ndarray
        Whether the episode reached a terminal state (win/loss/draw).
        None if the environment does not distinguish terminated/truncated.
    truncated : np.ndarray
        Whether the episode was truncated (e.g., time limit reached).
        None if the environment does not distinguish terminated/truncated.
    decision_indices : np.ndarray
        Monotonic action identities within the originating worker and episode.
        ``None`` for legacy producers that did not emit an identity.
    additional_data : pd.DataFrame
        Any additional data a :class:`Muscle` shares with is :class:`Brain`
    """

    sensor_readings: pd.DataFrame
    actuator_setpoints: pd.DataFrame
    rewards: pd.DataFrame
    dones: np.ndarray
    observations: np.ndarray
    actions: np.ndarray
    objective: np.ndarray
    additional_data: list
    terminated: Optional[np.ndarray] = None
    truncated: Optional[np.ndarray] = None
    decision_indices: Optional[np.ndarray] = None

    def __len__(self):
        """Number of usable entries in this particular muscle memory

        "Usable" entries are entries that have at least sensor inputs,
        actuator setpoints, and related rewards.
        """
        return len(self.rewards)

    @staticmethod
    def concat(
        memories: Union[List[MemoryShard], Tuple[MemoryShard]],
    ) -> MemoryShard:
        """Concatenate a number of ::`MemoryShard` objects

        All attributes are concatenated in order.
        """

        # Handle special case with len == 0:

        if len(memories) == 0:
            return MemoryShard(
                sensor_readings=pd.DataFrame(),
                actuator_setpoints=pd.DataFrame(),
                rewards=pd.DataFrame(),
                dones=np.array([]),
                observations=np.array([]),
                actions=np.array([]),
                objective=np.array([]),
                additional_data=[],
                terminated=np.array([]),
                truncated=np.array([]),
                decision_indices=np.array([]),
            )

        # Make sure to keep semantics with the NumPy arrays:

        return MemoryShard(
            sensor_readings=pd.concat(
                [m.sensor_readings for m in memories], ignore_index=True
            ),
            actuator_setpoints=pd.concat(
                [m.actuator_setpoints for m in memories], ignore_index=True
            ),
            rewards=pd.concat(
                [m.rewards for m in memories], ignore_index=True
            ),
            dones=np.concatenate([m.dones for m in memories]),
            observations=np.vstack(
                [
                    np.resize(
                        m.observations,
                        np.max([y.observations.shape[1] for y in memories]),
                    )
                    for m in memories
                ]
            ),
            actions=np.vstack(
                [
                    np.resize(
                        m.actions,
                        np.max([y.actions.shape[1] for y in memories]),
                    )
                    for m in memories
                ]
            ),
            objective=np.concatenate([m.objective for m in memories]),
            additional_data=[
                x
                for x in itertools.chain.from_iterable(
                    m.additional_data for m in memories
                )
            ],
            terminated=(
                np.concatenate(
                    [
                        (
                            m.terminated
                            if m.terminated is not None
                            else np.array([])
                        )
                        for m in memories
                    ]
                )
                if all(m.terminated is not None for m in memories)
                else None
            ),
            truncated=(
                np.concatenate(
                    [
                        (
                            m.truncated
                            if m.truncated is not None
                            else np.array([])
                        )
                        for m in memories
                    ]
                )
                if all(m.truncated is not None for m in memories)
                else None
            ),
            decision_indices=(
                np.concatenate(
                    [
                        (
                            m.decision_indices
                            if m.decision_indices is not None
                            else np.array([])
                        )
                        for m in memories
                    ]
                )
                if all(m.decision_indices is not None for m in memories)
                else None
            ),
        )


# ---------------------------------------------------------------------------
# Storage
# ---------------------------------------------------------------------------
#
# The public contract of :class:`Memory` is defined by the original
# deque-based implementation: every (muscle, field) pair is an independent
# FIFO queue; a "row" exists for every append that carried ``rewards``; when a
# row is read, every field is addressed *relative to the end of its own
# queue*; when a row is evicted, one element is removed from the *front* of
# every non-empty queue of that muscle.  This module keeps exactly that model
# and only changes how it is stored and materialised:
#
# * ``_Fifo`` replaces ``collections.deque``: amortised O(1) append and
#   popleft, but O(1) (instead of O(n)) access by index.
# * Field queues are only allocated when a field is used, so tags that only
#   ever see a few fields, or whose rows were all evicted, stay small.
# * ``Memory.tail`` selects all rows first and then builds *one* DataFrame or
#   array per field, instead of one ``MemoryShard`` per row followed by
#   ``MemoryShard.concat``.  Where the batched result could differ from the
#   per-row construction (heterogeneous dtypes, duplicate UIDs, ragged or
#   multi-dimensional values, ...), the legacy per-row algorithm is used.

_FIELDS: Tuple[str, ...] = (
    "sensor_readings",
    "actuator_setpoints",
    "rewards",
    "dones",
    "observations",
    "actions",
    "objective",
    "additional_data",
    "terminated",
    "truncated",
    "decision_indices",
)
_FIELD_SET = frozenset(_FIELDS)


class _Fifo:
    """List-backed FIFO queue with O(1) indexed access.

    Implements the subset of the :class:`collections.deque` interface the
    memory (and code reaching into ``Memory._data``) relies on: ``append``,
    ``popleft``, ``len``, iteration, ``reversed``, ``clear``, and integer
    ``__getitem__``/``__setitem__`` with deque-compatible ``IndexError``
    semantics.  Popped slots are cleared immediately so that evicted objects
    can be garbage-collected; the backing list is compacted lazily.
    """

    __slots__ = ("_items", "_head")

    _COMPACT_MIN = 64

    def __init__(self, iterable=()):
        self._items: list = list(iterable)
        self._head = 0

    def __len__(self) -> int:
        return len(self._items) - self._head

    def __bool__(self) -> bool:
        return len(self._items) > self._head

    def append(self, item):
        self._items.append(item)

    def popleft(self):
        if self._head >= len(self._items):
            raise IndexError("pop from an empty deque")
        item = self._items[self._head]
        self._items[self._head] = None  # Release the reference now
        self._head += 1
        if self._head >= self._COMPACT_MIN and 2 * self._head >= len(
            self._items
        ):
            del self._items[: self._head]
            self._head = 0
        return item

    def clear(self):
        self._items.clear()
        self._head = 0

    def _position(self, index: int) -> int:
        n = len(self._items) - self._head
        if index < 0:
            index += n
        if index < 0 or index >= n:
            raise IndexError("deque index out of range")
        return self._head + index

    def __getitem__(self, index: int):
        return self._items[self._position(index)]

    def __setitem__(self, index: int, value):
        self._items[self._position(index)] = value

    def get(self, index: int, default):
        """``self[index]``, or ``default`` if out of range"""
        n = len(self._items) - self._head
        if index < 0:
            index += n
        if 0 <= index < n:
            return self._items[self._head + index]
        return default

    def last(self, k: int) -> list:
        """The last ``k`` items as a list, in insertion order."""
        if k <= 0:
            return []
        return self._items[max(self._head, len(self._items) - k) :]

    def __iter__(self):
        return itertools.islice(self._items, self._head, None)

    def __reversed__(self):
        for i in range(len(self._items) - 1, self._head - 1, -1):
            yield self._items[i]

    def __eq__(self, other):
        try:
            return list(self) == list(other)
        except TypeError:
            return NotImplemented

    def __repr__(self):
        return f"_Fifo({list(self)!r})"

    def __getstate__(self):
        return list(self)

    def __setstate__(self, state):
        self._items = list(state)
        self._head = 0


class _MuscleMemory:
    """All queues of one tag (muscle/worker).

    Field queues are created on first access, so unused fields cost nothing.
    ``_seqs`` holds the global sequence numbers of this tag's rows, which lets
    :meth:`Memory.tail` answer ``include_only`` queries without scanning the
    complete history.
    """

    __slots__ = _FIELDS + ("_seqs",)

    def __init__(self):
        self._seqs = _Fifo()

    def __getattr__(self, name):
        # Only invoked when the slot is unset, i.e., on first access.
        if name in _FIELD_SET:
            fifo = _Fifo()
            object.__setattr__(self, name, fifo)
            return fifo
        raise AttributeError(name)

    def _field(self, name) -> Optional[_Fifo]:
        """The queue of ``name`` without allocating it."""
        try:
            return object.__getattribute__(self, name)
        except AttributeError:
            return None

    def _release_if_empty(self, name):
        fifo = self._field(name)
        if fifo is not None and not fifo:
            object.__delattr__(self, name)

    def __getstate__(self):
        state = {n: list(f) for n in _FIELDS if (f := self._field(n))}
        state["_seqs"] = list(self._seqs)
        return state

    def __setstate__(self, state):
        for name, items in state.items():
            object.__setattr__(self, name, _Fifo(items))
        if "_seqs" not in state:
            object.__setattr__(self, "_seqs", _Fifo())

    @staticmethod
    def _get_from_deque(d, item: int, default=None):
        try:
            return d[item]
        except IndexError:
            return default

    @staticmethod
    def _infos_to_df(
        infos: Union[
            List[SensorInformation],
            List[ActuatorInformation],
            List[RewardInformation],
        ],
    ) -> pd.DataFrame:
        data = defaultdict(list)
        for i in infos:
            data[i.uid].append(i.value)
        # The values have to be wrapped into np.ndarrays, because pandas
        # does not infer plain lists with zero dim np.ndarray as np.ndarrays
        # which can cause problems.
        # This is done after the collection of the values, because even though
        # the information uids should be unique, they may be set, which does
        # not guarantee the uniqueness. So the length of the lists may be
        # greater than one.
        wrapped_data: Dict[str, np.ndarray] = {}
        for key, value in data.items():
            # The reshaping only keeps one dimension
            wrapped_data[key] = np.reshape(np.array(value), -1)
        return pd.DataFrame(wrapped_data)

    def __getitem__(self, item: int) -> MemoryShard:
        """Receives a "full row" from the MuscleMemory (legacy accessor)"""
        return _assemble([(self, item)])


_STOCK_INFOS_TO_DF = _MuscleMemory.__dict__["_infos_to_df"]

# ---------------------------------------------------------------------------
# Batched materialisation
# ---------------------------------------------------------------------------

_INT64_MIN, _INT64_MAX = -(2**63), 2**63 - 1


def _scalar_key(value):
    """Hashable type signature of a size-1 numeric value, or ``None``.

    Two values with the same signature are converted by NumPy to the same
    dtype, both individually and in a batch.  ``None`` means "not eligible
    for the batched DataFrame path".
    """
    if isinstance(value, np.ndarray):
        if value.size == 1 and value.dtype.kind in "biuf":
            return (np.ndarray, value.dtype, value.shape)
        return None
    if isinstance(value, np.generic):
        return (type(value),) if value.dtype.kind in "biuf" else None
    if type(value) is float or type(value) is bool:
        return (type(value),)
    if type(value) is int and _INT64_MIN <= value <= _INT64_MAX:
        return (int,)
    return None


def _infos_column_batch(rows: List[list]) -> Optional[pd.DataFrame]:
    """Build the DataFrame for one information field in a single step.

    Returns ``None`` if the result could differ from
    ``pd.concat([_infos_to_df(r) for r in rows], ignore_index=True)``.
    Eligible: every row has the same, non-empty, duplicate-free UID sequence,
    and every UID holds size-1 numeric values of one type signature.
    """
    first = rows[0]
    if not first:
        return None
    uids = tuple(i.uid for i in first)
    if len(set(uids)) != len(uids):
        return None
    width = len(uids)
    columns: List[list] = [[] for _ in range(width)]
    for row in rows:
        if len(row) != width:
            return None
        for j, info in enumerate(row):
            if info.uid != uids[j]:
                return None
            columns[j].append(info.value)
    data: Dict[Any, np.ndarray] = {}
    for uid, values in zip(uids, columns):
        key = _scalar_key(values[0])
        if key is None:
            return None
        for v in values:
            if _scalar_key(v) != key:
                return None
        data[uid] = np.reshape(np.array(values), -1)
    return pd.DataFrame(data)


def _infos_column(rows: List[list]) -> pd.DataFrame:
    # The batched path is only equivalent to the stock per-row conversion.
    # Downstream projects replace ``_MuscleMemory._infos_to_df`` at runtime
    # (e.g., to tolerate ragged sensor arrays); honour such replacements by
    # always converting row by row through the installed function.
    if _MuscleMemory.__dict__["_infos_to_df"] is _STOCK_INFOS_TO_DF:
        frame = _infos_column_batch(rows)
        if frame is not None:
            return frame
    return pd.concat(
        [_MuscleMemory._infos_to_df(r) for r in rows], ignore_index=True
    )


def _boxed_column(values: list) -> np.ndarray:
    """Equivalent of ``np.concatenate([np.array([v]) for v in values])``"""
    first = values[0]
    if type(first) is bool or isinstance(first, (np.bool_, float, int)):
        t = type(first)
        if all(type(v) is t for v in values) and not (
            t is int and not all(_INT64_MIN <= v <= _INT64_MAX for v in values)
        ):
            return np.array(values)
    return np.concatenate([np.array([v]) for v in values])


def _objective_column(values: list) -> np.ndarray:
    """Equivalent of ``np.concatenate([np.array(v) for v in values])``"""
    first = values[0]
    if isinstance(first, np.ndarray) and first.ndim == 1:
        dtype = first.dtype
        if all(
            type(v) is np.ndarray and v.ndim == 1 and v.dtype == dtype
            for v in values
        ):
            return np.concatenate(values)
    return np.concatenate([np.array(v) for v in values])


def _vector_column(values: list) -> np.ndarray:
    """Equivalent of the ``observations``/``actions`` code path in
    :meth:`MemoryShard.concat`, including its ``np.resize`` behaviour, but
    with the maximum width computed once instead of once per row."""
    arrays = [np.array([v]) for v in values]
    width = np.max([a.shape[1] for a in arrays])
    if all(a.ndim == 2 and a.shape[1] == width for a in arrays):
        # np.resize(a, width) of a (1, width) array is a.reshape(width);
        # np.vstack of those rows is the axis-0 concatenation.
        return np.concatenate(arrays, axis=0)
    return np.vstack([np.resize(a, width) for a in arrays])


def _optional_column(values: list) -> Optional[np.ndarray]:
    if any(v is None for v in values):
        return None
    return _boxed_column(values)


def _assemble(rows: List[Tuple[_MuscleMemory, int]]) -> MemoryShard:
    """Materialise rows into a single :class:`MemoryShard`.

    ``rows`` holds ``(muscle_memory, index)`` pairs in output order; ``index``
    addresses every field queue of that muscle independently, exactly as the
    legacy ``_MuscleMemory.__getitem__(index)`` did (usually ``-1, -2, ...``).
    """
    if not rows:
        return MemoryShard.concat([])

    def gather(name, default):
        out = []
        for mem, index in rows:
            fifo = mem._field(name)
            out.append(default if fifo is None else fifo.get(index, default))
        return out

    rewards = []
    for mem, index in rows:
        rewards.append(mem.rewards[index])  # Better fail here, like legacy
    return MemoryShard(
        sensor_readings=_infos_column(gather("sensor_readings", [])),
        actuator_setpoints=_infos_column(gather("actuator_setpoints", [])),
        rewards=_infos_column(rewards),
        dones=_boxed_column(gather("dones", [False])),
        observations=_vector_column(gather("observations", [np.nan])),
        actions=_vector_column(gather("actions", [np.nan])),
        objective=_objective_column(gather("objective", [np.nan])),
        additional_data=list(
            itertools.chain.from_iterable(gather("additional_data", []))
        ),
        terminated=_optional_column(gather("terminated", None)),
        truncated=_optional_column(gather("truncated", None)),
        decision_indices=_optional_column(gather("decision_indices", None)),
    )


def _tail_limit(n) -> Optional[int]:
    """Translate ``tail``'s ``n`` into a row limit; ``None`` means all rows.

    The legacy loop stopped when its counter compared equal to ``n``; any
    ``n`` that a non-negative counter never equals (negative or fractional
    numbers, ``None``, ...) therefore returned every matching row.
    """
    try:
        if n >= 0 and n == int(n):
            return int(n)
    except (TypeError, ValueError, OverflowError):
        pass
    return None


class FieldView:
    """Sequence view on the stored values of one field of one muscle.

    Obtained through :meth:`Memory.field_view`.  Supports ``len``,
    iteration, ``reversed``, reading by integer index or slice, and
    replacing a value by integer index.  Indices out of range raise
    ``IndexError``, as with a :class:`collections.deque`.  ``None`` cannot
    be stored, because :meth:`Memory.append` treats ``None`` as "not
    supplied".
    """

    __slots__ = ("_memory", "_muscle_uid", "_field_name")

    def __init__(self, memory: Memory, muscle_uid: str, field_name: str):
        if field_name not in _FIELD_SET:
            raise KeyError(
                f"Unknown memory field {field_name!r}; "
                f"expected one of {', '.join(_FIELDS)}"
            )
        self._memory = memory
        self._muscle_uid = muscle_uid
        self._field_name = field_name

    @property
    def muscle_uid(self) -> str:
        return self._muscle_uid

    @property
    def field_name(self) -> str:
        return self._field_name

    def _fifo(self) -> Optional[_Fifo]:
        mem = self._memory._data.get(self._muscle_uid)
        return None if mem is None else mem._field(self._field_name)

    def __len__(self) -> int:
        fifo = self._fifo()
        return 0 if fifo is None else len(fifo)

    def __iter__(self):
        return iter(list(self._fifo() or ()))

    def __reversed__(self):
        return reversed(list(self._fifo() or ()))

    def __getitem__(self, index):
        fifo = self._fifo()
        if isinstance(index, slice):
            return list(fifo or ())[index]
        if fifo is None:
            raise IndexError("deque index out of range")
        return fifo[index]

    def __setitem__(self, index: int, value):
        if value is None:
            raise ValueError("None cannot be stored in the memory")
        fifo = self._fifo()
        if fifo is None:
            raise IndexError("deque index out of range")
        fifo[index] = value

    def __repr__(self):
        return (
            f"FieldView({self._muscle_uid!r}, {self._field_name!r}, "
            f"len={len(self)})"
        )


[docs] class Memory: """An in-memory data structure to store experiences in a ::`~Brain`. Each agent needs a memory to store experiences, regardless of the training algorithm that is used. This class represents this memory. It is an in-memory data structure that uses pandas DataFrames for its public API. The memory stores observations, actions, rewards given from the environment, and the internal reward of the agent (objective value). The memory is passed to an :class:`~Objective` to calculate the objective value from rewards. Parameters ---------- size_limit : int = 1e6 Maximum size the memory is allowed to grow to until old entries are overwritten by new ones. """ def __init__(self, size_limit: int = int(1e6)): self.size_limit = size_limit self._data: DefaultDict[str, _MuscleMemory] = defaultdict( _MuscleMemory ) self._index: _Fifo = _Fifo() self._next_seq = 0 @property def tags(self) -> Set[str]: """All tags known to this memory""" return set(self._data.keys())
[docs] def append( self, muscle_uid: str, sensor_readings: Optional[List[SensorInformation]] = None, actuator_setpoints: Optional[List[ActuatorInformation]] = None, rewards: Optional[List[RewardInformation]] = None, done: Optional[bool] = None, observations: Optional[np.ndarray] = None, actions: Optional[np.ndarray] = None, objective: Optional[np.ndarray] = None, additional_data: Optional[Dict] = None, *, terminated: Optional[bool] = None, truncated: Optional[bool] = None, decision_index: Optional[int] = None, ): """Stores a new item in the agent's memory (append) Every argument that is not ``None`` is appended to the muscle's queue for that field. An append that carries ``rewards`` creates a new row; other fields are associated with rows by their position from the end of their respective queue (see :meth:`tail`). Parameters ---------- muscle_uid : str UID of the agent (:class:`Muscle`) whose experiences we store sensor_readings : List[SensorInformation] A muscle's sensor readings as provided by the environment actuator_setpoints : List[ActuatorInformation] A muscle's setpoints as provided to an environment rewards : List[RewardInformation] Rewards issued by the environment. It is not necessary that sensor readings, setpoints, and rewards belong to the same time step; usually, rewards at a time step ``t`` belong to the sensor readings and actions from ``t-1``. done : bool = False Whether this was the last action executed in the environment observations : Optional[np.ndarray] = None Observations the :class:`Muscle` wants to share with its :class:`Brain`, e.g., transformed/scaled values actions: Optional[np.ndarray] = None, Action-related data a :class:`Muscle` emitted objective: Optional[np.ndarray] = None The agent's objective value describing its own goal. additional_data : Optional[Dict] = None Any additional data a :class:`Muscle` wants to store. Note that :meth:`tail` *iterates* over this object when concatenating rows (a ``dict`` contributes its keys). terminated : Optional[bool] = None, keyword-only Whether the episode reached a terminal state (win/loss/draw). truncated : Optional[bool] = None, keyword-only Whether the episode was truncated (e.g., time limit reached). decision_index : Optional[int] = None, keyword-only Monotonic identity of the action in its originating worker and episode. ``None`` preserves legacy producer compatibility. """ muscle_memory: _MuscleMemory = self._data[muscle_uid] if sensor_readings is not None: muscle_memory.sensor_readings.append(sensor_readings) if actuator_setpoints is not None: muscle_memory.actuator_setpoints.append(actuator_setpoints) if rewards is not None: muscle_memory.rewards.append(rewards) if additional_data is not None: muscle_memory.additional_data.append(additional_data) if done is not None: muscle_memory.dones.append(done) if terminated is not None: muscle_memory.terminated.append(terminated) if truncated is not None: muscle_memory.truncated.append(truncated) if decision_index is not None: muscle_memory.decision_indices.append(decision_index) if observations is not None: muscle_memory.observations.append(observations) if actions is not None: muscle_memory.actions.append(actions) if objective is not None: muscle_memory.objective.append(objective) if rewards is not None: self._index.append(muscle_uid) muscle_memory._seqs.append(self._next_seq) self._next_seq += 1 self.truncate(self.size_limit)
def _select(self, n, include_only) -> List[Tuple[_MuscleMemory, int]]: """Rows returned by :meth:`tail`, in chronological order.""" limit = _tail_limit(n) if limit == 0: return [] if include_only: tags = self._filter_tags(include_only) if tags is None: return self._select_by_scan(limit, include_only) candidates: List[Tuple[int, str]] = [] for tag in tags: mem = self._data.get(tag) if mem is None: continue seqs = mem._seqs.last(limit) if limit else list(mem._seqs) candidates.extend((s, tag) for s in seqs) candidates.sort() if limit is not None: candidates = candidates[-limit:] selected = [t for _, t in candidates] else: selected = self._index.last(limit) if limit else list(self._index) return self._rows(selected) def _rows(self, selected: List[str]) -> List[Tuple[_MuscleMemory, int]]: """Map chronologically ordered row tags to per-muscle indices. The i-th last selected row of a tag is that tag's ``-i``-th entry, because ``tail`` always selects a suffix of each tag's rows. """ seen: Dict[str, int] = defaultdict(int) rows: List[Tuple[_MuscleMemory, int]] = [] for tag in reversed(selected): seen[tag] += 1 rows.append((self._data[tag], -seen[tag])) rows.reverse() return rows @staticmethod def _filter_tags(include_only) -> Optional[Set[str]]: """``include_only`` as a set of tags, or ``None`` if the legacy ``tag in include_only`` test cannot be expressed as set membership (e.g., a ``str``, which tests for substrings).""" if isinstance(include_only, (list, tuple, set, frozenset)): try: return set(include_only) except TypeError: return None return None def _select_by_scan(self, limit, include_only): selected: List[str] = [] for tag in reversed(self._index): if limit is not None and len(selected) == limit: break if tag not in include_only: continue selected.append(tag) selected.reverse() return self._rows(selected)
[docs] def tail( self, n=1, include_only: Optional[List[str]] = None ) -> MemoryShard: """Returns the n last full entries Returns a :class:`MemoryShard` with the *n* most recent rows, i.e., appends that carried ``rewards``, in chronological order. You access each value through the hierarchy, e.g., shard = memory.tail(10) shard.sensor_readings["uid"].iloc[-1] Every other field of a row is taken from the same position, counted from the end, in that field's queue of the same muscle; if the queue is shorter, a default (``[]``, ``False``, ``NaN``, or ``None``) is used. Parameters ---------- n : int = 1 How many data items to return, counted from the latest addition. Defaults to 1. include_only : Optional list of str, default: None If set, include only data from the given muscles in the list. Returns ------- MemoryShard : The selected rows; each field is materialised once for the whole batch. """ return _assemble(self._select(n, include_only))
[docs] def field_view(self, muscle_uid: str, field_name: str) -> FieldView: """Indexed access to one stored field of one muscle. The view addresses the field's queue directly, i.e., with the same positions :meth:`tail` uses: ``view[-k]`` is the value that the ``k``-th last row of ``muscle_uid`` shows for this field, provided the queue holds at least ``k`` values. Values can be read and replaced in place; the structure (appending, removing) can only be changed through :meth:`append` and :meth:`truncate`. Example: replace the newest objective of a muscle:: objectives = memory.field_view(muscle_uid, "objective") objectives[-1] = np.array([normalized]) Parameters ---------- muscle_uid : str Tag the field belongs to. The view resolves the tag on every access, so it can be created before the first ``append``; it never registers ``muscle_uid`` as a tag. field_name : str Name of a :class:`MemoryShard` field, e.g., ``"objective"``, ``"rewards"``, ``"dones"``, or ``"decision_indices"``. Raises ------ KeyError If ``field_name`` is not a memory field. """ return FieldView(self, muscle_uid, field_name)
[docs] def truncate(self, n: int): """Truncates the memory: Only the last *n* entries are retained. Parameters ---------- n : int How many of the most recent entries should be retained. Negative values of n are treated as ``abs(n)``. """ n = abs(n) if len(self) <= n: return upto_exc = len(self) - n for _ in range(upto_exc): tag = self._index.popleft() mem = self._data[tag] _ = mem.rewards.popleft() # If this crashes, we're in trouble. mem._seqs.popleft() for name in _FIELDS: if name == "rewards": continue fifo = mem._field(name) if fifo: fifo.popleft() if fifo is not None and not fifo: mem._release_if_empty(name)
def __len__(self) -> int: """Returns the number of rows (appends that carried rewards).""" return len(self._index)