Run your first searches from PyPI

Install QDpy in a Python 3.11 or newer environment. All four scripts below use the base package. You can save each code block as a Python file in an empty working directory and run it without a repository checkout.

python -m pip install qdpy

In an existing uv project, run uv add qdpy and replace python with uv run python in the example commands.

MAP-Elites

Search for a small value of x across cells of the descriptor y. Each occupied cell keeps one design. The search spends 64 candidate attempts and saves first-map-elites/run.json and a numeric archive. The script reads the manifest, verifies the archive checksum, and prints coverage and the best raw cost from the saved measurements.

Save the code as map_elites.py and run python map_elites.py.

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Run MAP-Elites and reopen its numeric archive.

"""Find a low-cost solution in each descriptor cell."""

from qdpy.results import load_grid, read_run_manifest
from qdpy.simple import map_elites, run


def evaluate(candidate):
    """Minimise the first coordinate squared and bin on the second."""
    x, descriptor = candidate
    return (x**2,), (descriptor,)


def main():
    """Save the search and report the best cost and coverage from disk."""
    search = map_elites(
        dimension=2, budget=64, batch_size=8, shape=8,
        fitness_domain=((0.0, 1.0),), features_domain=((0.0, 1.0),),
    )
    result = run(search, evaluate, seed=42, output_dir="first-map-elites")
    manifest = read_run_manifest(result.manifest_path)
    snapshot = manifest["archive"]
    restored = load_grid(
        result.manifest_path.with_name(snapshot["file"]),
        expected_sha256=snapshot["sha256"],
    )
    print(f"Candidate attempts: {result.evaluations}")
    print(f"Occupied cells: {restored.filled_bins}/{restored.shape[0]}")
    print(f"Best raw cost: {restored.best.fitness.values[0]:.6f}")


if __name__ == "__main__":
    main()

MOME

Keep trade-offs between x**2 and (1 - x)**2 in each descriptor cell. The search spends 64 candidate attempts and writes its manifest and archive under first-mome. An occupied cell can hold up to four nondominated designs. The sum of cell hypervolumes measures the trade-offs available across cells. Global hypervolume treats designs from all cells as one front. Use the same reference point and objective directions when comparing runs.

Save the code as mome.py and run python mome.py.

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Save and reopen the local Pareto fronts found by MOME.

"""Find trade-offs between two costs in each descriptor cell."""

from qdpy.algorithms import MOME
from qdpy.containers import ParetoGrid
from qdpy.results import load_grid, read_run_manifest
from qdpy.simple import run


def evaluate(candidate):
    """Return two costs that favour opposite values of the first coordinate."""
    x, descriptor = candidate
    return (x**2, (1.0 - x)**2), (descriptor,)


def main():
    """Read the saved fronts and measure their hypervolume."""
    unit = (0.0, 1.0)
    archive = ParetoGrid(
        shape=8, max_items_per_bin=4, fitness_domain=(unit, unit),
        features_domain=(unit,), truncation="crowding",
    )
    search = MOME(archive, budget=64, dimension=2, batch_size=8,
                  optimisation_task="minimisation")
    result = run(search, evaluate, seed=42, output_dir="first-mome")
    manifest = read_run_manifest(result.manifest_path)
    snapshot = manifest["archive"]
    restored = load_grid(
        result.manifest_path.with_name(snapshot["file"]),
        expected_sha256=snapshot["sha256"],
    )
    reference = (1.0, 1.0)
    print(f"Candidate attempts: {result.evaluations}")
    print(f"Occupied cells: {restored.filled_bins}/{restored.shape[0]}")
    print(f"Retained trade-offs: {len(restored)}")
    print(f"Sum of cell hypervolumes: {restored.qd_hypervolume(reference):.6f}")
    print(f"Global hypervolume: {restored.global_hypervolume(reference):.6f}")


if __name__ == "__main__":
    main()

Constraint handling

Minimise x**2 subject to x + y <= 1 and fill cells along y. The evaluator reports a named residual, which must be at most zero for the candidate to enter the feasible grid. The search spends 64 candidate attempts and saves that grid under first-constrained. The script recomputes the residual from each saved genome and prints the largest one, which should be nonpositive.

Save the code as constrained.py and run python constrained.py.

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Save a constrained search and re-check the saved genomes.

"""Find feasible low-cost designs across descriptor cells."""

from qdpy.algorithms import ConstrainedMAPElites, RealVariable
from qdpy.containers import Grid
from qdpy.results import load_grid, read_run_manifest
from qdpy.simple import run


def evaluate(candidate):
    """Return one cost, one descriptor, and the residual for x + y <= 1."""
    x, y = candidate
    return (x**2,), (y,), {"capacity": x + y - 1.0}


def main():
    """Read the feasible archive and check its largest constraint residual."""
    archive = Grid(shape=8, fitness_domain=((0.0, 1.0),), features_domain=((0.0, 1.0),))
    search = ConstrainedMAPElites(
        archive, budget=64, variables=[RealVariable(0, 1), RealVariable(0, 1)],
        constraint_names=("capacity",), batch_size=8, optimisation_task="minimisation",
    )
    result = run(search, evaluate, seed=42, output_dir="first-constrained")
    manifest = read_run_manifest(result.manifest_path)
    snapshot = manifest["archive"]
    restored = load_grid(
        result.manifest_path.with_name(snapshot["file"]),
        expected_sha256=snapshot["sha256"],
    )
    largest_residual = max(evaluate(candidate)[2]["capacity"] for candidate in restored)
    print(f"Candidate attempts: {result.evaluations}")
    print(f"Feasible cells: {restored.filled_bins}/{restored.shape[0]}")
    print(f"Best feasible cost: {restored.best.fitness.values[0]:.6f}")
    print(f"Largest residual: {largest_residual:.6f}")


if __name__ == "__main__":
    main()

Inspect a saved archive

Use a fresh output directory for each run. The snapshots store genomes, fitness values, descriptors, and cell assignments. The noisy example saves the audited measurements, and the constrained example saves the feasible grid. For plots and result-file details, see Plot archive geometry and evolution and Replay a saved search.