QDpy
Loading...
Searching...
No Matches
reference.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
6
7"""Measure candidates with the Sphere and Lunar Lander protocols used by pyribs."""
8
9from dataclasses import dataclass
10from operator import index
11
12import numpy as np
13
14__all__ = ["ReferenceBatch", "PyribsSphereBenchmark", "pyribs_sphere", "LunarLanderBenchmark"]
15
16_SPHERE_LIMIT = 5.12
17_SPHERE_SHIFT = .4 * _SPHERE_LIMIT
18
19
20
21@dataclass(frozen=True)
23 """Fitness and descriptors preserve evaluator order.
24
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.
28 """
29
30 fitness: np.ndarray
31 descriptors: np.ndarray
32 episode_steps: np.ndarray
33 simulator_steps: int
34
35
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.")
42 return points
43
44
45def _count(value, name):
46 value = index(value)
47 if value < 1:
48 raise ValueError(f"{name} must be positive.")
49 return value
50
51
52def _seed(seed):
53 seed = index(seed)
54 if not 0 <= seed < 2**32:
55 raise ValueError("Seeds must be unsigned 32-bit integers.")
56 return seed
57
58
59
62def pyribs_sphere(genomes):
63 """Implement the pyribs Sphere linear projection benchmark.
64
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.
68 """
69 points = _batch(genomes, dtype=float)
70 dimension = points.shape[1]
71 if dimension < 2:
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
85
86
87
89 """Use the two sums as descriptors in physical, unnormalized units."""
90
91 name = "sphere"
92 score_offset = 0.
93 ind_domain = (-_SPHERE_LIMIT, _SPHERE_LIMIT)
94
95
96 def __init__(self, dimension=100):
97 self.dimension = _count(dimension, "dimension")
98 if self.dimension < 2:
99 raise ValueError("Sphere projection uses at least two coordinates.")
100 split = self.dimension // 2
101 self.features_domain = tuple((-width * _SPHERE_LIMIT, width * _SPHERE_LIMIT)
102 for width in (split, self.dimension - split))
103
104
105 def sample(self, count, *, seed=0):
106 count = _count(count, "count")
107 return np.random.default_rng(_seed(seed)).uniform(*self.ind_domain, (count, self.dimension))
108
109
110 def evaluate_batch(self, genomes, *, seed=0):
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)
114
115
116def _land(env, parameters, seed):
117 observation, _ = env.reset(seed=seed)
118 contact = None
119 lowest_y_velocity = np.inf
120 total_reward = 0.
121 steps = 0
122 while True:
123 action = int(np.argmax(parameters @ observation))
124 observation, reward, terminated, truncated, _ = env.step(action)
125 steps += 1
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
134
135
136
138 """Reuse one Box2D environment across candidates and close it when finished.
139
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.
143 """
144
145 name = "lunar-lander"
146 score_offset = 600.
147 features_domain = ((-1., 1.), (-3., 0.))
148
149 def __init__(self):
150 try:
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")
155 self._weights_shape = self._env.action_space.n, self._env.observation_space.shape[0]
156 self.dimension = int(np.prod(self._weights_shape))
157
158
159 def close(self):
160 self._env.close()
161
162 def __enter__(self):
163 return self
164
165 def __exit__(self, exc_type, exc_value, traceback):
166 self.close()
167
168
169 def sample(self, count, *, seed=0):
170 count = _count(count, "count")
171 return np.random.default_rng(_seed(seed)).normal(0., .1, size=(count, self.dimension))
172
173
174 def evaluate_batch(self, genomes, *, seed=0):
175 points = _batch(genomes, self.dimension, dtype=float)
176 seed = _seed(seed)
177 fitness, descriptors, steps = zip(*(_land(self._env, row.reshape(self._weights_shape), seed)
178 for row in points))
179 return ReferenceBatch(np.asarray(fitness), np.asarray(descriptors), np.asarray(steps), sum(steps))
Score the pyribs linear policy in Gymnasium LunarLander-v3.
Definition reference.py:137
evaluate_batch(self, genomes, *, seed=0)
Score every policy on the specified common reset seed.
Definition reference.py:174
close(self)
Release the Gymnasium simulator.
Definition reference.py:159
sample(self, count, *, seed=0)
Sample near the reference's zero-weight starting policy.
Definition reference.py:169
Parameterize the reference Sphere protocol for a fixed genome dimension.
Definition reference.py:88
evaluate_batch(self, genomes, *, seed=0)
Score a batch.
Definition reference.py:110
sample(self, count, *, seed=0)
Draw a batch uniformly in the nominal decision domain.
Definition reference.py:105
Raw measurements and simulator accounting for a batch of candidates.
Definition reference.py:22