Differential evolution, mixed variables, and learned preferences ================================================================ Differential MAP-Elites, mixed Bayesian QD, and preference-learning emitters use the base installation. Diverse Quality Species (DQS) uses ``qdpy[rl]``. The :doc:`mixed_preference_benchmarks` page reports seeded comparisons for all four. .. _differential-map-elites: Differential MAP-Elites ----------------------- Differential MAP-Elites chooses a target and three donors from distinct occupied cells. It adds a scaled difference between two donors to the third, clips the result to the genome bounds, and crosses it with the target. At least one coordinate comes from the donor vector. The offspring competes in the cell determined by its measured descriptors. .. code-block:: python from qdpy.algorithms import DifferentialMAPElites from qdpy.containers import CVTGrid archive = CVTGrid(shape=(9,), centroids=[[x, y] for x in (.15, .5, .85) for y in (.15, .5, .85)], features_domain=((0., 1.),) * 2, fitness_domain=((0., 1.),), fitness_weights=(1.,)) def evaluate(candidate): x, y, z = candidate return (1. / (1. + (z - x * y)**2),), (x, y) search = DifferentialMAPElites(archive, budget=96, dimension=3, initial_samples=16, scaling_factor=.5, crossover_rate=.9, batch_size=1, seed=7) search.optimise(evaluate) print(archive.filled_bins, search.differential_proposals) Uniform proposals continue until four cells are occupied. Use ``initial_samples=0`` to begin breeding immediately with a suitable seed archive. With batches above one, all candidates are generated against the same archive snapshot. The measured results are applied in proposal order. You can use a rectangular Grid with the same variation operator. Run ``python examples/differential_mixed_preference.py differential`` to compare with Iso+LineDD on two rotated functions using common initial points. See `Choi and Togelius `_ for the original CVT method. .. _mixed-variable-bayesian-qd: Mixed-variable Bayesian QD -------------------------- Use mixed Bayesian QD when you can only afford a limited number of evaluations and your design space contains real and discrete choices. Pass ``RealVariable``, ``IntegerVariable``, and ``CategoricalVariable`` specifications in genome order. ``decode()`` returns the original categorical labels. Return one finite residual per constraint. Residuals at most zero satisfy their constraints. .. code-block:: python from qdpy.algorithms import (CategoricalVariable, IntegerVariable, MixedBayesianQD, RealVariable) from qdpy.containers import Grid archive = Grid(shape=(8, 4), features_domain=((0., 1.),) * 2, fitness_domain=((0., 3.),), fitness_weights=(1.,)) variables = (RealVariable(0., 1.), IntegerVariable(1, 4), CategoricalVariable(("light", "dense"))) search = MixedBayesianQD(archive, 36, variables, constraint_names=("load",), initial_samples=8, surrogate_budget=48, batch_size=4, seed=7) def evaluate(candidate): width, ribs, material = search.decode(candidate) limit = .60 if material == "light" else .95 return (1. + width + .1 * ribs,), (width, (ribs - 1) / 3), { "load": width + .1 * ribs - limit, } search.optimise(evaluate) print(search.nb_evaluations, search.surrogate_evaluations, archive.filled_bins) The model uses a Gaussian kernel on scaled real coordinates and the compound-symmetry (Gower) kernel on integers and categories. Each discrete coordinate contributes one covariance factor when its levels differ. The GPs predict objective, descriptors and residuals independently. They share the covariance matrix and a fixed kernel scale. Exact measurements outside the feasible region or reporting grid still inform the models when their outputs are finite. The auxiliary search bins candidates by predicted mean descriptors, ranks them by expected constraint violation and optimistic quality, and promotes candidates from cells targeted by a Sobol stream. It returns to mixed-space sampling when the auxiliary archive offers too few candidates. The measured grid contains only feasible records. Use ``surrogate_evaluations`` to measure acquisition work separately from exact evaluations. Finite spaces can repeat designs once the sampler stops finding unseen candidates. Run ``python examples/differential_mixed_preference.py mixed`` for an equal-budget comparison with mixed Constrained MAP-Elites. See `Brevault and Balesdent `_ for the acquisition and discrete covariance. .. _preference-learning-emitters: Preference-learning emitters ---------------------------- A preference-learning emitter learns where to choose parents from a user's choices across several archive displays. The archive still stores elites according to the evaluator's fitness and descriptors. The default model is ridge regression over normalized descriptors. Its training rows contain the selected cells and the other occupied cells the user saw. The tabular option counts selections over the same recent window. Both models mix their predicted parent distribution with a uniform draw. .. code-block:: python from qdpy.algorithms import PreferenceLearningMAPElites from qdpy.containers import Grid archive = Grid(shape=(8, 8), features_domain=((0., 1.),) * 2, fitness_domain=((0., 1.),), fitness_weights=(1.,)) search = PreferenceLearningMAPElites(archive, 48, 2, batch_size=12, seed=7) def evaluate(candidate): x, y = candidate return (1. - (x - .5)**2 - (y - .5)**2,), (x, y) first = search.ask_batch() search.tell_batch([evaluate(candidate) for candidate in first]) displayed = [cell for cell, entries in archive.solutions.items() if entries] # A scripted choice stands in for a user selection in this example. preferred = max(displayed, key=lambda cell: cell[1]) search.record_feedback([preferred], displayed=displayed) print(search.parent_probabilities()[preferred]) offspring = search.ask_batch() search.tell_batch([evaluate(candidate) for candidate in offspring]) Keep the archive snapshot fixed until you record feedback for that display. Pass ``displayed`` if the interface shows a subset of the cells. With custom model features, return a finite vector of the same size for every evaluated elite. Use ``mode="uniform"`` to compare the automated phase with an ordinary uniform emitter while recording the same feedback. Run ``python examples/differential_mixed_preference.py preference`` to compare ridge, tabular and uniform emitters with a scripted chooser. The `paper by Gallotta et al. `_ describes additional predictors and selection strategies. .. _diverse-quality-species: Diverse Quality Species ----------------------- DQS keeps equal-sized species of continuous policies. A discriminator learns which species visited each successor state. The TD3 critic uses task reward plus a bonus for visiting states the discriminator associates with the policy's species. Policies retain their species throughout training. Each generation remeasures the entire population and ranks members by running mean task return. Cloned offspring learn from replay states gathered by their own species. .. code-block:: python from qdpy.containers import Grid from qdpy.rl import DiverseQualitySpecies, PolicyConfig, TD3Config from examples.dqs import TwoPeaks search = DiverseQualitySpecies( TwoPeaks, num_species=2, species_size=3, elites=1, policy=PolicyConfig((12,)), max_episode_steps=12, gradient_steps=2, td3=TD3Config(batch_size=16, learning_starts=16), seed=7, ) stats = search.train(144) geometry = Grid(shape=(9,), features_domain=((-1., 1.),), fitness_domain=((0., 12.),), fitness_weights=(1.,)) audit = search.evaluate( episodes=2, seed=99, best_per_species=True, archive=geometry, descriptor=lambda episode: (float(episode.observations[:-1, 0].mean()),), ) print(stats.env_steps, audit.env_steps, audit.archive.filled_bins) policy = search.best_policy() Training uses a single Gymnasium environment with numeric Box observations and bounded floating-point Box actions. A cut episode still provides replay transitions. Only complete episodes change policy rankings, and the next training call retries the interrupted member. Audit a species' best policy with ``best_per_species=True``. Omit that setting to audit every current member with a completed measurement. The audit uses a common set of fresh reset seeds and returns its own archive. Save an individual actor with ``policy.save(path)`` and reload it with ``ContinuousPolicy.load(path)``. Run ``python examples/dqs.py`` to compare DQS with a zero-bonus control and DOMiNO. `Wickman et al. `_ describe the species-conditioned TD3 update and the information objective.