QDpy
Loading...
Searching...
No Matches
repair_transfer.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Compare constrained binary designs, fault adaptation, and component pairing."""
6
7import argparse
8import json
9from time import perf_counter
10
11import numpy as np
12from scipy.optimize import LinearConstraint
13
14from qdpy.algorithms import (APROL, MEliTA, RTESkill, BinaryMILPRepair, ConstrainedMAPElites,
15 IntegerVariable, RepairedMAPElites)
16from qdpy.containers import Grid
17from qdpy.simple import _coordinator_seed
18
19
20def _grid(shape, bound):
21 return Grid(shape=shape, features_domain=((0., 1.),) * len(shape),
22 fitness_domain=((0., bound),), fitness_weights=(1.,))
23
24
25
26def repair_trial(seed, budget):
27 """Use 12 slots, four installed modules, and exclusion of simultaneous pairs."""
28 dimension = 12
29 matrix = np.vstack([np.ones(dimension), np.repeat(np.eye(6), 2, axis=1)])
30 lower = [4., *([0.] * 6)]
31 upper = [4., *([1.] * 6)]
32 repair = BinaryMILPRepair(dimension, LinearConstraint(matrix, lower, upper))
33 values = np.random.default_rng(seed).uniform(.3, 1., dimension)
34 for method in ("repair", "constrained_me"):
35 start = perf_counter()
36 archive = _grid((5, 5), 4.)
37 feasible = 0
38
39 def evaluate(candidate):
40 nonlocal feasible
41 vector = np.asarray(candidate)
42 total = int(vector.sum())
43 conflicts = np.maximum(vector.reshape(6, 2).sum(axis=1) - 1, 0).sum()
44 constraint = abs(total - 4) + int(conflicts)
45 feasible += constraint == 0
46 quality = float(values @ vector) / 3.
47 return (quality,), (vector[:6].sum() / 6, vector[::2].sum() / 6), {"validity": constraint}
48
49 if method == "repair":
50 stats = RepairedMAPElites(archive, repair, seed=seed).run(evaluate, budget, repair_budget=16 * budget)
51 attempts, calls, duplicates = stats.evaluations, stats.repair_calls, stats.duplicate_repairs
52 else:
53 search = ConstrainedMAPElites(archive, budget, (IntegerVariable(0, 1),) * dimension,
54 constraint_names=("validity",), batch_size=4,
55 optimisation_task="maximisation")
56 with _coordinator_seed(seed):
57 while search.nb_evaluations < budget:
58 batch = search.ask_batch(min(4, budget - search.nb_evaluations))
59 search.tell_batch([evaluate(candidate) for candidate in batch])
60 attempts, calls, duplicates = search.nb_evaluations, 0, 0
61 yield dict(method=method, seed=seed, evaluations=attempts, feasible=int(feasible),
62 solver_calls=calls, duplicate_repairs=duplicates, cells=archive.filled_bins,
63 score=archive.qd_score(), elapsed_s=perf_counter() - start)
64
65
66
67def aprol_trial(seed, budget):
68 """Compare adaptive prior selection and a fixed nominal prior with the same live cap."""
69 actions = [(float(x), float(y)) for x in (-.23, 0., .23) for y in (-.23, 0., .23) if x or y]
70 nominal = tuple(RTESkill(action, action) for action in actions)
71 rotated = tuple(RTESkill((x, y), (-y, x)) for x, y in actions)
72 goal = np.asarray([1.1, -.43])
73 for method in ("aprol", "fixed"):
74 start = perf_counter()
75 options = {"nominal": nominal, "rotated": rotated} if method == "aprol" else {"nominal": nominal}
76 planner = APROL(options, exploration=.12, compatibility_std=.16, goal_std=.14)
77 rng = np.random.default_rng(seed)
78 position = np.zeros(2)
79 min_error = np.linalg.norm(position - goal)
80 for _ in range(budget):
81 subgoal = np.clip(goal - position, -.25, .25)
82 skill = planner.ask(subgoal)
83 x, y = skill.genome
84 effect = .96 * np.asarray([-y, x]) + rng.normal(0., .015, size=2)
85 planner.tell(effect)
86 position += effect
87 error = np.linalg.norm(position - goal)
88 min_error = min(min_error, error)
89 if error <= .11:
90 break
91 yield dict(method=method, seed=seed, live_trials=planner.trials, reached=bool(min_error <= .11),
92 error=float(min_error), rotated_selections=planner.trials_by_repertoire.get("rotated", 0),
93 elapsed_s=perf_counter() - start)
94
95
96
97def melita_trial(seed, budget):
98 """Pair a layout opening angle with a tracking controller's preferred angle."""
99 for mode in ("melita", "direct"):
100 start = perf_counter()
101 archive = _grid((8, 8), 1.)
102
103 def change(index):
104 return lambda parts, rng: float(np.clip(parts[index] + rng.normal(0., .20), 0., 1.))
105
106 def coherence(parts):
107 angle, controller = parts
108 return (1. - abs(angle - controller)) * (.85 + .15 * np.cos(6 * (angle + controller)) ** 2)
109
110 method = MEliTA(archive, initialize=lambda rng: tuple(rng.random(2)),
111 mutations=(change(0), change(1)), descriptors=(float, float),
112 coherence=coherence, transverse=mode == "melita", seed=seed)
113 stats = method.run(budget)
114 yield dict(method=mode, seed=seed, assessments=stats.assessments, edits=stats.proposals,
115 transverse=stats.transverse_assessments, cells=archive.filled_bins,
116 score=archive.qd_score(), elapsed_s=perf_counter() - start)
117
118
119def main():
120 """Write JSON records for the requested CPU comparison."""
121 parser = argparse.ArgumentParser(description=__doc__)
122 parser.add_argument("study", choices=("repair", "aprol", "melita"))
123 parser.add_argument("--budget", type=int)
124 parser.add_argument("--seeds", type=int, nargs="+", default=[7])
125 args = parser.parse_args()
126 experiment, default = {"repair": (repair_trial, 80), "aprol": (aprol_trial, 20),
127 "melita": (melita_trial, 240)}[args.study]
128 budget = default if args.budget is None else args.budget
129 if budget < 1:
130 parser.error("--budget must be positive")
131 for seed in args.seeds:
132 for row in experiment(seed, budget):
133 print(json.dumps(row))
134
135
136if __name__ == "__main__":
137 main()