QDpy
Loading...
Searching...
No Matches
constrained_map_elites.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Search a synthetic design space with real, integer, and categorical variables."""
6
7from qdpy.algorithms import CategoricalVariable, ConstrainedMAPElites, IntegerVariable, RealVariable
8from qdpy.containers import Grid
9from qdpy.simple import run
10
11
12def make_search(budget, *, batch_size=1, infeasible_parent_probability=0.5):
13 """Build the same design space and reporting grid for each run."""
14 grid = Grid(shape=(8, 4), fitness_domain=((0.0, 2.0),),
15 features_domain=((0.0, 1.0), (0.5, 4.5)))
16 return ConstrainedMAPElites(
17 grid, budget, [RealVariable(0, 1), IntegerVariable(1, 4),
18 CategoricalVariable(("light", "reinforced"))],
19 constraint_names=("strength", "clearance"), batch_size=batch_size,
20 infeasible_parent_probability=infeasible_parent_probability,
21 )
22
23
24def evaluate_design(design):
25 """Return a cost, two descriptors, and residuals for this synthetic task."""
26 size, layers, material = design
27 reinforced = material == "reinforced"
28 cost = (size - 0.35) ** 2 + 0.08 * layers + 0.15 * reinforced
29 return (cost,), (size, layers), {
30 "strength": 0.6 - (size + 0.15 * layers + 0.2 * reinforced),
31 "clearance": size + 0.10 * layers - 1.1,
32 }
33
34
35if __name__ == "__main__":
36 search = make_search(24)
37
38 def evaluate(candidate):
39 """Translate the numeric genome before evaluating it."""
40 return evaluate_design(search.decode(candidate))
41
42 result = run(search, evaluate, seed=7)
43 print(f"Attempts: {result.evaluations}")
44 print(f"Feasible cells: {result.archive.filled_bins}/{len(result.archive.solutions)}")
45 print(f"Near-feasible cells: {len(search.infeasible_elites)}")
46 print(f"Best design: {search.decode(result.best)}, cost {result.best.fitness.values[0]:.4f}")