36 """Run Qin et al.'s tabular operator selector with user-defined variation.
38 Select a parent uniformly from the archive and learn from admission
39 to its offspring's destination cell. A new cell yields one unit of
40 reward, improvement yields a scaled quality gain, and rejection
41 yields zero. The controller advances through batch positions
42 cyclically. Each operator call proposes one candidate.
44 :param archive: Parentless best-only Grid or CVTGrid with native scalar fitness.
45 :param sample: Callable (rng) returning a fresh genome.
46 :param operators: Ordered mapping of names to callbacks (genome, rng).
47 :param batch_size: Number of positions in the cyclic controller state.
48 :param initial_samples: Warm-up attempts, defaulting to batch_size.
49 :param controller: ``q-learning``, ``uniform``, or ``bandit``.
50 :param learning_rate: Initial Q-table step size in (0, 1].
51 :param discount: Bootstrapping coefficient in [0, 1].
52 :param epsilon: Initial exploration probability.
53 :param epsilon_decay: Multiplier applied after each local proposal.
54 :param anneal_batches: Optional batch count for annealing learning_rate toward .01.
55 :param improvement_scale: Positive denominator floor for relative improvement.
56 :param seed: Seed for selection, variation, and evaluator calls.
59 def __init__(self, archive, *, sample, operators, batch_size=16, initial_samples=None,
60 controller="q-learning", learning_rate=.5, discount=.9, epsilon=.3, epsilon_decay=.999,
61 anneal_batches=None, improvement_scale=1e-12, seed=0):
62 if (
not isinstance(archive, Grid)
or archive.parents
or archive.max_items_per_bin != 1
63 or archive.discard_random_on_bin_overload
or archive.fitness_score_names
64 or archive.features_score_names
or len(archive.fitness_domain
or ()) != 1
65 or len(archive.fitness_weights
or ()) != 1
or not isfinite(archive.fitness_weights[0])
66 or not archive.fitness_weights[0]):
67 raise ValueError(
"Supply a parentless best-only grid with one signed native fitness.")
68 if (
not callable(sample)
or not isinstance(operators, Mapping)
or not operators
69 or any(
not isinstance(name, str)
or not name
or not callable(op)
for name, op
in operators.items())):
70 raise ValueError(
"Supply a sampler and a nonempty mapping of named local-search operators.")
71 if (controller
not in (
"q-learning",
"uniform",
"bandit")
or not 0 < learning_rate <= 1
72 or not 0 <= discount <= 1
or not 0 <= epsilon <= 1
or not 0 < epsilon_decay <= 1
73 or not 0 < improvement_scale < np.inf):
74 raise ValueError(
"Use valid controller settings and positive finite improvement_scale.")
77 self.
_size = _positive_int(batch_size,
"batch_size")
78 self.
_warmup = self.
_size if initial_samples
is None else _attempt_budget(initial_samples)
79 self.
_anneal =
None if anneal_batches
is None else _positive_int(anneal_batches,
"anneal_batches")
83 np.random.default_rng, np.random.SeedSequence(seed).spawn(3))
91 """Return a copy of the table in batch position and operator order."""
96 """Return cumulative work and operator counts."""
100 def _action(self, state):
108 unseen = np.flatnonzero(self.
_attempts == 0)
110 return int(self.
_choice.choice(unseen))
112 return int(self.
_choice.choice(np.flatnonzero(scores == scores.max())))
114 def _offer(self, genome, result):
118 quality, features = result
119 descriptor = _finite_vector(features,
"Behavior descriptor", len(self.
archive.features_domain))
120 quality = float(quality)
121 if not isfinite(quality):
122 raise ValueError(
"Fitness must be finite.")
124 if not grid.in_bounds((quality,), grid.fitness_domain)
or not grid.in_bounds(descriptor, grid.features_domain):
126 occupants = grid.solutions[grid.index_grid(descriptor)]
127 previous = grid.get_ind_fitness(occupants[0]).values[0]
if occupants
else None
128 before = grid.nb_added
129 grid.add(
Individual(genome, fitness=
Fitness((quality,), weights=grid.fitness_weights),
131 if grid.nb_added == before:
136 scale = max(abs(previous), abs(quality), self.
_scale)
137 difference = abs(previous / scale - quality / scale)
138 denominator = max(abs(previous), self.
_scale) / scale
139 return 1.
if difference >= denominator
else difference / denominator
145 def run(self, evaluate, budget):
146 """Use the same next batch position when the search is continued."""
147 for _
in range(_attempt_budget(budget)):
149 state = self._local % self.
_size
158 reward = self.
_offer(genome, evaluate(genome, int(self.
_evaluation.integers(2**32))))
163 successor = (state + 1) % self.
_size
165 previous = self.
_values[state, action]
170 progress = min((self._local // self.
_size + 1) / self.
_anneal, 1.)