7"""Measure candidates with the Sphere and Lunar Lander protocols used by pyribs."""
9from dataclasses
import dataclass
10from operator
import index
14__all__ = [
"ReferenceBatch",
"PyribsSphereBenchmark",
"pyribs_sphere",
"LunarLanderBenchmark"]
17_SPHERE_SHIFT = .4 * _SPHERE_LIMIT
21@dataclass(frozen=True)
23 """Fitness and descriptors preserve evaluator order.
25 Episode lengths count the transitions used for scoring. Simulator steps
26 also count any computation after termination in a fixed-length scan.
27 Both are zero for benchmarks without a simulator.
31 descriptors: np.ndarray
32 episode_steps: np.ndarray
36def _batch(genomes, dimension=None, *, dtype=None):
37 with np.errstate(over=
"ignore"):
38 points = np.asarray(genomes, dtype=dtype)
39 if (points.ndim != 2
or not points.size
or (dimension
is not None and points.shape[1] != dimension)
40 or not np.isfinite(points).all()):
41 raise ValueError(
"Supply a nonempty matrix of finite genomes with the configured dimension.")
45def _count(value, name):
48 raise ValueError(f
"{name} must be positive.")
54 if not 0 <= seed < 2**32:
55 raise ValueError(
"Seeds must be unsigned 32-bit integers.")
62def pyribs_sphere(genomes):
63 """Implement the pyribs Sphere linear projection benchmark.
65 Each out-of-bounds coordinate contributes 5.12 divided by its value
66 to its descriptor. Fitness uses the original coordinates and may
67 be negative for points outside the nominal search domain.
69 points = _batch(genomes, dtype=float)
70 dimension = points.shape[1]
72 raise ValueError(
"Sphere projection uses at least two coordinates.")
73 worst = dimension * (_SPHERE_LIMIT + _SPHERE_SHIFT) ** 2
74 with np.errstate(over=
"ignore"):
75 cost = np.sum(np.square(points - _SPHERE_SHIFT), axis=1)
76 if not np.isfinite(cost).all():
77 raise ValueError(
"Sphere fitness must be finite.")
78 fitness = 100. * (1. - cost / worst)
79 outside = np.abs(points) > _SPHERE_LIMIT
80 projected = points.copy()
81 np.divide(_SPHERE_LIMIT, points, out=projected, where=outside)
82 first_half = dimension // 2
83 descriptors = np.column_stack((projected[:, :first_half].sum(axis=1), projected[:, first_half:].sum(axis=1)))
84 return fitness, descriptors
89 """Use the two sums as descriptors in physical, unnormalized units."""
93 ind_domain = (-_SPHERE_LIMIT, _SPHERE_LIMIT)
97 self.
dimension = _count(dimension,
"dimension")
99 raise ValueError(
"Sphere projection uses at least two coordinates.")
101 self.
features_domain = tuple((-width * _SPHERE_LIMIT, width * _SPHERE_LIMIT)
102 for width
in (split, self.
dimension - split))
106 count = _count(count,
"count")
107 return np.random.default_rng(_seed(seed)).uniform(*self.
ind_domain, (count, self.
dimension))
111 points = _batch(genomes, self.
dimension, dtype=float)
112 fitness, descriptors = pyribs_sphere(points)
113 return ReferenceBatch(fitness, descriptors, np.zeros(len(points), dtype=int), 0)
116def _land(env, parameters, seed):
117 observation, _ = env.reset(seed=seed)
119 lowest_y_velocity = np.inf
123 action = int(np.argmax(parameters @ observation))
124 observation, reward, terminated, truncated, _ = env.step(action)
126 total_reward += reward
127 x, velocity = float(observation[0]), float(observation[3])
128 lowest_y_velocity = min(lowest_y_velocity, velocity)
129 if contact
is None and (observation[6]
or observation[7]):
130 contact = (x, velocity)
131 if terminated
or truncated:
132 descriptors = contact
if contact
is not None else (x, lowest_y_velocity)
133 return total_reward, descriptors, steps
138 """Reuse one Box2D environment across candidates and close it when finished.
140 The first ground contact supplies horizontal position and vertical
141 velocity. Episodes without contact use final horizontal position and
142 the lowest vertical velocity observed after a step.
145 name =
"lunar-lander"
147 features_domain = ((-1., 1.), (-3., 0.))
151 import gymnasium
as gym
152 except ImportError
as exc:
153 raise ImportError(
'Lunar Lander needs gymnasium[box2d]. Install "gymnasium[box2d]".')
from exc
154 self.
_env = gym.make(
"LunarLander-v3")
165 def __exit__(self, exc_type, exc_value, traceback):
170 count = _count(count,
"count")
171 return np.random.default_rng(_seed(seed)).normal(0., .1, size=(count, self.
dimension))
175 points = _batch(genomes, self.
dimension, dtype=float)
177 fitness, descriptors, steps = zip(*(_land(self.
_env, row.reshape(self.
_weights_shape), seed)
179 return ReferenceBatch(np.asarray(fitness), np.asarray(descriptors), np.asarray(steps), sum(steps))
Score the pyribs linear policy in Gymnasium LunarLander-v3.
evaluate_batch(self, genomes, *, seed=0)
Score every policy on the specified common reset seed.
close(self)
Release the Gymnasium simulator.
sample(self, count, *, seed=0)
Sample near the reference's zero-weight starting policy.
Parameterize the reference Sphere protocol for a fixed genome dimension.
evaluate_batch(self, genomes, *, seed=0)
Score a batch.
sample(self, count, *, seed=0)
Draw a batch uniformly in the nominal decision domain.
__init__(self, dimension=100)
Raw measurements and simulator accounting for a batch of candidates.