QDpy
Loading...
Searching...
No Matches
differential_mixed_preference.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Reproducible CPU studies for bounded search and interactive illumination."""
6
7import argparse
8import json
9import math
10from time import perf_counter
11
12import numpy as np
13
14from qdpy.algorithms import (CategoricalVariable, ConstrainedMAPElites,
15 DifferentialMAPElites, IntegerVariable, IsoLineMAPElites,
16 MixedBayesianQD, PreferenceLearningMAPElites, RealVariable)
17from qdpy.containers import CVTGrid, Grid
18from qdpy.phenotype import Features, Fitness, Individual
19from qdpy.simple import _coordinator_seed
20
21
22
23def differential_trial(seed, budget):
24 """Use a rotated ill-conditioned ellipsoid and a rotated Rastrigin function."""
25 dimension = 10
26 bounds = (-5.12, 5.12)
27 domain = (bounds, bounds)
28 axes = np.linspace(-4.48, 4.48, 8)
29 centers = [(a, b) for a in axes for b in axes]
30 rng = np.random.default_rng(seed)
31 rotation, _ = np.linalg.qr(rng.normal(size=(dimension, dimension)))
32 warmup = min(24, budget - 1)
33 warm = rng.uniform(*bounds, size=(warmup, dimension))
34 weights = np.geomspace(1., 1e4, dimension)
35
36 for landscape in ("ellipsoid", "rastrigin"):
37 for method in ("differential", "iso_line"):
38 archive = CVTGrid(shape=(len(centers),), centroids=centers, features_domain=domain,
39 fitness_domain=((0., 1.),), fitness_weights=(1.,))
40
41 def evaluate(genome):
42 rotated = rotation @ genome
43 error = (np.sum(weights * rotated ** 2) if landscape == "ellipsoid"
44 else np.sum(rotated ** 2 + 10 * (1 - np.cos(2 * np.pi * rotated))))
45 return (1. / (1. + float(error)),), tuple(genome[:2])
46
47 start = perf_counter()
48 for genome in warm:
49 quality, behavior = evaluate(genome)
50 archive.add(Individual(genome.tolist(), fitness=Fitness(quality, weights=(1.,)),
51 features=Features(behavior)))
52 options = dict(container=archive, budget=budget - warmup, dimension=dimension,
53 ind_domain=bounds, batch_size=1, optimisation_task="maximisation")
54 search = (DifferentialMAPElites(**options, initial_samples=0, seed=seed)
55 if method == "differential" else IsoLineMAPElites(**options, iso_sigma=.15))
56 with _coordinator_seed(seed):
57 search.optimise(evaluate)
58 yield dict(method=method, seed=seed, landscape=landscape, evaluations=search.nb_evaluations + warmup,
59 coverage=archive.filled_bins / len(centers), qd_score=archive.qd_score(),
60 best=archive.best.fitness.values[0],
61 differential_proposals=getattr(search, "differential_proposals", 0),
62 elapsed_s=perf_counter() - start)
63
64
65
66def mixed_trial(seed, budget):
67 """Design a synthetic beam with width, a rib count, and unordered material."""
68 variables = (RealVariable(0., 1.), IntegerVariable(1, 4), CategoricalVariable(("light", "dense", "hybrid")))
69 properties = {"light": (.55, .75, .16), "dense": (.92, .25, .25), "hybrid": (.75, .57, .21)}
70
71 for method in ("gower", "constrained_me"):
72 start = perf_counter()
73 archive = Grid(shape=(8, 4), features_domain=((0., 1.),) * 2,
74 fitness_domain=((0., 3.),), fitness_weights=(1.,))
75 options = dict(container=archive, budget=budget, variables=variables, batch_size=4,
76 optimisation_task="maximisation", constraint_names=("load", "mass"))
77 search = (MixedBayesianQD(**options, initial_samples=12, surrogate_budget=96, seed=seed)
78 if method == "gower" else ConstrainedMAPElites(**options))
79 feasible_attempts = 0
80
81 def evaluate(genome):
82 nonlocal feasible_attempts
83 width, ribs, material = search.decode(genome)
84 strength, target, density = properties[material]
85 load = .40 + .48 * width - strength - .04 * (ribs - 1)
86 mass = density * (ribs + width) - .89
87 feasible_attempts += load <= 0. and mass <= 0.
88 quality = 1. + math.exp(-10 * (width - target) ** 2) + .06 * ribs
89 return (quality,), (width, (ribs - 1) / 3.), {"load": load, "mass": mass}
90
91 # An empty feasible archive is a legitimate outcome with short budgets.
92 with _coordinator_seed(seed):
93 while search.nb_evaluations < budget:
94 batch = search.ask_batch(min(search.batch_size, budget - search.nb_evaluations))
95 search.tell_batch([evaluate(candidate) for candidate in batch])
96 yield dict(method=method, seed=seed, exact=search.nb_evaluations,
97 surrogate=getattr(search, "surrogate_evaluations", 0), feasible_attempts=feasible_attempts,
98 coverage=archive.filled_bins / 32, score=archive.qd_score(),
99 best=None if archive.best is None else archive.best.fitness.values[0],
100 elapsed_s=perf_counter() - start)
101
102
103
104def preference_trial(seed, budget):
105 """Use one shared warm start and a scripted user who favors larger second descriptors."""
106 warmup = min(20, budget - 1)
107 start_points = np.random.default_rng(seed).uniform(0., 1., size=(warmup, 2))
108
109 def measure(genome):
110 x, y = genome
111 return (1. - ((x - .5) ** 2 + (y - .5) ** 2),), (x, y)
112
113 def preference(genome):
114 return float(genome[1] + .2 * genome[0])
115
116 for mode in ("ridge", "tabular", "uniform"):
117 start = perf_counter()
118 grid = Grid(shape=(10, 10), features_domain=((0., 1.),) * 2,
119 fitness_domain=((0., 1.),), fitness_weights=(1.,))
120 for genome in start_points:
121 quality, descriptors = measure(genome)
122 grid.add(Individual(genome.tolist(), fitness=Fitness(quality, weights=(1.,)),
123 features=Features(descriptors)))
124 search = PreferenceLearningMAPElites(grid, budget, 2, mode=mode, seed=seed, batch_size=12,
125 iso_sigma=.09, line_sigma=.12)
126 preferred = total = 0
127 while search.nb_evaluations < budget - warmup:
128 occupied = {cell: entries[0] for cell, entries in grid.solutions.items() if entries}
129 selected = max(occupied, key=lambda cell: preference(occupied[cell]))
130 search.record_feedback([selected])
131 candidates = search.ask_batch(min(12, budget - warmup - search.nb_evaluations))
132 preferred += sum(preference(genome) >= .85 for genome in candidates)
133 total += len(candidates)
134 search.tell_batch([measure(genome) for genome in candidates])
135 yield dict(method=mode, seed=seed, evaluations=search.nb_evaluations + warmup,
136 feedback=search.feedback_rounds, favored_fraction=preferred / total, coverage=len(grid) / 100,
137 qd_score=grid.qd_score(), elapsed_s=perf_counter() - start)
138
139
140def main():
141 """Emit per-method and seed JSON records."""
142 parser = argparse.ArgumentParser(description=__doc__)
143 parser.add_argument("study", choices=("differential", "mixed", "preference"))
144 parser.add_argument("--seeds", type=int, nargs="+", default=[7])
145 parser.add_argument("--budget", type=int)
146 args = parser.parse_args()
147 trial, default = {"differential": (differential_trial, 480), "mixed": (mixed_trial, 96),
148 "preference": (preference_trial, 164)}[args.study]
149 budget = default if args.budget is None else args.budget
150 if budget < 2:
151 parser.error("--budget must be at least two")
152 for seed in args.seeds:
153 for record in trial(seed, budget):
154 print(json.dumps(record))
155
156
157if __name__ == "__main__":
158 main()