Module likelihood.models.environments

RL environment and action-space definitions.

Functions

def flatten_chain(matrix: List[List[Any]]) ‑> List[Any]
Expand source code
def flatten_chain(matrix: List[List[Any]]) -> List[Any]:
    """Flatten a chain of lists into a single list.

    Parameters
    ----------
    matrix : List[List[Any]]
        A list of lists to be flattened.

    Returns
    -------
    List[Any]
        A single list containing all elements from the nested lists.
    """
    return list(chain.from_iterable(matrix))

Flatten a chain of lists into a single list.

Parameters

matrix : List[List[Any]]
A list of lists to be flattened.

Returns

List[Any]
A single list containing all elements from the nested lists.

Classes

class ActionSpace (num_actions: int)
Expand source code
class ActionSpace:
    """Action space representing a discrete set of actions.

    Parameters
    ----------
    num_actions : int
        The number of possible actions.
    """

    def __init__(self, num_actions: int) -> None:
        self._num_actions = num_actions

    @property
    def n(self) -> int:
        """The number of actions in the space."""
        return self._num_actions

    def save(self, path: str | Path = "./action_space.pkl") -> None:
        """Serialize the action space to disk using pickle.

        Parameters
        ----------
        path : str or pathlib.Path, default="./action_space.pkl"
            Destination file.
        """
        with Path(path).open("wb") as file:
            pickle.dump(self, file)

    @classmethod
    def load(cls, path: str | Path = "./action_space.pkl") -> "ActionSpace":
        """Restore an action space saved with :meth:`save`.

        Parameters
        ----------
        path : str or pathlib.Path, default="./action_space.pkl"
            Checkpoint written by :meth:`save`.

        Returns
        -------
        ActionSpace
            Action space with the stored number of actions.

        Raises
        ------
        TypeError
            If the pickle does not contain an :class:`ActionSpace` instance.

        Notes
        -----
        Checkpoints are pickles, so only load files you trust.
        """
        with Path(path).open("rb") as file:
            space = pickle.load(file)
        if not isinstance(space, cls):
            raise TypeError(f"{str(path)!r} does not contain an ActionSpace instance")
        return space

Action space representing a discrete set of actions.

Parameters

num_actions : int
The number of possible actions.

Static methods

def load(path: str | pathlib.Path = './action_space.pkl') ‑> ActionSpace

Restore an action space saved with :meth:save.

Parameters

path : str or pathlib.Path, default="./action_space.pkl"
Checkpoint written by :meth:save.

Returns

ActionSpace
Action space with the stored number of actions.

Raises

TypeError
If the pickle does not contain an :class:ActionSpace instance.

Notes

Checkpoints are pickles, so only load files you trust.

Instance variables

prop n : int
Expand source code
@property
def n(self) -> int:
    """The number of actions in the space."""
    return self._num_actions

The number of actions in the space.

Methods

def save(self, path: str | pathlib.Path = './action_space.pkl') ‑> None
Expand source code
def save(self, path: str | Path = "./action_space.pkl") -> None:
    """Serialize the action space to disk using pickle.

    Parameters
    ----------
    path : str or pathlib.Path, default="./action_space.pkl"
        Destination file.
    """
    with Path(path).open("wb") as file:
        pickle.dump(self, file)

Serialize the action space to disk using pickle.

Parameters

