QDpy
Loading...
Searching...
No Matches
feasible_diversity.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Run four small quality-diversity comparisons on the CPU."""
6
7import argparse
8import json
9import random
10
11import numpy as np
12
13from qdpy.algorithms import (CMAMAEGA, FeasibleMOME, GradientEvaluation, IsoLineMAPElites,
14 MEPGD, MultiDescriptorNSLC, OMGMEGA)
15from qdpy.containers import Grid, ParetoGrid
16from qdpy.phenotype import Features, Fitness, Individual
17
18
19def evaluate_panel(genome):
20 """Trade off mass and stiffness while satisfying a narrow clearance interval."""
21 length, reinforcement, thickness = genome
22 target = .18 + .55 * (.55 * length + .45 * reinforcement)
23 offset = thickness - target
24 mass = .2 + .45 * reinforcement + .4 * thickness + .1 * length
25 stiffness = .22 + .65 * reinforcement + .33 * thickness - .13 * (length - .45)**2
26 return (mass, stiffness), (length,), {"too_thin": -.021 - offset, "too_thick": offset - .021}
27
28
29def feasible_trial(seed, budget):
30 """Compare the same Pareto selection with and without infeasible parents."""
31 for label, probability in (("FeasibleMOME", .45), ("feasible parents only", 0.)):
32 grid = ParetoGrid(shape=(12,), features_domain=((0., 1.),),
33 fitness_domain=((0., 2.), (0., 2.)), fitness_weights=(-1., 1.),
34 max_items_per_bin=5, truncation="crowding")
35 search = FeasibleMOME(
36 grid, budget, 3, 4, constraint_names=("too_thin", "too_thick"),
37 iso_sigma=.065, line_sigma=.16, infeasible_parent_probability=probability, seed=seed,
38 )
39 feasible = 0
40 while search.nb_evaluations < budget:
41 size = min(search.batch_size, budget - search.nb_evaluations)
42 results = [evaluate_panel(genome) for genome in search.ask_batch(size)]
43 feasible += sum(all(value <= 0. for value in scores.values()) for _, _, scores in results)
44 search.tell_batch(results)
45 yield dict(method=label, seed=seed, evaluations=search.nb_evaluations, feasible_evaluations=feasible,
46 cells=grid.filled_bins, elites=len(grid), auxiliary_cells=len(search.infeasible_elites),
47 qd_hypervolume=grid.qd_hypervolume((2., 0.)))
48
49
50def differentiable_design(genome):
51 """Return an exact objective, descriptors, and their Jacobian."""
52 x, y, z = genome
53 quality = 1. - .30 * (x - .55)**2 - .20 * (y - .5)**2 - .5 * (z - .7)**2
54 return GradientEvaluation(quality, (x, y), [[-.6 * (x - .55), -.4 * (y - .5), .7 - z],
55 [1., 0., 0.], [0., 1., 0.]])
56
57
58def design_measurement(genome):
59 """Measure the same design without computing derivatives."""
60 x, y, z = genome
61 quality = 1. - .30 * (x - .55)**2 - .20 * (y - .5)**2 - .5 * (z - .7)**2
62 return (quality,), (x, y)
63
64
65def gradient_trial(seed, budget, include_cma=False):
66 """Compare analytic and derivative-free searches in the same grid."""
67 kinds = (OMGMEGA, IsoLineMAPElites, CMAMAEGA) if include_cma else (OMGMEGA, IsoLineMAPElites)
68 for kind in kinds:
69 grid = Grid(shape=(8, 8), features_domain=((0., 1.),) * 2,
70 fitness_domain=((0., 1.),), fitness_weights=(1.,))
71 random.seed(seed)
72 np.random.seed(seed)
73 measure = design_measurement
74 if kind is OMGMEGA:
75 search = kind(grid, budget, 3, batch_size=8, sigma=.16, seed=seed)
76 measure = differentiable_design
77 elif kind is CMAMAEGA:
78 search = kind(grid, budget, (.5, .5, .5), .16, 8, 0., gradient_evaluate=differentiable_design,
79 ind_domain=(0., 1.), seed=seed, optimisation_task="maximisation")
80 else:
81 search = kind(grid, budget, 3, batch_size=8, iso_sigma=.13,
82 optimisation_task="maximisation")
83 search.optimise(measure)
84 yield dict(method=kind.__name__, seed=seed, evaluations=search.nb_evaluations,
85 gradients=getattr(search, "gradient_evaluations", 0), cells=grid.filled_bins,
86 qd_score=float(sum(item.fitness.values[0] for item in grid)))
87
88
89_MOVES = ((1, 0), (-1, 0), (0, 1), (0, -1))
90
91
92def measure_route(genome):
93 """Measure route style, ending coordinates, and success in a two-door maze."""
94 x, y = 1, 3
95 previous, turns, y_sum, door = None, 0, 0, None
96 for length, gene in enumerate(genome, start=1):
97 action = min(3, int(4 * gene))
98 dx, dy = _MOVES[action]
99 col, row = x + dx, y + dy
100 if 0 <= col < 7 and 0 <= row < 7 and (col != 3 or row in (0, 6)):
101 x, y = col, row
102 if x == 3 and door is None:
103 door = y
104 turns += previous is not None and previous != action
105 previous = action
106 y_sum += y
107 if (x, y) == (5, 3):
108 break
109 distance = abs(5 - x) + abs(3 - y)
110 return (1. / (1. + distance),), (y_sum / (6 * length), turns / max(1, length - 1)), (x / 6, y / 6), door
111
112
113def nslc_trial(seed, budget):
114 """Compare reporting-view local competition with and without endpoint novelty."""
115 for label, use_exploration in (("NS–NSLC", True), ("reporting view only", False)):
116 search = MultiDescriptorNSLC(budget, 18, 24, 12, reference_capacity=48, k=6,
117 sigma=.16, seed=seed, optimisation_task="maximisation")
118 styles = Grid(shape=(8, 8), features_domain=((0., 1.),) * 2, fitness_domain=((0., 1.),))
119 endpoints, goals = set(), set()
120
121 def evaluate(genome):
122 fitness, features, endpoint, door = measure_route(genome)
123 endpoints.add(endpoint)
124 if fitness[0] == 1.:
125 goals.add(door)
126 return fitness, features, {"exploration": endpoint if use_exploration else (0., 0.)}
127
128 search.optimise(evaluate)
129 yield dict(method=label, seed=seed, evaluations=search.nb_evaluations,
130 terminal_cells=len(endpoints), retained_styles=len({styles.index_grid(item) for item in search.container}),
131 goal_door_count=len(goals), best_fitness=search.best().fitness.values[0])
132
133
134STAIR_FITNESS = (.7, .61, .52, .43, .8, .86, .91, .95, 1.)
135
136
137def deceptive_path(genome):
138 """Reach a new cell only after losing fitness several times in the first cell."""
139 step = int(round(genome[0] * 8))
140 return (STAIR_FITNESS[step],), (max(0, step - 3) / 5,)
141
142
143def breeder_trial(seed, budget):
144 """Use identical start and mutation, with or without a second breeding slot."""
145 def mutate(parent, rng):
146 move = rng.choice((-1, 1))
147 return (float(np.clip(parent[0] + move / 8., 0., 1.)),)
148
149 for label, probability in (("MEPGD", .3), ("primary slot only", 0.)):
150 grid = Grid(shape=(6,), features_domain=((0., 1.),), fitness_domain=((0., 1.),), fitness_weights=(1.,))
151 search = MEPGD(grid, budget - 1, 1, replacement_probability=probability, mutate=mutate, seed=seed)
152 fitness, features = deceptive_path((0.,))
153 grid.add(Individual([0.], fitness=Fitness(fitness, weights=(1.,)), features=Features(features)))
154 search.optimise(deceptive_path)
155 yield dict(method=label, seed=seed, evaluations=search.nb_evaluations + 1,
156 cells=grid.filled_bins, best_fitness=grid.best.fitness.values[0],
157 auxiliary_admissions=search.auxiliary_admissions)
158
159
160if __name__ == "__main__":
161 trials = {"mome": (feasible_trial, 320), "gradient": (gradient_trial, 352),
162 "nslc": (nslc_trial, 576), "breeder": (breeder_trial, 192)}
163 parser = argparse.ArgumentParser(description=__doc__)
164 parser.add_argument("task", choices=trials)
165 parser.add_argument("--budget", type=int)
166 parser.add_argument("--seeds", nargs="+", type=int, default=[11, 22, 33])
167 parser.add_argument("--include-cma", action="store_true", help="add CMA-MAEGA to the gradient comparison")
168 args = parser.parse_args()
169 trial, default_budget = trials[args.task]
170 budget = default_budget if args.budget is None else args.budget
171 if budget < 2:
172 parser.error("Use an evaluation budget of at least two.")
173 for seed in args.seeds:
174 extra = {"include_cma": args.include_cma} if args.task == "gradient" else {}
175 for row in trial(seed, budget, **extra):
176 print(json.dumps(row, sort_keys=True))