# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Reuse tabular policies under new linear rewards with successor features.
# @see https://proceedings.neurips.cc/paper/2017/hash/350db081a661525235354dd3e19b8c05-Abstract.html
"""Exact tabular policy evaluation and generalized policy improvement."""
from dataclasses import dataclass
import numpy as np
__all__ = ["SuccessorFeatureRepertoire", "fit_tabular_successor_features"]
## @brief Discounted feature predictions for each archived policy and first action.
[docs]
@dataclass(frozen=True, eq=False)
class SuccessorFeatureRepertoire:
"""The values array is indexed by policy, state, first action, and feature.
Feature returns predict continuing with the source policy after the
first action. GPI chooses the action with the highest value across
all source policies independently at each visited state.
"""
successor_features: np.ndarray
def __post_init__(self):
values = np.array(self.successor_features, dtype=float, copy=True)
if values.ndim != 4 or min(values.shape) < 1 or not np.isfinite(values).all():
raise ValueError("Provide finite successor features with shape (policies, states, actions, features).")
values.setflags(write=False)
object.__setattr__(self, "successor_features", values)
## @brief Evaluate every source policy's action-values under new reward weights.
[docs]
def action_values(self, reward_weights):
"""Return a (policy, state, action) array."""
weights = np.asarray(reward_weights, dtype=float)
if weights.shape != self.successor_features.shape[-1:] or not np.isfinite(weights).all():
raise ValueError("Provide one finite weight per reward feature.")
values = self.successor_features @ weights
if not np.isfinite(values).all():
raise ValueError("Weighted action values must be finite.")
return values
## @brief Return the greedy GPI action for every state.
[docs]
def action_table(self, reward_weights):
"""Break exact ties by choosing the lowest action index."""
return self.action_values(reward_weights).max(axis=0).argmax(axis=1)
def _tabular_model(continuation, features, gamma):
dynamics = np.asarray(continuation, dtype=float)
features = np.asarray(features, dtype=float)
if dynamics.ndim != 3 or min(dynamics.shape) < 1 or dynamics.shape[0] != dynamics.shape[2]:
raise ValueError("continuation must have shape (states, actions, states).")
states, actions, _ = dynamics.shape
mass = dynamics.sum(axis=-1, keepdims=True)
if (not np.isfinite(dynamics).all() or (dynamics < 0.).any() or (mass > 1. + 1e-12).any()
or not 0. <= gamma < 1.):
raise ValueError("Use substochastic nonnegative transitions and 0 <= gamma < 1.")
dynamics = dynamics / np.maximum(mass, 1.)
if (features.ndim != 3 or features.shape[:2] != (states, actions) or not features.shape[2]
or not np.isfinite(features).all()):
raise ValueError("Provide finite expected features with shape (states, actions, features).")
return dynamics, features
## @brief Evaluate a fixed policy repertoire in one finite environment model.
# @param continuation Substochastic array [state, action, successor state].
# @param features Expected immediate feature vector [state, action, feature].
# @param policies Integer action tables [policy, state] or probabilities [policy, state, action].
# @param gamma Discount factor in [0, 1).
# @return Read-only successor-feature predictions for GPI.
[docs]
def fit_tabular_successor_features(continuation, features, policies, *, gamma=.99):
"""Solve each source policy's Bellman system exactly up to float precision.
Missing transition mass denotes termination. Include immediate
features from the terminal outcomes in the expected input features.
Observations and actions are integer indices. All policies transfer
within the same dynamics and reward is linear in the features.
"""
dynamics, features = _tabular_model(continuation, features, gamma)
states, actions, _ = dynamics.shape
policies = np.asarray(policies)
if policies.ndim == 2:
if (policies.dtype.kind not in "iu" or policies.shape[1] != states
or (policies < 0).any() or (policies >= actions).any()):
raise ValueError("Use a policy-by-state table of valid integer actions.")
transition = dynamics[np.arange(states), policies]
immediate = features[np.arange(states), policies]
else:
policies = np.asarray(policies, dtype=float)
if (policies.ndim != 3 or policies.shape[1:] != (states, actions)
or not np.isfinite(policies).all() or (policies < 0.).any()):
raise ValueError("Provide probability distributions over actions for each policy and state.")
totals = policies.sum(axis=-1, keepdims=True)
if not np.allclose(totals, 1., rtol=0., atol=1e-12):
raise ValueError("Each policy's action probabilities must sum to one.")
policies = policies / totals
transition = np.einsum("ksa,sat->kst", policies, dynamics)
immediate = np.einsum("ksa,saf->ksf", policies, features)
if not len(policies):
raise ValueError("Supply at least one source policy.")
state_values = np.linalg.solve(np.eye(states) - gamma * transition, immediate)
action_values = features + gamma * np.einsum("sat,ktf->ksaf", dynamics, state_values)
return SuccessorFeatureRepertoire(action_values)