# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Build a tabular successor-feature repertoire using optimistic linear support.
# @see https://proceedings.mlr.press/v162/alegre22a.html
"""Optimistic linear support on the nonnegative reward simplex."""
from dataclasses import dataclass
from itertools import combinations
import numpy as np
from scipy.optimize import linprog
from .modern import _positive_int
from .successor_repertoire import SuccessorFeatureRepertoire, _tabular_model, fit_tabular_successor_features
__all__ = ["SFOLSResult", "tabular_optimal_policy", "tabular_sfols"]
## @brief A policy repertoire, solved reward weights, and the residual optimistic gap.
[docs]
@dataclass(frozen=True)
class SFOLSResult:
"""Coverage and the gap refer to the supplied start-state distribution.
upper_gap is None if the budget was too small to solve every unit
reward. Read the finite gap with the policy and LP solver tolerances.
Each row of feature_returns reports one retained policy's start value.
"""
repertoire: SuccessorFeatureRepertoire
policies: tuple[tuple[int, ...], ...]
feature_returns: tuple[tuple[float, ...], ...]
solved_weights: tuple[tuple[float, ...], ...]
upper_gap: float | None
converged: bool
bound_solves: int
@property
def policy_solves(self):
"""Count supported weights sent to the scalar policy solver."""
return len(self.solved_weights)
def _optimal(dynamics, reward, gamma):
indices = np.arange(len(reward))
policy = reward.argmax(axis=1)
identity = np.eye(len(reward))
precision = 64 * np.finfo(float).eps
while True:
values = np.linalg.solve(identity - gamma * dynamics[indices, policy], reward[indices, policy])
actions = reward + gamma * (dynamics @ values)
if not np.isfinite(actions).all() or not np.isfinite(values).all():
raise ValueError("Scalar policy evaluation produced nonfinite values.")
best = actions.argmax(axis=1)
residual = actions[indices, best] - actions[indices, policy]
improve = residual > precision * max(1., np.max(abs(actions)))
if not improve.any():
bellman_residual = max(0., float(np.max(actions[indices, best] - values)))
return policy, bellman_residual / (1. - gamma)
policy[improve] = best[improve]
## @brief Compute a deterministic scalar-optimal policy by finite-state policy iteration.
[docs]
def tabular_optimal_policy(continuation, features, reward_weights, *, gamma=.99):
"""Return the integer action table for a fixed linear reward."""
dynamics, features = _tabular_model(continuation, features, gamma)
weights = np.asarray(reward_weights, dtype=float)
if weights.shape != features.shape[-1:] or not np.isfinite(weights).all():
raise ValueError("Provide one finite scalar reward weight per feature.")
policy, _ = _optimal(dynamics, features @ weights, gamma)
return tuple(map(int, policy))
def _corners(values):
"""Enumerate vertices of each policy's region on the reward simplex."""
dimensions = values.shape[1]
unit = np.eye(dimensions)
ones = np.ones(dimensions)
right = unit[-1]
corners = {tuple(row) for row in unit}
for active in values:
deltas = active - values
scale = np.max(abs(deltas), axis=1)
directions = deltas[scale > 0.] / scale[scale > 0., None]
boundaries = np.vstack((unit, directions))
for rows in combinations(boundaries, dimensions - 1):
try:
point = np.linalg.solve(np.vstack((*rows, ones)), right)
except np.linalg.LinAlgError:
continue
if (point < -1e-10).any() or (directions @ point < -1e-10).any():
continue
point = point.clip(min=0.)
point = (point / point.sum()).round(12)
corners.add(tuple(map(float, point / point.sum())))
return tuple(sorted(corners))
## @brief Learn a finite-state policy repertoire for a simplex of linear rewards.
# @param continuation Substochastic transition array [state, action, state].
# @param features Expected immediate feature array [state, action, feature].
# @param start Initial-state probability vector.
# @param gamma Discount in [0, 1).
# @param max_policy_solves Hard cap on scalar optimal-policy queries.
# @param tolerance Target absolute gap in discounted reward.
# @return Supported policies, their successor features, and search accounting.
[docs]
def tabular_sfols(continuation, features, start, *, gamma=.99, max_policy_solves=32, tolerance=1e-7):
"""Solve the most promising corner of the current policy envelope next.
The search first solves unit reward weights. For each corner of
the current piecewise-linear value envelope, a linear program
bounds the value of any unknown policy using the solved tasks.
Numerical roundoff in policy evaluation is tracked through
a Bellman residual bound. Corner enumeration is intended for small
reward spaces. Auditing uses the supplied start distribution.
"""
dynamics, features = _tabular_model(continuation, features, gamma)
budget = _positive_int(max_policy_solves, "max_policy_solves")
start = np.asarray(start, dtype=float)
if (start.shape != (len(dynamics),) or not np.isfinite(start).all() or (start < 0.).any()
or not np.isclose(start.sum(), 1., rtol=0., atol=1e-12) or not 0. < tolerance < np.inf):
raise ValueError("Supply a start distribution and positive finite tolerance.")
start = start / start.sum()
dimension = features.shape[-1]
states = np.arange(len(dynamics))
identity = np.eye(len(dynamics))
records, policies = {}, {}
bound_solves = 0
def evaluate(weights):
action, residual = _optimal(dynamics, features @ weights, gamma)
matrix = identity - gamma * dynamics[states, action]
value = start @ np.linalg.solve(matrix, features[states, action])
bound = float(value @ weights) + residual
if not np.isfinite(value).all() or not np.isfinite(bound):
raise ValueError("SFOLS produced nonfinite feature returns or bounds.")
records[weights] = bound
policies.setdefault(tuple(map(int, action)), tuple(map(float, value)))
for corner in np.eye(dimension)[:budget]:
evaluate(tuple(map(float, corner)))
gap = None
if len(records) == dimension:
while True:
values = np.asarray(tuple(policies.values()))
candidates = []
for corner in _corners(values):
lower = float((values @ corner).max())
if corner in records:
upper = records[corner]
else:
# Bounding each objective by its unit task improves numerical conditioning.
lin = linprog(-np.asarray(corner), A_ub=np.asarray(tuple(records)),
b_ub=np.asarray(tuple(records.values())), bounds=(None, None), method="highs")
bound_solves += 1
if not lin.success:
raise RuntimeError(f"SFOLS could not bound an unsolved reward: {lin.message}")
upper = -float(lin.fun)
candidates.append((max(0., upper - lower), corner))
gap = max(value for value, _ in candidates)
pending = [(value, corner) for value, corner in candidates if corner not in records]
if gap <= tolerance or not pending or len(records) == budget:
break
gain, target = max(pending)
if gain <= tolerance:
break
evaluate(target)
repertoire = fit_tabular_successor_features(dynamics, features, tuple(policies), gamma=gamma)
return SFOLSResult(repertoire, tuple(policies), tuple(policies.values()), tuple(records), gap,
gap is not None and gap <= tolerance, bound_solves)