# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Reference scoring for pyribs Sphere and LunarLander-v3.
# @see https://docs.pyribs.org/en/latest/tutorials/cma_mae.html#the-sphere-linear-projection-benchmark
# @see https://github.com/icaros-usc/pyribs/blob/v0.12.0/examples/lunar_lander.py
"""Measure candidates with the Sphere and Lunar Lander protocols used by pyribs."""
from dataclasses import dataclass
from operator import index
import numpy as np
__all__ = ["ReferenceBatch", "PyribsSphereBenchmark", "pyribs_sphere", "LunarLanderBenchmark"]
_SPHERE_LIMIT = 5.12
_SPHERE_SHIFT = .4 * _SPHERE_LIMIT
## @brief Raw measurements and simulator accounting for a batch of candidates.
[docs]
@dataclass(frozen=True)
class ReferenceBatch:
"""Fitness and descriptors preserve evaluator order.
Episode lengths count the transitions used for scoring. Simulator steps
also count any computation after termination in a fixed-length scan.
Both are zero for benchmarks without a simulator.
"""
fitness: np.ndarray
descriptors: np.ndarray
episode_steps: np.ndarray
simulator_steps: int
def _batch(genomes, dimension=None, *, dtype=None):
with np.errstate(over="ignore"):
points = np.asarray(genomes, dtype=dtype)
if (points.ndim != 2 or not points.size or (dimension is not None and points.shape[1] != dimension)
or not np.isfinite(points).all()):
raise ValueError("Supply a nonempty matrix of finite genomes with the configured dimension.")
return points
def _count(value, name):
value = index(value)
if value < 1:
raise ValueError(f"{name} must be positive.")
return value
def _seed(seed):
seed = index(seed)
if not 0 <= seed < 2**32:
raise ValueError("Seeds must be unsigned 32-bit integers.")
return seed
## @brief Evaluate shifted Sphere and the reference projections without clamping the inputs.
# @param genomes Nonempty matrix of genomes with at least two coordinates.
# @return Pair of arrays containing raw fitness and two descriptor coordinates per genome.
[docs]
def pyribs_sphere(genomes):
"""Implement the pyribs Sphere linear projection benchmark.
Each out-of-bounds coordinate contributes 5.12 divided by its value
to its descriptor. Fitness uses the original coordinates and may
be negative for points outside the nominal search domain.
"""
points = _batch(genomes, dtype=float)
dimension = points.shape[1]
if dimension < 2:
raise ValueError("Sphere projection uses at least two coordinates.")
worst = dimension * (_SPHERE_LIMIT + _SPHERE_SHIFT) ** 2
with np.errstate(over="ignore"):
cost = np.sum(np.square(points - _SPHERE_SHIFT), axis=1)
if not np.isfinite(cost).all():
raise ValueError("Sphere fitness must be finite.")
fitness = 100. * (1. - cost / worst)
outside = np.abs(points) > _SPHERE_LIMIT
projected = points.copy()
np.divide(_SPHERE_LIMIT, points, out=projected, where=outside)
first_half = dimension // 2
descriptors = np.column_stack((projected[:, :first_half].sum(axis=1), projected[:, first_half:].sum(axis=1)))
return fitness, descriptors
## @brief Parameterize the reference Sphere protocol for a fixed genome dimension.
[docs]
class PyribsSphereBenchmark:
"""Use the two sums as descriptors in physical, unnormalized units."""
name = "sphere"
score_offset = 0.
ind_domain = (-_SPHERE_LIMIT, _SPHERE_LIMIT)
## @param dimension Number of decision variables. The tutorial uses 100.
def __init__(self, dimension=100):
self.dimension = _count(dimension, "dimension")
if self.dimension < 2:
raise ValueError("Sphere projection uses at least two coordinates.")
split = self.dimension // 2
self.features_domain = tuple((-width * _SPHERE_LIMIT, width * _SPHERE_LIMIT)
for width in (split, self.dimension - split))
## @brief Draw a batch uniformly in the nominal decision domain.
def sample(self, count, *, seed=0):
count = _count(count, "count")
return np.random.default_rng(_seed(seed)).uniform(*self.ind_domain, (count, self.dimension))
## @brief Score a batch. The deterministic objective ignores the evaluation seed.
def evaluate_batch(self, genomes, *, seed=0):
points = _batch(genomes, self.dimension, dtype=float)
fitness, descriptors = pyribs_sphere(points)
return ReferenceBatch(fitness, descriptors, np.zeros(len(points), dtype=int), 0)
def _land(env, parameters, seed):
observation, _ = env.reset(seed=seed)
contact = None
lowest_y_velocity = np.inf
total_reward = 0.
steps = 0
while True:
action = int(np.argmax(parameters @ observation))
observation, reward, terminated, truncated, _ = env.step(action)
steps += 1
total_reward += reward
x, velocity = float(observation[0]), float(observation[3])
lowest_y_velocity = min(lowest_y_velocity, velocity)
if contact is None and (observation[6] or observation[7]):
contact = (x, velocity)
if terminated or truncated:
descriptors = contact if contact is not None else (x, lowest_y_velocity)
return total_reward, descriptors, steps
## @brief Score the pyribs linear policy in Gymnasium LunarLander-v3.
[docs]
class LunarLanderBenchmark:
"""Reuse one Box2D environment across candidates and close it when finished.
The first ground contact supplies horizontal position and vertical
velocity. Episodes without contact use final horizontal position and
the lowest vertical velocity observed after a step.
"""
name = "lunar-lander"
score_offset = 600.
features_domain = ((-1., 1.), (-3., 0.))
def __init__(self):
try:
import gymnasium as gym
except ImportError as exc:
raise ImportError('Lunar Lander needs gymnasium[box2d]. Install "gymnasium[box2d]".') from exc
self._env = gym.make("LunarLander-v3")
self._weights_shape = self._env.action_space.n, self._env.observation_space.shape[0]
self.dimension = int(np.prod(self._weights_shape))
## @brief Release the Gymnasium simulator.
def close(self):
self._env.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
## @brief Sample near the reference's zero-weight starting policy.
def sample(self, count, *, seed=0):
count = _count(count, "count")
return np.random.default_rng(_seed(seed)).normal(0., .1, size=(count, self.dimension))
## @brief Score every policy on the specified common reset seed.
def evaluate_batch(self, genomes, *, seed=0):
points = _batch(genomes, self.dimension, dtype=float)
seed = _seed(seed)
fitness, descriptors, steps = zip(*(_land(self._env, row.reshape(self._weights_shape), seed)
for row in points))
return ReferenceBatch(np.asarray(fitness), np.asarray(descriptors), np.asarray(steps), sum(steps))