Source code for qdpy.simple

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Python shortcuts for constructing and running common QD searches.

"""Construct MAP-Elites and NSLC searches and run existing QDpy optimisers."""

from collections.abc import Mapping
from contextlib import contextmanager, nullcontext
from dataclasses import dataclass
from math import isfinite
from operator import index
from os import PathLike
from pathlib import Path
import random
from typing import Any, Callable, Sequence

import numpy as np

from qdpy.algorithms import QDAlgorithmLike, RandomSearchMutPolyBounded
from qdpy.base import DomainLike, ExecutorLike, ParallelismManager
from qdpy.bundles import RunBundleOptions, _BundleWriter, _reserve_bundle, _WORK
from qdpy.containers import Container, Grid, NoveltyArchive
from qdpy.phenotype import IndividualLike
from qdpy.results import write_run_manifest
from qdpy.utils import tuplify

__all__ = ["map_elites", "nslc", "run", "RunResult", "RunBundleOptions"]


## @brief Carry the outcome of one optimiser invocation.
[docs] @dataclass(frozen=True, eq=False) class RunResult: """References to a completed search and its evaluation count. :ivar algorithm: The optimiser supplied to :func:`run`. :ivar archive: The live container at the end of the run. :ivar best: The live individual returned by the optimiser. :ivar evaluations: Candidate slots consumed during this invocation. :ivar manifest_path: The manifest path if an output directory was supplied. """ algorithm: QDAlgorithmLike archive: Container best: IndividualLike evaluations: int manifest_path: Path | None
def _positive_int(value: int, name: str) -> int: try: number = 0 if isinstance(value, (bool, np.bool_)) else index(value) except TypeError: number = 0 if number < 1: raise ValueError(f"{name} must be a positive integer.") return number ## @brief Construct a polynomial-mutation search with one elite per grid cell.
[docs] def map_elites( *, dimension: int, budget: int, shape: int | Sequence[int], fitness_domain: Sequence[DomainLike], features_domain: Sequence[DomainLike], ind_domain: DomainLike = (0, 1), batch_size: int = 1, optimisation_task: str | Sequence[float] = "minimisation", ) -> RandomSearchMutPolyBounded: """Make a MAP-Elites search for real-valued genomes. :param dimension: Number of coordinates in each genome. :param budget: Number of candidate evaluations per run. :param shape: Number of bins for each descriptor, or an integer for one descriptor. :param fitness_domain: One closed interval per objective. :param features_domain: One closed interval per grid axis. :param ind_domain: Bounds shared by all genome coordinates. :param batch_size: Candidate count per batch. The default gives each proposal feedback from the previous evaluation. :param optimisation_task: Objective direction or a sequence of objective weights. :returns: An optimiser ready for :func:`run` or the native ask/tell API. """ dimension = _positive_int(dimension, "dimension") budget = _positive_int(budget, "budget") batch_size = _positive_int(batch_size, "batch_size") grid_shape = tuple(_positive_int(size, "grid extent") for size in tuplify(shape)) if not grid_shape or len(grid_shape) != len(features_domain): raise ValueError("shape must give one grid extent per descriptor interval.") archive = Grid(shape=grid_shape, fitness_domain=fitness_domain, features_domain=features_domain) return RandomSearchMutPolyBounded( archive, budget=budget, dimension=dimension, ind_domain=ind_domain, batch_size=batch_size, optimisation_task=optimisation_task, )
## @brief Construct a novelty and local competition search with parent history.
[docs] def nslc( *, dimension: int, budget: int, fitness_domain: Sequence[DomainLike], features_domain: Sequence[DomainLike], threshold_novelty: float, k: int = 15, ind_domain: DomainLike = (0, 1), batch_size: int = 1, optimisation_task: str | Sequence[float] = "minimisation", ) -> RandomSearchMutPolyBounded: """Make an NSLC search with a fixed novelty threshold. The child archive uses Euclidean distances to its parent history. The optimiser keeps that parent when saved with the native pickle tools. :param dimension: Number of coordinates in each genome. :param budget: Number of candidate evaluations per run. :param fitness_domain: One closed interval per objective. :param features_domain: One closed interval per descriptor. :param threshold_novelty: Finite, nonnegative threshold in descriptor units. :param k: Number of nearest neighbours to consider. :param ind_domain: Bounds shared by all genome coordinates. :param batch_size: Candidate count per batch. :param optimisation_task: Objective direction or a sequence of objective weights. :returns: An optimiser with a child novelty archive and a separate parent. """ dimension = _positive_int(dimension, "dimension") budget = _positive_int(budget, "budget") batch_size = _positive_int(batch_size, "batch_size") k = _positive_int(k, "k") if not isfinite(threshold_novelty) or threshold_novelty < 0: raise ValueError("threshold_novelty must be finite and nonnegative.") if len(fitness_domain) == 0 or len(features_domain) == 0: raise ValueError("fitness_domain and features_domain must each specify at least one interval.") history = Container(fitness_domain=fitness_domain, features_domain=features_domain) archive = NoveltyArchive( parents=[history], k=k, threshold_novelty=threshold_novelty, fitness_domain=fitness_domain, features_domain=features_domain, disable_parents_pickling=False, ) return RandomSearchMutPolyBounded( archive, budget=budget, dimension=dimension, ind_domain=ind_domain, batch_size=batch_size, optimisation_task=optimisation_task, )
@contextmanager def _coordinator_seed(seed: int | None): if seed is None: yield None return seed = index(seed) python_state = random.getstate() numpy_state = np.random.get_state() try: random.seed(seed) np.random.seed(seed) yield seed finally: random.setstate(python_state) np.random.set_state(numpy_state) @contextmanager def _reserve_manifest(output_dir: str | PathLike[str] | None): """Give one run exclusive use of its output directory until it finishes.""" if output_dir is None: yield None return directory = Path(output_dir) directory.mkdir(parents=True, exist_ok=True) manifest = directory / "run.json" reservation = directory / ".run.json.lock" with reservation.open("x"): pass try: if manifest.exists() or manifest.is_symlink(): raise FileExistsError(f"Run manifest already exists at {manifest}.") if (directory / _WORK).exists(): raise FileExistsError(f"A run bundle already owns {directory}.") yield manifest finally: reservation.unlink() ## @brief Run a native optimiser and optionally save its manifest.
[docs] def run( algorithm: QDAlgorithmLike, evaluate: Callable, *, seed: int | None = None, backend: str | None = None, executor: ExecutorLike | None = None, max_workers: int | None = None, ray_address: str | None = None, batch_mode: bool = True, pack_size: int | None = None, output_dir: str | PathLike[str] | None = None, configuration: Mapping[str, Any] | None = None, bundle: RunBundleOptions | None = None, ) -> RunResult: """Drive an existing optimiser with its native evaluation contract. The optimiser keeps its archive, counters and callbacks between calls. Evaluator results and failures follow the algorithm's ``optimise()`` behavior. Parallel feedback follows the executor's completion order. :param algorithm: An optimiser with the native ``optimise()`` interface. :param evaluate: Candidate evaluator, or a list-taking evaluator with ``pack_size``. :param seed: Optional seed for the calling process's Python and NumPy global random streams. Their states are restored after the run. :param backend: Backend accepted by the parallelism manager. Defaults to sequential. :param executor: A caller-owned executor. Use it on its own or select a managed backend. :param max_workers: Worker limit passed to the parallelism manager. :param ray_address: Address passed to the optional Ray backend. :param batch_mode: Complete each batch before proposing the next one. :param pack_size: Maximum number of candidates passed to a packed evaluator. :param output_dir: Optional directory for a new ``run.json`` and supported grid export. :param configuration: Run settings to record in the manifest. The actual seed passed to the runner is recorded under ``seed``. :param bundle: Optional portable history, lineage, and checkpoint settings. Supply ``output_dir``. Checkpointed bundles use the native batch driver with a sequential scalar evaluator or one packed call per batch. :returns: References to the live run objects and the evaluation count for this call. :raises FileExistsError: If the directory already has a manifest or an active run. """ if executor is not None and (backend is not None or max_workers is not None or ray_address is not None): raise ValueError("Specify executor or managed backend options, one at a time.") if pack_size is not None: pack_size = _positive_int(pack_size, "pack_size") if configuration is not None and not isinstance(configuration, Mapping): raise TypeError("configuration must map setting names to values.") if bundle is not None: if not isinstance(bundle, RunBundleOptions) or output_dir is None: raise ValueError("Pass RunBundleOptions with an output_dir.") if seed is not None: seed = index(seed) if not 0 <= seed < 2**32: raise ValueError("Use a seed between 0 and 2**32 - 1.") if bundle.history_every is not None: _positive_int(bundle.history_every, "history_every") if bundle.checkpoint_every is None: if bundle.resume or bundle.stop_after is not None or bundle.stop_requested is not None: raise ValueError("Resume and stop options require checkpoint_every.") else: _positive_int(bundle.checkpoint_every, "checkpoint_every") if bundle.resume and not bundle.trusted: raise ValueError("Resume requires trusted=True for a checkpoint you trust.") if (executor is not None or backend not in (None, "sequential", "none") or not batch_mode or pack_size not in (None, algorithm.batch_size)): raise ValueError("Checkpointed bundles use sequential batches and at most one packed call per batch.") manager = ( ParallelismManager("sequential" if backend is None else backend, max_workers, ray_address=ray_address) if executor is None else nullcontext() ) reservation = (_reserve_manifest(output_dir) if bundle is None else _reserve_bundle(output_dir, resume=bundle.resume)) coordinator = _coordinator_seed(seed) if bundle is None else nullcontext(seed) with coordinator as seed, reservation as manifest: writer = None initial_evaluations = algorithm.nb_evaluations with manager as managed: execution = None if manifest is None else { "backend": "external" if managed is None else managed.parallelism_type, "start_method": None if managed is None else managed.start_method, "max_workers": None if managed is None else managed.max_workers, "batch_mode": batch_mode, "batch_size": algorithm.batch_size, "packed": pack_size is not None, "max_suggestions_per_call": pack_size, } if bundle is not None: writer = _BundleWriter(manifest, bundle, algorithm, evaluate, seed, configuration, execution) if bundle is not None and bundle.checkpoint_every is not None: from qdpy.checkpoints import run_checkpointed result = run_checkpointed(algorithm, evaluate, checkpoint_path=writer.checkpoint, seed=writer.seed, checkpoint_every=bundle.checkpoint_every, stop_after=bundle.stop_after, stop_requested=bundle.stop_requested, resume=bundle.resume, trusted=bundle.trusted, packed=pack_size is not None, _observer=writer) best, attempted, initial_evaluations = result.best, result.evaluations, 0 else: observation = nullcontext() if writer is None else writer.record(algorithm) random_scope = nullcontext() if writer is None else _coordinator_seed(writer.seed) with random_scope, observation: best = algorithm.optimise( evaluate, batch_mode=batch_mode, executor=executor if managed is None else managed.executor, send_several_suggestions_to_fn=pack_size is not None, max_nb_suggestions_per_call=1 if pack_size is None else pack_size, ) attempted = algorithm.nb_evaluations - initial_evaluations if manifest is not None: committed = algorithm.nb_evaluations - initial_evaluations execution["batch_size"] = algorithm.batch_size resumed_from = committed - attempted if bundle is not None and bundle.resume else None write_run_manifest( manifest, algorithm, evaluate=evaluate, execution=execution, initial_evaluations=initial_evaluations, configuration=writer.configuration if writer is not None else {**(configuration or {}), "seed": seed}, bundle=None if writer is None else writer.describe(best, committed, resumed_from=resumed_from), ) return RunResult( algorithm=algorithm, archive=algorithm.container, best=best, evaluations=attempted, manifest_path=manifest, )