Binary swarms, geometric policies, and budgeted archives¶
These four searches work with QDpy’s best-only Grid and CVTGrid. The binary swarm counts objective calls, GENE counts environment steps, LUCIE counts noisy observations, and Traveling Thief counts tour solves and packing transitions.
Binary particle swarms driven by novelty¶
Use qdpy.algorithms.NoveltyBinaryPSO when designs are bit
vectors and Hamming distance reflects a meaningful design change.
The swarm compares each particle and its personal leader against the
same memory of previously measured designs. The most novel personal
leader supplies the social term. The passive archive tracks the
actual objective and descriptors for reporting.
from qdpy.algorithms import NoveltyBinaryPSO
from qdpy.containers import Grid
archive = Grid(shape=(4, 4), fitness_domain=((0., 11.),),
features_domain=((0., 3.), (0., 3.)))
weights = (1., 2., 1., 2., 3., 2.)
def evaluate(bits):
fitness = sum(weight * bit for weight, bit in zip(weights, bits))
return fitness, (sum(bits[:3]), sum(bits[3:]))
result = NoveltyBinaryPSO(archive, 6, population_size=8, seed=11).optimise(evaluate, 100)
print(result.evaluations, result.archive_updates, archive.filled_bins)
If feasibility requires repair, pass a callable that returns a bit vector of the original length. Both the archive and swarm will use the repaired design. Keep fitness and descriptors deterministic for a given design. Measurements outside the archive domains still spend a call and enter novelty memory.
The implementation adapts the binary particle update and novelty leaders from Assimi et al.’s structural topology study to a general binary objective with a passive reporting archive.
Geometric encoding for neural MAP-Elites¶
Install the RL extra to use qdpy.rl.GENEMAPElites. It evolves a
coordinate vector per neuron and directly encoded biases. The pL2
decoder subtracts target coordinates from source coordinates for each
connection. It multiplies the Euclidean distance by the product of
those differences clipped to the interval [-1, 1]. Rollouts and
policy export reuse QDpy’s dense PyTorch actors.
import gymnasium as gym
from qdpy.containers import Grid
from qdpy.rl import GENEMAPElites, PolicyConfig
archive = Grid(shape=(8, 8), fitness_domain=((0., 64.),),
features_domain=((-4.8, 4.8), (-0.42, 0.42)))
search = GENEMAPElites(
lambda: gym.make("CartPole-v1"),
archive,
descriptor=lambda episode: (episode.observations[-1, 0], episode.observations[-1, 2]),
max_episode_steps=64, policy=PolicyConfig((32, 32)), coordinate_size=2, seed=11,
)
stats = search.train(1024)
print(stats.env_steps, search.encoding.genome_size, search.encoding.parameter_count)
search.best_policy().save("gene-cartpole.npz")
The deployed policy uses the same format as one produced by
NeuralMAPElites. Load this example with
CategoricalPolicy.load("gene-cartpole.npz"). For Box actions use
ContinuousPolicy.load. During search the archive stores the
geometric genome, so use search.policy_for(elite) to export an
individual cell. Evaluation is sequential. Compare the genome sizes
before choosing this representation for a narrow actor.
See Templier et al., Geometric Encoding for NeuroEvolution, Templier’s thesis for the pL2 equation, and Kunze et al., Illumination of Diverse Neural Cellular Automata for Level Generation for the use of geometric genomes in MAP-Elites.
LUCIE-style races for bounded noisy fitness¶
Use qdpy.algorithms.LUCIEMAPElites when a genome’s cell is
deterministic but its fitness needs repeated measurements. Set
fitness_domain to cover every raw observation. The race starts
with a few challenger samples. If needed it draws a pair of new
observations from the incumbent and challenger and reuses the
incumbent’s earlier samples. Use each evaluator seed for an independent
draw from the same distribution for that genome.
import numpy as np
from qdpy.algorithms import LUCIEMAPElites
from qdpy.containers import Grid
def evaluate(genome, seed):
mean = 0.25 + 0.7 * genome[1]
return float(np.random.default_rng(seed).random() < mean)
archive = Grid(shape=8, fitness_domain=((0., 1.),), features_domain=((0., 1.),))
search = LUCIEMAPElites(archive, 2, epsilon=0.25, initial_samples=4, max_pairs=12, seed=11)
stats = search.run(evaluate, lambda genome: (genome[0],), budget=512)
print(stats.evaluations, stats.certified_races, stats.unresolved_races)
An occupied-cell race is certified when the outsider’s upper bound
is at most epsilon above the empirical leader’s lower bound.
QDpy spends delta across arm creation and sample counts using a
summable Hoeffding allocation. A certificate concerns the two designs
in that race under the confidence event. A restricted budget can leave
a race unresolved. It then keeps the empirical winner, with ties
going to the incumbent. An empty cell takes the challenger directly.
Use elite.scores["rollout_count"] to inspect the sample count behind
an elite’s fitness.
The proposal cap lets a run finish even if descriptors keep falling
outside the grid. Check stats.evaluations for actual usage. Further
calls to run continue with the same sample histories and confidence
allocation. Keep the objective and deterministic descriptor fixed and
let the search own updates to the archive.
The local races follow the setup in Lecarpentier et al., LUCIE: An Evaluation and Selection Method for Stochastic Problems. The run-wide Hoeffding schedule and empirical fallback are QDpy implementation choices.
Bilevel MAP-Elites for Traveling Thief¶
A tour visits each city once and returns to depot zero. Picking up an item earns its profit and increases the carried weight for the remaining legs. The search maximizes profit minus rent times the loaded travel duration. Its archive axes are unloaded tour length and raw item profit.
from qdpy.algorithms import TravelingThiefItem, TravelingThiefMAPElites, TravelingThiefProblem
from qdpy.containers import Grid
problem = TravelingThiefProblem(
[[0., 3., 4.], [3., 0., 2.], [4., 2., 0.]],
[TravelingThiefItem(1, 2, 10.), TravelingThiefItem(2, 3, 14.)],
capacity=4, min_speed=0.25, rent=0.5,
)
archive = Grid(shape=(1, 5), fitness_domain=((-20., 24.),),
features_domain=((9., 9.), (0., 24.)))
search = TravelingThiefMAPElites(problem, archive, seed=11)
stats = search.run(24, seed_tours=[(0, 1, 2), (0, 2, 1)])
print(stats.tour_evaluations, stats.packing_transitions)
print(search.solution_for(archive.best))
Each proposal solves packing exactly for its tour by retaining the best partial score at each reachable integer weight. Two tours with opposite visit orders can have different loaded durations even if their unloaded lengths are identical. The search uses 2-opt after the initial tours. The packing cost grows with the number of reachable weights, so this implementation suits small instances. Archive coverage is over the optimal packings selected for sampled tours.
This variant follows Nikfarjam, A. Neumann and F. Neumann, On the Use of Quality Diversity Algorithms for the Traveling Thief Problem and uses one 2-opt move per offspring with exact integer-weight packing.
Run the base examples and the optional policy comparison from the repository root. See CPU pilots for binary, geometric, and budgeted search for budget definitions and results.
python examples/swarm_packing.py swarm lucie thief
python examples/swarm_packing.py gene --timing