Control evaluation with ask and tell ==================================== Use :meth:`qdpy.algorithms.QDAlgorithm.optimise` when QDpy should schedule evaluations and enforce the budget. Use :meth:`qdpy.algorithms.QDAlgorithm.ask` and :meth:`qdpy.algorithms.QDAlgorithm.tell` when your own scheduler, simulator, or interactive session controls when results arrive. Use :func:`qdpy.simple.run` to set the seed, open a backend, and run the same optimiser from Python. The function passes the evaluator through to ``optimise()``. For example, ``run(search, evaluate_batch, backend="multithreading", max_workers=2, pack_size=3)`` sends lists of up to three candidates to ``evaluate_batch``. Set the optimiser's batch size high enough to keep workers busy. Pass ``executor=`` if your application owns the executor. The runner restores Python and NumPy's global random streams after a seeded call. Give parallel evaluators their own per-candidate seeds when needed. Run seeded searches in separate processes if they need to execute concurrently with independent global random streams. Run an evaluation loop ---------------------- This example minimises the distance to ``0.25`` in a one-dimensional search space. The coordinate is also the descriptor, so the grid keeps a separate elite for each interval. Fitness and descriptors are both sequences, even when each contains a single value. .. code-block:: python import random from qdpy.algorithms import RandomUniform from qdpy.containers import Grid def make_search(): grid = Grid( shape=(4,), fitness_domain=((0.0, 1.0),), features_domain=((0.0, 1.0),), ) return RandomUniform( grid, budget=8, batch_size=4, dimension=1, ind_domain=(0.0, 1.0), optimisation_task="minimisation", ) def evaluate(candidate): x = candidate[0] return (abs(x - 0.25),), (x,) random.seed(42) search = make_search() for _ in range(search.budget): candidate = search.ask() fitness, features = evaluate(candidate) search.tell(candidate, fitness=fitness, features=features) print("Evaluations:", search.nb_evaluations) print("Occupied cells:", search.container.filled_bins) print("Best fitness:", search.best().fitness.values) ``ask()`` produces a candidate and increments the suggestion count. ``tell()`` applies the objective weights when you supply fitness, reports the result to the algorithm, and increments the evaluation count even if the archive declines the candidate. Its Boolean return indicates a local insertion or replacement. Use ``len(search.container)`` to count the stored entries. ``best()`` raises ``RuntimeError`` if the archive is empty. For maximisation, set ``optimisation_task="maximisation"`` and report the original objective values. A tuple of weights lets mixed-objective searches assign negative weights to minimised objectives and positive weights to maximised objectives. Keep fitness and descriptor values within the respective domains. Optimisers that share an archive must use identical objective weights. Let QDpy schedule the same evaluator ------------------------------------ The default evaluator contract is ``(fitness, features)``. You can add a third value, a dictionary of named scores. An evaluator that fills in an individual's fitness and features can return the updated individual. Set its fitness weights before assigning fitness values. Use ``()`` only if the evaluator updates the same object that the coordinator holds, as in sequential evaluation. Process and Ray workers need to return the result. During ``optimise()``, custom ``tell()`` overrides can declare ``fitness``, ``features``, and ``scores`` as keyword-only parameters. Positional overrides are also supported. QDpy chooses how to pass a measurement pair or triple at the start of each managed run. Here is an evaluator for a grid configured with ``fitness_score_names=("cost",)`` and ``features_score_names=("position",)``. It returns the evaluated candidate, so it also works in a process worker when defined at module scope. .. code-block:: python def evaluate_named(candidate): x = candidate[0] candidate.scores = {"cost": abs(x - 0.25), "position": x} return candidate For an archive that reads the candidate's fitness and descriptor fields, choose the return contract that matches where the evaluator runs. .. code-block:: python def evaluate_in_process(candidate): candidate.fitness.values, candidate.features.values = evaluate(candidate) return () def evaluate_in_worker(candidate): evaluate_in_process(candidate) return candidate Algorithms that learn from proposal coordinates, including BOP-Elites and the CMA-MAE family, require the evaluated genome to match the proposal. If an evaluator processes a list, return one result per candidate in the input order. Add the following to the script to run a fresh search with packed evaluations. .. code-block:: python def evaluate_batch(candidates): return [evaluate(candidate) for candidate in candidates] random.seed(42) managed = make_search() managed.optimise( evaluate_batch, send_several_suggestions_to_fn=True, max_nb_suggestions_per_call=3, ) print("Managed evaluations:", managed.nb_evaluations) The budget, batch size, and per-call limit all count candidates. An evaluator exception or invalid result format emits a warning and consumes its slots. A well-formed result outside the archive domain also consumes its slot. If every offer is declined and the archive starts empty, the managed run raises when it tries to return the best elite. With ``batch_mode=True``, QDpy completes each batch before asking for the next. With ``batch_mode=False``, it can ask for more as results arrive. If you use your own workers, keep the archive and ask/tell calls in the coordinator and send the workers only the evaluation work. To let QDpy manage the workers, open :class:`qdpy.base.ParallelismManager` in a ``with`` block and pass its ``executor`` to ``optimise()``. With a process pool, define the evaluator in an importable module and start the run inside an ``if __name__ == "__main__"`` guard. See `Python's executor documentation `_. Keep parallel results in input order ------------------------------------ When archive updates must follow the same order as a sequential run, give QDpy one packed call per batch and dispatch smaller packs inside that call. ``Executor.map`` yields results in input order even when workers finish out of order. This continuation uses the evaluator and search defined above. .. code-block:: python from concurrent.futures import ThreadPoolExecutor random.seed(42) ordered = make_search() with ThreadPoolExecutor(max_workers=2) as pool: def evaluate_in_order(candidates): packs = (candidates[i:i + 2] for i in range(0, len(candidates), 2)) return [result for pack in pool.map(evaluate_batch, packs) for result in pack] ordered.optimise( evaluate_in_order, send_several_suggestions_to_fn=True, max_nb_suggestions_per_call=ordered.batch_size, ) def archive_contents(search): return [(list(ind), ind.fitness.values, tuple(ind.features)) for ind in search.container] assert archive_contents(ordered) == archive_contents(managed) The example checks order with a deterministic evaluator. If your evaluator uses randomness, seed each candidate's evaluation independently of the worker. Keep the search's batch size fixed when comparing runs. An exception that escapes the evaluator fails the packed call for that batch. See :doc:`performance` for timings with threads and processes. Track search progress --------------------- ``add_callback()`` supports ``ask`` and ``tell`` events in both workflows. An ask callback receives the algorithm and candidate. A tell callback receives those plus the container update flag and a mapping of algorithm metadata. ``optimise()`` also drives ``started_optimisation``, ``iteration`` at complete batch-size boundaries, and ``finished_optimisation``. The start callback receives the algorithm. Iteration and finish callbacks also receive elapsed time in seconds. A manual loop controls its own budget and save schedule. An :class:`qdpy.algorithms.AlgorithmLogger` can collect reports from ``tell()`` and write the archive and evaluation rows when you call ``save()``. See :doc:`api_reference` for signatures and :doc:`tutorial_map_elites` for an example with final and per-iteration result files. For a one-elite grid, adding the first accepted candidate to a cell raises both ``filled_bins`` and the cell's ``activity_per_bin``. Replacing it raises activity and the optimiser's ``nb_updated``. The number of occupied cells stays the same. Archive histories can retain activity for replay. Portable grid exports record occupancy. Use :doc:`tutorial_corrected_archive` when you need a QD score from fresh evaluations of the retained solutions.