5"""Run small seeded CPU comparisons. CP-SAT requires the optional cpsat extra."""
10from itertools
import product
11from pathlib
import Path
18 DifferentialMAPElites,
22 SafeBayesianIllumination,
27DURATIONS = (2, 3, 2, 1)
30SAFE_SEED = SAFE_SEED_INDEX / 160
31NARROW_PEAKS = np.array([(-.72, -.7, .65, -.55), (-.68, .73, -.62, .56),
32 (.69, -.71, -.58, .67), (.73, .68, .58, -.62)])
33HIMMELBLAU_PEAKS = np.array([(3., 2.), (-2.805118, 3.131312),
34 (-3.779310, -3.283186), (3.584428, -1.848126)]) / 5.
37def quality_grid(shape):
38 """Create a one-elite maximizing archive with unit domains."""
39 return Grid(shape=shape, features_domain=((0., 1.),) * len(shape),
40 fitness_domain=((0., 1.),), fitness_weights=(1.,))
43def scheduling_model():
44 """Set up two jobs that visit two machines in opposite order."""
45 from ortools.sat.python
import cp_model
47 model = cp_model.CpModel()
48 starts = [model.new_int_var(0, HORIZON - d, f
"start_{i}")
for i, d
in enumerate(DURATIONS)]
49 ends = tuple(start + duration
for start, duration
in zip(starts, DURATIONS))
50 intervals = [model.new_fixed_size_interval_var(start, duration, f
"operation_{i}")
51 for i, (start, duration)
in enumerate(zip(starts, DURATIONS))]
52 model.add(starts[1] >= ends[0])
53 model.add(starts[3] >= ends[2])
54 for first, second
in ((0, 3), (1, 2)):
55 model.add_no_overlap((intervals[first], intervals[second]))
56 model.add_cumulative(intervals, DEMANDS, 2)
57 makespan = model.new_int_var(0, HORIZON,
"makespan")
58 model.add_max_equality(makespan, (ends[1], ends[3]))
59 return model, ends[1] + ends[3], (makespan, ends[1] - ends[3])
62def exhaustive_schedule(archive):
63 """Find exact niche optima by enumerating integer start times."""
65 for starts
in product(*(range(HORIZON - d + 1)
for d
in DURATIONS)):
66 finishes = tuple(start + duration
for start, duration
in zip(starts, DURATIONS))
67 if starts[1] < finishes[0]
or starts[3] < finishes[2]:
69 if any(max(starts[a], starts[b]) < min(finishes[a], finishes[b])
for a, b
in ((0, 3), (1, 2))):
71 if any(sum(demand
for start, end, demand
in zip(starts, finishes, DEMANDS)
if start <= tick < end) > 2
72 for tick
in range(HORIZON)):
74 a, b = finishes[1], finishes[3]
75 cell = archive.index_grid((max(a, b), a - b))
76 best[cell] = min(best.get(cell, 2 * HORIZON), a + b)
81 """Solve every cell and certify the reports against the enumerated reference."""
82 model, objective, descriptors = scheduling_model()
83 archive = Grid(shape=(5, 7), features_domain=((0, HORIZON), (-HORIZON, HORIZON)),
84 fitness_domain=((0, 2 * HORIZON),), fitness_weights=(-1.,))
85 reports = CPSATArchiveSearch(archive, model, objective=objective, descriptors=descriptors).run()
86 exact = exhaustive_schedule(archive)
87 solved = {row.cell: row.fitness
for row
in reports
if row.status ==
"optimal"}
88 if solved != exact
or any(row.status !=
"infeasible" for row
in reports
if row.cell
not in exact):
89 raise AssertionError(
"The CP-SAT cell reports differ from exhaustive enumeration.")
90 return {
"task":
"cpsat",
"method":
"cpsat",
"cells": len(reports),
"optimal": len(solved),
91 "infeasible": len(reports) - len(solved),
"solver_calls": sum(row.solver_status
is not None
93 "enumerated_starts": int(np.prod([HORIZON - d + 1
for d
in DURATIONS]))}
96def simulate_design(genome):
97 """Score a one-dimensional simulator with two separate safe regions."""
99 margin = .15 - min(abs(x - .29), abs(x - .78))
100 quality = max(.82 * np.exp(-((x - .37) / .095)**2), np.exp(-((x - .82) / .11)**2))
101 return float(quality), (margin,)
105 """Give the feasibility-weighted baseline the same initial safe observation."""
107 def _sobol_point(self):
109 return np.array([SAFE_SEED])
110 return super()._sobol_point()
113def safe_trial(seed, budget):
114 """Compare safety gates and feasibility-weighted acquisition."""
116 points = np.arange(161, dtype=float)[:,
None] / 160
117 for method, bound
in ((
"lipschitz", 1.), (
"gp-gate",
None)):
118 archive = quality_grid((20,))
120 lipschitz=bound, expansion_budget=10, confidence=3.,
122 search.run(simulate_design, budget=budget)
123 rows.append({
"task":
"safe",
"method": method,
"seed": seed,
"budget": budget,
124 "evaluations": len(search.trials),
"expansion": sum(row.phase ==
"expansion"
125 for row
in search.trials),
126 "unsafe": sum(any(value < 0.
for value
in row.margins)
for row
in search.trials),
127 "halted": search.halted,
"cells": len(archive),
"qd": archive.qd_score()})
128 archive = quality_grid((20,))
130 candidate_pool=64, restarts=2, model_feasibility=
True,
131 optimisation_task=
"maximisation", seed=seed)
134 def benchmark(genome):
136 fitness, margins = simulate_design(genome)
137 if min(margins) < 0.:
139 return None,
None, {
"bop_valid":
False}
140 return (fitness,), tuple(genome)
142 baseline.optimise(benchmark)
143 rows.append({
"task":
"safe",
"method":
"feasibility-bop",
"seed": seed,
"budget": budget,
144 "evaluations": baseline.nb_evaluations,
"unsafe": unsafe,
145 "halted":
False,
"cells": len(archive),
"qd": archive.qd_score()})
149def diffusion_trial(seed, budget, workload):
150 """Compare four emitters with the same bounded domains and reporting grid."""
151 peaks = HIMMELBLAU_PEAKS
if workload ==
"himmelblau" else NARROW_PEAKS
152 batch = min(24, budget)
153 steps = max(2, (budget + batch - 1) // batch)
155 for name
in (
"diffusion-map-elites",
"diffusion-evolution",
"iso-line",
"differential"):
156 archive = quality_grid((12, 12))
157 if name.startswith(
"diffusion"):
158 kind = DiffusionMAPElites
if name.endswith(
"map-elites")
else DiffusionEvolution
159 run = kind(archive, budget, peaks.shape[1], batch, diffusion_steps=steps, seed=seed)
160 elif name ==
"differential":
162 optimisation_task=
"maximisation", seed=seed)
166 run =
IsoLineMAPElites(archive, budget, peaks.shape[1], (-1., 1.), batch_size=batch,
167 optimisation_task=
"maximisation", iso_sigma=.12, line_sigma=.2)
170 def evaluate(genome, hits=hits):
171 point = np.asarray(genome)
172 delta = np.linalg.norm(peaks - point, axis=1)
173 closest = int(np.argmin(delta))
174 if delta[closest] <= (.1
if workload ==
"himmelblau" else .2):
176 if workload ==
"himmelblau":
178 quality = 1. / (1. + ((x * x + y - 11.)**2 + (x + y * y - 7.)**2) / 35.)
180 quality = max(np.exp(-(delta[closest] / .30)**2), .78 * np.exp(-np.dot(point, point) / .85))
181 return (float(quality),), tuple(.5 + .5 * point[:2])
183 run.optimise(evaluate)
184 rows.append({
"task": workload,
"method": name,
"seed": seed,
"budget": budget,
185 "evaluations": run.nb_evaluations,
"cells": len(archive),
"qd": archive.qd_score(),
186 "peaks": len(hits),
"best": archive.best_fitness.values[0]})
191 """Run selected methods and optionally write the per-seed records as JSONL."""
192 parser = argparse.ArgumentParser(description=__doc__)
193 parser.add_argument(
"task", choices=(
"cpsat",
"safe",
"diffusion",
"all"))
194 parser.add_argument(
"--include-cpsat", action=
"store_true", help=
"Run the solver in the all command.")
195 parser.add_argument(
"--budget", type=int, help=
"Override the search evaluation budgets.")
196 parser.add_argument(
"--seeds", type=int, nargs=
"+", default=[11, 12, 13, 14, 15])
197 parser.add_argument(
"--output", type=Path)
198 args = parser.parse_args()
199 if args.budget
is not None and args.budget < 1:
200 parser.error(
"budget must be positive.")
202 if args.task ==
"cpsat" or args.task ==
"all" and args.include_cpsat:
203 rows.append(solver_trial())
204 if args.task
in (
"safe",
"all"):
205 for seed
in args.seeds:
206 rows.extend(safe_trial(seed, args.budget
or 32))
207 if args.task
in (
"diffusion",
"all"):
208 for seed
in args.seeds:
209 for workload
in (
"himmelblau",
"deceptive-peaks"):
210 rows.extend(diffusion_trial(seed, args.budget
or 720, workload))
211 report =
"".join(json.dumps(row, sort_keys=
True) +
"\n" for row
in rows)
212 if args.output
is None:
213 print(report, end=
"")
215 args.output.write_text(report, encoding=
"utf-8")
218if __name__ ==
"__main__":
Select one genuine evaluation with expected joint improvement of elites.
Sample four distinct elites, recombine them, and perform local competition.
Fill a one-elite grid using Iso+LineDD variation.
Illuminate a pool of measurable designs while separating safety and quality.