5"""Construct MAP-Elites and NSLC searches and run existing QDpy optimisers."""
7from collections.abc
import Mapping
8from contextlib
import contextmanager, nullcontext
9from dataclasses
import dataclass
10from math
import isfinite
11from operator
import index
12from os
import PathLike
13from pathlib
import Path
15from typing
import Any, Callable, Sequence
20from qdpy.base import DomainLike, ExecutorLike, ParallelismManager
21from qdpy.bundles import RunBundleOptions, _BundleWriter, _reserve_bundle, _WORK
27__all__ = [
"map_elites",
"nslc",
"run",
"RunResult",
"RunBundleOptions"]
31@dataclass(frozen=True, eq=False)
33 """References to a completed search and its evaluation count.
35 :ivar algorithm: The optimiser supplied to :func:`run`.
36 :ivar archive: The live container at the end of the run.
37 :ivar best: The live individual returned by the optimiser.
38 :ivar evaluations: Candidate slots consumed during this invocation.
39 :ivar manifest_path: The manifest path if an output directory was supplied.
42 algorithm: QDAlgorithmLike
46 manifest_path: Path |
None
49def _positive_int(value: int, name: str) -> int:
51 number = 0
if isinstance(value, (bool, np.bool_))
else index(value)
55 raise ValueError(f
"{name} must be a positive integer.")
64 shape: int | Sequence[int],
65 fitness_domain: Sequence[DomainLike],
66 features_domain: Sequence[DomainLike],
67 ind_domain: DomainLike = (0, 1),
69 optimisation_task: str | Sequence[float] =
"minimisation",
70) -> RandomSearchMutPolyBounded:
71 """Make a MAP-Elites search for real-valued genomes.
73 :param dimension: Number of coordinates in each genome.
74 :param budget: Number of candidate evaluations per run.
75 :param shape: Number of bins for each descriptor, or an integer for one descriptor.
76 :param fitness_domain: One closed interval per objective.
77 :param features_domain: One closed interval per grid axis.
78 :param ind_domain: Bounds shared by all genome coordinates.
79 :param batch_size: Candidate count per batch. The default gives each proposal
80 feedback from the previous evaluation.
81 :param optimisation_task: Objective direction or a sequence of objective weights.
82 :returns: An optimiser ready for :func:`run` or the native ask/tell API.
84 dimension = _positive_int(dimension,
"dimension")
85 budget = _positive_int(budget,
"budget")
86 batch_size = _positive_int(batch_size,
"batch_size")
87 grid_shape = tuple(_positive_int(size,
"grid extent")
for size
in tuplify(shape))
88 if not grid_shape
or len(grid_shape) != len(features_domain):
89 raise ValueError(
"shape must give one grid extent per descriptor interval.")
91 archive =
Grid(shape=grid_shape, fitness_domain=fitness_domain, features_domain=features_domain)
93 archive, budget=budget, dimension=dimension, ind_domain=ind_domain,
94 batch_size=batch_size, optimisation_task=optimisation_task,
103 fitness_domain: Sequence[DomainLike],
104 features_domain: Sequence[DomainLike],
105 threshold_novelty: float,
107 ind_domain: DomainLike = (0, 1),
109 optimisation_task: str | Sequence[float] =
"minimisation",
110) -> RandomSearchMutPolyBounded:
111 """Make an NSLC search with a fixed novelty threshold.
113 The child archive uses Euclidean distances to its parent history. The
114 optimiser keeps that parent when saved with the native pickle tools.
116 :param dimension: Number of coordinates in each genome.
117 :param budget: Number of candidate evaluations per run.
118 :param fitness_domain: One closed interval per objective.
119 :param features_domain: One closed interval per descriptor.
120 :param threshold_novelty: Finite, nonnegative threshold in descriptor units.
121 :param k: Number of nearest neighbours to consider.
122 :param ind_domain: Bounds shared by all genome coordinates.
123 :param batch_size: Candidate count per batch.
124 :param optimisation_task: Objective direction or a sequence of objective weights.
125 :returns: An optimiser with a child novelty archive and a separate parent.
127 dimension = _positive_int(dimension,
"dimension")
128 budget = _positive_int(budget,
"budget")
129 batch_size = _positive_int(batch_size,
"batch_size")
130 k = _positive_int(k,
"k")
131 if not isfinite(threshold_novelty)
or threshold_novelty < 0:
132 raise ValueError(
"threshold_novelty must be finite and nonnegative.")
133 if len(fitness_domain) == 0
or len(features_domain) == 0:
134 raise ValueError(
"fitness_domain and features_domain must each specify at least one interval.")
136 history =
Container(fitness_domain=fitness_domain, features_domain=features_domain)
138 parents=[history], k=k, threshold_novelty=threshold_novelty,
139 fitness_domain=fitness_domain, features_domain=features_domain,
140 disable_parents_pickling=
False,
143 archive, budget=budget, dimension=dimension, ind_domain=ind_domain,
144 batch_size=batch_size, optimisation_task=optimisation_task,
149def _coordinator_seed(seed: int |
None):
155 python_state = random.getstate()
156 numpy_state = np.random.get_state()
162 random.setstate(python_state)
163 np.random.set_state(numpy_state)
167def _reserve_manifest(output_dir: str | PathLike[str] |
None):
168 """Give one run exclusive use of its output directory until it finishes."""
169 if output_dir
is None:
173 directory = Path(output_dir)
174 directory.mkdir(parents=
True, exist_ok=
True)
175 manifest = directory /
"run.json"
176 reservation = directory /
".run.json.lock"
177 with reservation.open(
"x"):
180 if manifest.exists()
or manifest.is_symlink():
181 raise FileExistsError(f
"Run manifest already exists at {manifest}.")
182 if (directory / _WORK).exists():
183 raise FileExistsError(f
"A run bundle already owns {directory}.")
191 algorithm: QDAlgorithmLike,
194 seed: int |
None =
None,
195 backend: str |
None =
None,
196 executor: ExecutorLike |
None =
None,
197 max_workers: int |
None =
None,
198 ray_address: str |
None =
None,
199 batch_mode: bool =
True,
200 pack_size: int |
None =
None,
201 output_dir: str | PathLike[str] |
None =
None,
202 configuration: Mapping[str, Any] |
None =
None,
203 bundle: RunBundleOptions |
None =
None,
205 """Drive an existing optimiser with its native evaluation contract.
207 The optimiser keeps its archive, counters and callbacks between calls.
208 Evaluator results and failures follow the algorithm's ``optimise()``
209 behavior. Parallel feedback follows the executor's completion order.
211 :param algorithm: An optimiser with the native ``optimise()`` interface.
212 :param evaluate: Candidate evaluator, or a list-taking evaluator with ``pack_size``.
213 :param seed: Optional seed for the calling process's Python and NumPy global
214 random streams. Their states are restored after the run.
215 :param backend: Backend accepted by the parallelism manager. Defaults to sequential.
216 :param executor: A caller-owned executor. Use it on its own or select a managed backend.
217 :param max_workers: Worker limit passed to the parallelism manager.
218 :param ray_address: Address passed to the optional Ray backend.
219 :param batch_mode: Complete each batch before proposing the next one.
220 :param pack_size: Maximum number of candidates passed to a packed evaluator.
221 :param output_dir: Optional directory for a new ``run.json`` and supported grid export.
222 :param configuration: Run settings to record in the manifest. The actual
223 seed passed to the runner is recorded under ``seed``.
224 :param bundle: Optional portable history, lineage, and checkpoint settings.
225 Supply ``output_dir``. Checkpointed bundles use the native batch
226 driver with a sequential scalar evaluator or one packed call per batch.
227 :returns: References to the live run objects and the evaluation count for this call.
228 :raises FileExistsError: If the directory already has a manifest or an active run.
230 if executor
is not None and (backend
is not None or max_workers
is not None or ray_address
is not None):
231 raise ValueError(
"Specify executor or managed backend options, one at a time.")
232 if pack_size
is not None:
233 pack_size = _positive_int(pack_size,
"pack_size")
234 if configuration
is not None and not isinstance(configuration, Mapping):
235 raise TypeError(
"configuration must map setting names to values.")
236 if bundle
is not None:
237 if not isinstance(bundle, RunBundleOptions)
or output_dir
is None:
238 raise ValueError(
"Pass RunBundleOptions with an output_dir.")
241 if not 0 <= seed < 2**32:
242 raise ValueError(
"Use a seed between 0 and 2**32 - 1.")
243 if bundle.history_every
is not None:
244 _positive_int(bundle.history_every,
"history_every")
245 if bundle.checkpoint_every
is None:
246 if bundle.resume
or bundle.stop_after
is not None or bundle.stop_requested
is not None:
247 raise ValueError(
"Resume and stop options require checkpoint_every.")
249 _positive_int(bundle.checkpoint_every,
"checkpoint_every")
250 if bundle.resume
and not bundle.trusted:
251 raise ValueError(
"Resume requires trusted=True for a checkpoint you trust.")
252 if (executor
is not None or backend
not in (
None,
"sequential",
"none")
or not batch_mode
253 or pack_size
not in (
None, algorithm.batch_size)):
254 raise ValueError(
"Checkpointed bundles use sequential batches and at most one packed call per batch.")
256 ParallelismManager(
"sequential" if backend
is None else backend, max_workers, ray_address=ray_address)
257 if executor
is None else nullcontext()
260 reservation = (_reserve_manifest(output_dir)
if bundle
is None
261 else _reserve_bundle(output_dir, resume=bundle.resume))
262 coordinator = _coordinator_seed(seed)
if bundle
is None else nullcontext(seed)
263 with coordinator
as seed, reservation
as manifest:
265 initial_evaluations = algorithm.nb_evaluations
266 with manager
as managed:
267 execution =
None if manifest
is None else {
268 "backend":
"external" if managed
is None else managed.parallelism_type,
269 "start_method":
None if managed
is None else managed.start_method,
270 "max_workers":
None if managed
is None else managed.max_workers,
271 "batch_mode": batch_mode,
272 "batch_size": algorithm.batch_size,
273 "packed": pack_size
is not None,
274 "max_suggestions_per_call": pack_size,
276 if bundle
is not None:
277 writer =
_BundleWriter(manifest, bundle, algorithm, evaluate, seed, configuration, execution)
278 if bundle
is not None and bundle.checkpoint_every
is not None:
281 result = run_checkpointed(algorithm, evaluate, checkpoint_path=writer.checkpoint,
282 seed=writer.seed, checkpoint_every=bundle.checkpoint_every,
283 stop_after=bundle.stop_after, stop_requested=bundle.stop_requested,
284 resume=bundle.resume, trusted=bundle.trusted, packed=pack_size
is not None,
286 best, attempted, initial_evaluations = result.best, result.evaluations, 0
288 observation = nullcontext()
if writer
is None else writer.record(algorithm)
289 random_scope = nullcontext()
if writer
is None else _coordinator_seed(writer.seed)
290 with random_scope, observation:
291 best = algorithm.optimise(
292 evaluate, batch_mode=batch_mode,
293 executor=executor
if managed
is None else managed.executor,
294 send_several_suggestions_to_fn=pack_size
is not None,
295 max_nb_suggestions_per_call=1
if pack_size
is None else pack_size,
297 attempted = algorithm.nb_evaluations - initial_evaluations
298 if manifest
is not None:
299 committed = algorithm.nb_evaluations - initial_evaluations
300 execution[
"batch_size"] = algorithm.batch_size
301 resumed_from = committed - attempted
if bundle
is not None and bundle.resume
else None
303 manifest, algorithm, evaluate=evaluate, execution=execution, initial_evaluations=initial_evaluations,
304 configuration=writer.configuration
if writer
is not None else {**(configuration
or {}),
"seed": seed},
305 bundle=
None if writer
is None else writer.describe(best, committed, resumed_from=resumed_from),
308 algorithm=algorithm, archive=algorithm.container, best=best,
309 evaluations=attempted,
310 manifest_path=manifest,
Carry the outcome of one optimiser invocation.