path : str or pathlib.Path, default="./action_space.pkl"
Destination file.
class OptionCriticEnv (episodes: Dict[int, Dict[str, List]])
Expand source code
class OptionCriticEnv:
    """An environment for Option Critic reinforcement learning that processes a dataset of episodes.

    Attributes
    ----------
    episodes : `Dict[str, Dict]`
        Dataset of episodes with state, action, selected_option, reward, next_state, and done information.
    observation_space : `np.ndarray`
        Initial observation space shape (from first episode's state)
    done : `bool`
        Whether the current episode has terminated
    num_options : `int`
        Number of distinct options available in the dataset
    actions_by_option : `defaultdict(set)`
        Maps selected options to sets of actions that were taken with them
    unique_actions_count : `List[int]`
        Count of unique actions per option index (used for action space definition)
    action_space : `ActionSpace`
        Custom action space defined by unique actions per option
    idx_episode : `int`
        Current episode index being processed
    current_state : `np.ndarray`
        Current state observation in the environment
    """

    def __init__(
        self,
        episodes: Dict[int, Dict[str, List]],
    ) -> None:
        """Initialize the OptionCriticEnv with a dataset of episodes.

        Parameters
        ----------
        episodes : `Dict[int, Dict]`
            Dataset of episodes where keys are episode identifiers and values are episode data.
            Each episode must contain at least:
                - *state*: `List` of state observations
                - *selected_option*: `List[int]` or `List[List[int]]` of selected options
                - *action*: `List[int]` or `List[List[int]]` of actions taken
                - *reward*: `List` of rewards
                - *next_state*: `List` of next states
                - *done*: `List` of termination flags

        Raises
        ------
        ValueError
            If required fields ("state" or "selected_option") are missing from episode data
        """
        self.episodes = episodes
        self.multiple_option = False

        required_keys = ["state", "action", "selected_option", "reward", "next_state", "done"]
        for episode_id, data in episodes.items():
            if not all(k in data for k in required_keys):
                raise ValueError(
                    f"Episode {episode_id} missing keys: {set(required_keys) - set(data.keys())}"
                )

        self.observation_space = np.array(episodes[0]["state"][0])
        self.done = False
        self.idx_episode = 0
        self.current_state = None
        self.num_options = len(
            set(flatten_chain(episodes[0]["selected_option"]))
            if isinstance(episodes[0]["selected_option"][0], list)
            else episodes[0]["selected_option"]
        )
        self.actions_by_option = defaultdict(set)

        # Build fast lookup for transitions
        self.state_action_option_to_transition: Dict[Tuple, Dict[str, Any]] = {}

        for episode_id, data in episodes.items():
            states = data["state"]
            actions = data["action"]
            options = data["selected_option"]
            next_states = data["next_state"]
            rewards = data["reward"]
            dones = data["done"]

            for i in range(len(states)):
                key = self._make_transition_key(
                    states[i],
                    options[i],
                    actions[i],
                )

                self.state_action_option_to_transition[key] = {
                    "next_state": next_states[i],
                    "reward": rewards[i],
                    "done": dones[i],
                }

            for i, selected in enumerate(options):
                self.actions_by_option[
                    tuple(selected) if isinstance(options[0], list) else selected
                ].add(tuple(actions[i]) if isinstance(actions[i], list) else actions[i])

        check_type = list(set([key for key in self.actions_by_option.keys()]))
        keys_actions_by_option = list(self.actions_by_option.keys())
        actions = self.actions_by_option[keys_actions_by_option[0]]

        self.unique_actions_count = [
            len(
                set(
                    flatten_chain(
                        [
                            list(action)
                            for action in self.actions_by_option.get(
                                keys_actions_by_option[i], set()
                            )
                        ]
                    )
                )
                if isinstance(keys_actions_by_option[i], tuple)
                else self.actions_by_option.get(keys_actions_by_option[i], set())
            )
            for i in range(
                max(self.actions_by_option.keys()) + 1
                if not isinstance(check_type[0], tuple)
                else len(set(keys_actions_by_option))
            )
        ]

        self.action_space = ActionSpace(self.unique_actions_count)
        next_states = np.array(
            [trans["next_state"] for trans in self.state_action_option_to_transition.values()]
        )
        self.kdtree = KDTree(next_states)
        self.trans_list = list(self.state_action_option_to_transition.values())

    def _make_transition_key(
        self,
        state: List[float],
        option: Union[int, List[int]],
        action: Union[int, List[int]],
        decimals: int = 6,
    ) -> Tuple:
        """
        Build a canonical transition key.
        ((state_tuple), option(s)..., action(s)...)
        """
        state_key = tuple(round(float(x), decimals) for x in state)

        if isinstance(action, (list, tuple)):
            self.multiple_option = True
            return (state_key,) + tuple(int(o) for o in option) + tuple(int(a) for a in action)
        else:
            return (state_key, int(option), int(action))

    def reset(self) -> tuple[np.ndarray, dict]:
        """Reset the environment to a random episode and returns the initial state.

        Returns
        -------
        observation : `np.ndarray`
            Initial state observation
        info : `Dict`
            Empty dictionary (no additional information)
        """
        episode_id = np.random.choice(list(self.episodes.keys()))
        self.idx_episode = episode_id
        self.current_state = self.episodes[episode_id]["state"][0]
        return self.current_state, {}

    def step(
        self, action: int | List[int], option: int | List[int]
    ) -> tuple[np.ndarray, float, bool, bool, dict]:
        """Take an action with a specific option and returns the next state, reward, and
        termination status.

        Parameters
        ----------
        action : `int` | `List[int]`
            Action index to execute
        option : `int` | `List[int]`
            Selected option index

        Returns
        -------
        next_state : `np.ndarray`
            State after taking the action
        reward : `float`
            Immediate reward for the transition
        done : `bool`
            Whether the episode has terminated (from episode data)
        terminated : `bool`
            Whether the action-option pair was found in the dataset
        info : `Dict`
            Empty dictionary (no additional information)

        Notes
        -----
        - Uses a KD-tree for efficient nearest-neighbor lookup of next states.
        """
        key = self._make_transition_key(
            self.current_state,
            option,
            action,
        )

        if key in self.state_action_option_to_transition:
            trans = self.state_action_option_to_transition[key]
            self.current_state = trans["next_state"]
            return trans["next_state"].copy(), trans["reward"], trans["done"], True, {}
        else:
            # Query KD-tree for nearest neighbor
            distance, idx = self.kdtree.query(self.current_state)
            closest_trans = self.trans_list[idx]
            closest_state = closest_trans["next_state"]

            self.current_state = closest_state.copy()
            return (
                closest_state.copy(),
                closest_trans.get("reward", 0.0),
                closest_trans.get("done", False),
                False,
                {},
            )

An environment for Option Critic reinforcement learning that processes a dataset of episodes.

Attributes

episodes : Dict[str, Dict]
Dataset of episodes with state, action, selected_option, reward, next_state, and done information.
observation_space : np.ndarray
Initial observation space shape (from first episode's state)
done : bool
Whether the current episode has terminated
num_options : int
Number of distinct options available in the dataset
actions_by_option : defaultdict(set)
Maps selected options to sets of actions that were taken with them
unique_actions_count : List[int]
Count of unique actions per option index (used for action space definition)
action_space : ActionSpace
Custom action space defined by unique actions per option
idx_episode : int
Current episode index being processed
current_state : np.ndarray
Current state observation in the environment

Notes

The environment is a simulator derived from the episode dataset (it builds spatial indexes over the transitions), so it is rebuilt from that dataset instead of being checkpointed as a model artifact.

Initialize the OptionCriticEnv with a dataset of episodes.

Parameters

episodes : Dict[int, Dict]
Dataset of episodes where keys are episode identifiers and values are episode data. Each episode must contain at least: - state: List of state observations - selected_option: List[int] or List[List[int]] of selected options - action: List[int] or List[List[int]] of actions taken - reward: List of rewards - next_state: List of next states - done: List of termination flags

Raises

ValueError
If required fields ("state" or "selected_option") are missing from episode data

Methods

def reset(self) ‑> tuple[numpy.ndarray, dict]
Expand source code
def reset(self) -> tuple[np.ndarray, dict]:
    """Reset the environment to a random episode and returns the initial state.

    Returns
    -------
    observation : `np.ndarray`
        Initial state observation
    info : `Dict`
        Empty dictionary (no additional information)
    """
    episode_id = np.random.choice(list(self.episodes.keys()))
    self.idx_episode = episode_id
    self.current_state = self.episodes[episode_id]["state"][0]
    return self.current_state, {}

Reset the environment to a random episode and returns the initial state.

Returns

observation : np.ndarray
Initial state observation
info : Dict
Empty dictionary (no additional information)
def step(self, action: int | List[int], option: int | List[int]) ‑> tuple[numpy.ndarray, float, bool, bool, dict]
Expand source code
def step(
    self, action: int | List[int], option: int | List[int]
) -> tuple[np.ndarray, float, bool, bool, dict]:
    """Take an action with a specific option and returns the next state, reward, and
    termination status.

    Parameters
    ----------
    action : `int` | `List[int]`
        Action index to execute
    option : `int` | `List[int]`
        Selected option index

    Returns
    -------
    next_state : `np.ndarray`
        State after taking the action
    reward : `float`
        Immediate reward for the transition
    done : `bool`
        Whether the episode has terminated (from episode data)
    terminated : `bool`
        Whether the action-option pair was found in the dataset
    info : `Dict`
        Empty dictionary (no additional information)

    Notes
    -----
    - Uses a KD-tree for efficient nearest-neighbor lookup of next states.
    """
    key = self._make_transition_key(
        self.current_state,
        option,
        action,
    )

    if key in self.state_action_option_to_transition:
        trans = self.state_action_option_to_transition[key]
        self.current_state = trans["next_state"]
        return trans["next_state"].copy(), trans["reward"], trans["done"], True, {}
    else:
        # Query KD-tree for nearest neighbor
        distance, idx = self.kdtree.query(self.current_state)
        closest_trans = self.trans_list[idx]
        closest_state = closest_trans["next_state"]

        self.current_state = closest_state.copy()
        return (
            closest_state.copy(),
            closest_trans.get("reward", 0.0),
            closest_trans.get("done", False),
            False,
            {},
        )

Take an action with a specific option and returns the next state, reward, and termination status.

Parameters

action : int` | `List[int]
Action index to execute
option : int` | `List[int]
Selected option index

Returns

next_state : np.ndarray
State after taking the action
reward : float
Immediate reward for the transition
done : bool
Whether the episode has terminated (from episode data)
terminated : bool
Whether the action-option pair was found in the dataset
info : Dict
Empty dictionary (no additional information)

Notes

  • Uses a KD-tree for efficient nearest-neighbor lookup of next states.