Experiments and integrations¶
YAML configuration¶
Use one factory for containers and algorithms so an algorithm can refer to
its archive by name. A container that keeps a parent history also references
that parent by name. Define each dependency before the object that uses it.
Top-level domain definitions can use one name per objective or descriptor,
with bounds named by appending Domain to the name.
The following configuration minimises a score named error and uses
x and y as descriptors. Save it as search.yaml.
seed: 42
logger_type: basic
fitness_list: [error]
errorDomain: [0.0, 2.0]
features_list: [x, y]
xDomain: [0.0, 1.0]
yDomain: [0.0, 1.0]
main_algorithm_name: search
containers:
archive:
type: Grid
shape: [4, 4]
algorithms:
search:
type: RandomUniform
container: archive
budget: 12
batch_size: 4
dimension: 2
ind_domain: [0.0, 1.0]
optimisation_task: minimisation
Run a small experiment with an evaluator that produces those named scores. The logger writes the effective YAML configuration and seed with the result.
from qdpy.experiment import QDExperiment
class Example(QDExperiment):
def eval_fn(self, ind):
x, y = ind
error = x**2 + y**2
return (error,), (x, y), {"error": error, "x": x, "y": y}
if __name__ == "__main__":
experiment = Example("search.yaml", parallelism_type="none")
experiment.run()
- class qdpy.experiment.QDExperiment(config_filename, parallelism_type='concurrent', seed=None, base_config=None)[source]¶
Construct and run a native QD optimisation from YAML.
The file defines named containers and algorithms and identifies
main_algorithm_name. Domain entries named after objectives and descriptors can supply bounds to the configured archives.Override eval_fn for a real objective. The base evaluator draws demonstration values from the configured domains. Override several_eval_fn to evaluate packed candidates as a group.
- Parameters:
config_filename – YAML file describing the experiment.
parallelism_type – Backend for ParallelismManager.
seed – Optional seed override for Python and NumPy.
base_config – Top-level configuration overrides applied after loading.
- eval_fn(ind)[source]¶
Return demonstration fitness, descriptors, and named scores for one candidate.
The base implementation draws random values inside declared domains. Subclasses supply the real measurements for an application.
- reinit()[source]¶
Rebuild the configured archives, algorithms, logger, and output paths.
The constructor seeds the random generators before calling reinit. This method can also be called after changing the configuration.
- class qdpy.base.Factory(registry: Registry = registry)[source]¶
Resolve registered types and named objects in a configuration.
A mapping with a type entry describes an object. A string matching a previously built object’s name refers to that object. Lists and count mappings can request copies of registered configurations, with reinitialisation where supported. Plain settings mappings pass through to the constructor.
Build dependencies before the objects that refer to them. Use the same Factory for the containers and algorithms of one experiment.
- build(config: Mapping[str, Any], default_params: Mapping[str, Any] = {}, **kwargs: Any) Any[source]¶
Build a registered object or the named objects in a configuration section.
- Parameters:
config – Mapping containing a type or nested object definitions.
default_params – Defaults inherited by object definitions.
kwargs – Additional arguments forwarded to the top-level factory hook.
- Returns:
The constructed object or a list of objects from a section.
The builder transforms a deep copy of the supplied mapping. A known top-level name can return a previously built object.
Executors¶
Choose a sequential executor to debug evaluation code in the controlling process. Thread evaluators share application memory. Process evaluators receive serialized arguments and return serialized results. Keep the candidate’s returned measurements in the result so the controller can update its own archive.
Use the ray extra for the Ray executor and install SCOOP separately.
SCOOP scripts start under python -m scoop. See Evaluate a MAP-Elites search with Ray to
run Ray with a local or distributed runtime.
Snapshots and plots¶
Use AlgorithmLogger for native result files.
Evaluation tables record incumbent values, and iteration tables summarize
the archive after completed batches. Read a trusted pickle using
open_pickle_file(). To include the immediate parents of a
container in saved results, set disable_parents_pickling=False.
Current snapshots can supply genomes for a warm start with
FromArchive.
- class qdpy.base.Saveable[source]¶
Write a result dictionary supplied by the object.
Subclasses choose what the snapshot holds through the saved-state hook. Result files can contain Python objects and should only be loaded from trusted sources.
- save(output_path: str, output_type: str = 'pickle') None[source]¶
Serialize a result dictionary and replace the destination atomically.
Write the new pickle to a temporary file in the destination directory. Preserve the previous result if serialisation or replacement fails.
- Parameters:
output_path – Destination file in an existing directory.
output_type – Output format. The supported value is
pickle.
- Raises:
ValueError – If another output type is requested.
- class qdpy.bundles.RunBundleOptions(history_every: int | None = 10, lineage: bool = False, checkpoint_every: int | None = None, resume: bool = False, trusted: bool = False, stop_after: int | None = None, stop_requested: Callable[[], bool] | None = None)[source]¶
Select search artifacts and restart behavior for
qdpy.simple.run.history_everycounts completed batches. Set it to None to omit history.lineagerecords ancestry, fitness, and descriptors for supported emitters.checkpoint_everyenables exact restart with the native checkpoint driver, in units of batches.stop_afteris an optional cumulative evaluation boundary.stop_requestedis polled at complete batches. Reconstruct the same optimiser and bundle settings to resume. Settrusted=Trueonly when you trust the checkpoint’s source.
- class qdpy.bundles.RunBundle(manifest_path: Path, manifest: dict, archive_path: Path | None, history_paths: tuple[Path, ...], lineage_path: Path | None, checkpoint_path: Path | None, best_lineage_id: int | None)[source]¶
Hold the manifest and local artifact paths without loading a checkpoint.
- qdpy.bundles.open_run_bundle(path, *, verify=True)[source]¶
Open a directory or its
run.jsonand verify every published artifact.All paths are relative to the manifest. The history is returned in capture order, independently of other files in the directory. The checkpoint is never deserialized here. Use
verify=Falseto inspect paths without reading each artifact’s contents.
- qdpy.plots.default_plots_grid(logger, output_dir=None, suffix=None, to_grid_parameters={}, fitness_domain=None)[source]¶
Save the primary optimiser’s evaluation, iteration, quality, and activity plots.
Use the existing Grid, or convert a container using
to_grid_parameters. The fitness surface shows the first objective. The destination directory defaults to the logger’s output directory.
- qdpy.plots.plotGrid(data, outputFilename, cmap, featuresBounds=[(0., 1.), (0., 1.)], fitnessBounds=(0., 1.), drawCbar=True, xlabel='', ylabel='', cBarLabel='', nbBins=None, nbTicks=None)[source]¶
Save a one- or two-axis grid to a file with optional colour bar and descriptor labels.
- qdpy.plots.plotGridSubplots(data, outputFilename, cmap, featuresBounds=((0., 1.), (0., 1.), (0., 1.), (0., 1.)), fitnessBounds=(0., 1.), drawCbar=True, xlabel='', ylabel='', cBarLabel='', nbBins=None, nbTicks=None, binSizeInInches=0.30)[source]¶
Save a grid plot for up to four descriptor axes.
One- and two-axis data use a single panel. Additional axes index the subplot arrangement. Pass a scalar objective slice such as
grid.quality_array[..., 0]when plotting multiobjective fitness.
Archive visualization¶
- qdpy.plots.plot_archive(archive, *, ax=None, view='auto', dimensions=None, slice_at=None, metric='fitness', objective=0, sphere_center=(0, 0, 0), cmap='viridis', vmin=None, vmax=None, colorbar=True)[source]¶
Plot an archive using the selected descriptor axes and raw metric.
- Parameters:
archive – Live container, decorator, or numeric archive JSON path.
ax – Optional Matplotlib axes. Use 3D axes for a spherical view.
view – Automatic, grid, CVT, scatter, or sphere.
dimensions – Descriptor indices in plot order, starting at zero.
slice_at – Mapping from omitted descriptor indices to fixed values.
metric – Fitness, occupancy count, or cell activity.
objective – Index of the raw fitness objective.
sphere_center – Three coordinates for the centre of a sphere view.
cmap – Matplotlib colormap.
vmin – Lower colour limit.
vmax – Upper colour limit.
colorbar – Show the metric scale beside the axes.
- Returns:
The Matplotlib axes used for the plot.
- qdpy.plots.plot_archives(archives, *, shared_scale=False, panel_options=None, columns=None, colorbar=True, figsize=None, **options)[source]¶
Return a figure and a mapping of archive labels to Matplotlib axes.
- Parameters:
archives – Ordered mapping of labels to archives, or a sequence.
shared_scale – Use one colour scale for the same metric in every panel.
panel_options – Per-label overrides for the plot_archive view options.
columns – Number of panels per row.
colorbar – Show a colourbar or, with shared_scale, a common one.
figsize – Matplotlib figure size in inches.
options – Default view options shared by the panels.
- class qdpy.reporting.ArchiveCellComparison¶
Result of
qdpy.reporting.compare_archive_cells(). The count arraysreference_only,contender_only, andbothhave the reporting grid’s shape.median_differencehas the same shape and holds NaN where no seed reached the cell with both methods.paired_seeds,unmatched_reference, andunmatched_contenderidentify seed support.
- qdpy.reporting.compare_archive_cells(reference, contender, *, reporting_grid, objective=0)[source]¶
Compare mappings from seed to live archive or portable archive JSON.
Use a common Grid or CVTGrid with the same descriptor meaning for both methods. In each seed and cell, retain the best finite measurement of the selected objective. Report occupancy counts and the median of the within-seed differences where both methods reach the cell. Differences use raw fitness units with the sign oriented toward improvement.
- Parameters:
reference – Seed-to-archive mapping for the reference method.
contender – Seed-to-archive mapping for the comparison method.
reporting_grid – Fixed geometry used to assign measurements to cells.
objective – Zero-based index of the selected objective.
- Returns:
An ArchiveCellComparison containing per-cell arrays.
- qdpy.plots.plot_archive_difference(comparison, *, labels=('Reference', 'Contender'), figsize=None)[source]¶
Draw the result of
compare_archive_cellson a 1D or 2D grid or a 2D CVT.
- class qdpy.lineage.LineageRecorder(path, *, record_measurements=False)[source]¶
Attach to one supported MAP-Elites optimiser and write a fresh JSONL log.
Use a context manager or call
close()to flush the log and detach. The recorder tracks live objects with weak references. Userecord_measurements=Trueto retain fitness and descriptors for genealogical analysis. A newly attached recorder treats current archive contents as founders. Genomes are never stored.
- qdpy.lineage.read_lineage(path)[source]¶
Load a JSONL trace as a dictionary keyed by stable proposal ID.
- qdpy.plots.plot_lineage(source, *, elite=None, highlight_edges=(), ax=None)[source]¶
Plot all recorded nodes, or the ancestors of one proposal ID.
- Parameters:
source – JSONL path or dictionary returned by
read_lineage.elite – Optional selected proposal ID whose ancestors to display.
highlight_edges – Parent-child ID pairs to draw in accent color.
ax – Optional Matplotlib axes.
- Returns:
The Matplotlib axes used for the plot.
- class qdpy.plots.ArchiveRecorder(directory, *, every=10)[source]¶
Capture archive measurements without running a renderer in the search.
- Parameters:
directory – New or empty output directory.
every – Number of completed iterations between automatic captures.
- class qdpy.plots.ArchiveFrame(number: int, archives: dict, iteration: int | None = None, evaluations: int | None = None)[source]¶
A numbered archive snapshot with optional iteration and attempt counts.
- qdpy.plots.read_archive_history(source, *, trusted_pickle=False)[source]¶
Yield archive frames from a file, directory, or explicit sequence.
A directory uses recorded JSON frames when present. Native iteration pickles follow numeric order and a distinct final checkpoint follows them. Explicit sequences retain the caller’s order.
- Parameters:
source – History path or sequence of paths or ArchiveFrame objects.
trusted_pickle – Allow native Python checkpoints from trusted sources.
- qdpy.plots.align_archive_histories(histories, *, trusted_pickle=False)[source]¶
Yield aligned frames from a mapping of run label to history source.
The timeline uses the union of recorded budgets within the overlap of all runs. Each panel shows the latest snapshot at or before the current budget. Named archives keep their labels with the run name prefixed.
- qdpy.plots.render_archive_frames(source, output_dir, *, trusted_pickle=False, panel_options=None, shared_scale=False, columns=None, colorbar=True, figsize=None, dpi=100, show_progress=False, highlight_changes=False, **options)[source]¶
Write numbered PNG frames and return their paths in time order.
Use a history directory or the same input accepted by
read_archive_history(). View options followplot_archives(). Axis and colour limits are gathered across the history before drawing. The output directory must be new or empty.- Parameters:
show_progress – Add QD score and coverage curves with a budget cursor.
highlight_changes – Mark new and improved cells on stable planar geometry.
- qdpy.plots.assemble_gif(frames, output, *, fps=8, encoder='auto', overwrite=False)[source]¶
Encode looping GIF output and return its path.
Directories use natural filename order. Explicit sequences keep the caller’s order. Auto mode tries gifski, FFmpeg, and Pillow in sequence. Explicit encoder failures report the original diagnostic.
Genealogy and stepping stones¶
See Genealogy and stepping stones for measured examples.
- class qdpy.lineage.LineageNode(id: int, parents: tuple[int, ...], operator: str, suggestion: int | None, status: str = 'pending', evaluation: int | None = None, cell: tuple[int, ...] | None = None, descriptors: tuple[float, ...] | None = None, fitness: tuple[float, ...] | None = None, fitness_weights: tuple[float, ...] | None = None)[source]¶
Hold proposal identity, parent IDs, operator, and archive outcome.
- qdpy.genealogy.ancestry(source, elite, *, include_elite=False)[source]¶
Return a dictionary of the selected elite’s unique ancestors ordered by proposal ID.
Supply a lineage JSONL path or a mapping of IDs to
LineageNoderecords.include_eliteadds the focal individual to the returned graph.
- qdpy.genealogy.ancestor_archive(source, elite, *, grid, include_elite=False)[source]¶
Build a new Grid or CVTGrid containing measurements from one elite’s ancestry.
Use a measured lineage and a fixed reporting grid with matching objectives and descriptors. Ignore measurements outside the reporting domain. Each candidate stores its lineage ID as its sole genome coordinate. The grid can be plotted and scored with ordinary QDpy archive methods.
- qdpy.genealogy.plot_ancestry_archive(source, elite, *, grid, ax=None)[source]¶
Plot directed ancestry paths on a two-descriptor Grid or CVTGrid.
The background contains the ancestors’ cell elites. The outlined focal elite is included in the paths and excluded from the background colors.
- class qdpy.genealogy.GoalSwitch(parent: int, child: int, source: object, target: object)[source]¶
Identify the two nodes and their distinct cells or categorical goals.
- qdpy.genealogy.goal_switches(source, *, elite=None, goals=None)[source]¶
Return all observed switches, or just switches in one elite’s ancestry.
By default use the cells recorded at admission. Provide
goalsas a mapping from proposal IDs to explicit categorical goals to override them. Edges with an unknown endpoint are omitted. A repeated parent on one proposal contributes at most one edge.
- qdpy.genealogy.search_trajectory_network(trajectories)[source]¶
Build a directed network from an iterable of ordered sequences of hashable states.
- qdpy.genealogy.lineage_trajectory_network(runs, *, state=None, targets=None, objective=0)[source]¶
Aggregate parent-to-child transitions across a mapping of run labels to lineage logs.
Use recorded admission cells or supply
state(node)returning a hashable location.Nonemarks an unknown location. To restrict the graph to stepping stones of selected elites, passtargetsas a mapping from run label to an iterable of node IDs. Supply the same state definition and geometry for all runs. Counts preserve repeated transitions. Record worsening onobjectivewhen both endpoints have comparable measurements. Passobjective=Nonefor a topology-only analysis.
- class qdpy.genealogy.SearchTrajectoryNetwork(states: tuple, transitions: dict, measured_transitions: dict = <factory>, worsening_transitions: dict = <factory>)[source]¶
Store ordered states and counts of observed directed transitions between them.
- betweenness(*, normalized=True)[source]¶
Return exact Brandes betweenness excluding path endpoints and self-loops.
Normalize by the number of ordered endpoint pairs excluding the focal state. Transition frequencies remain available in
transitions.
- stepping_stones(endpoints, *, percentile=75)[source]¶
Flag states strictly above the chosen percentile of shortest-path counts.
Supply an iterable of ordered
(start, final)pairs. Counts sum over all equally short directed paths for each pair, excluding the pair’s endpoints. Repeated pairs contribute repeatedly. Unreachable pairs contribute zero paths. The percentile includes zero-count states.
- property worsening_fraction¶
Return the fraction of scored transitions that worsened, or None without scores.
- class qdpy.genealogy.SteppingStoneAnalysis(counts: dict, stones: tuple, shortest_paths: int)[source]¶
Store intermediate path counts by state, qualifying states, and total shortest paths.
- qdpy.genealogy.plot_stepping_stones(network, *, analysis=None, positions=None, ax=None)[source]¶
Plot a directed trajectory network, using supplied two-dimensional positions or a circle.
Node color shows normalized betweenness, or shortest-path counts if
analysisis supplied. A ring marks states classified as stepping stones. Thicker arrows correspond to more observations. Self-loops count in the data and are omitted from the plot.
- class qdpy.algorithms.innovation_engine.ClassChampion(candidate: object, score: float, lineage_id: int)[source]¶
Store a candidate’s score for this class and the corresponding lineage ID.
- class qdpy.algorithms.innovation_engine.ClassifierIlluminationResult(champions: tuple[ClassChampion, ...], nodes: dict[int, LineageNode], switches: tuple[GoalSwitch, ...], evaluations: int, champion_updates: int)[source]¶
Return champions in class order, genealogy, and evaluation counters.
- qdpy.algorithms.classifier_illumination(initialise, mutate, classify, *, classes, budget, initial_samples=1, seed=0)[source]¶
Run the fixed-class MAP-Elites variant of an Innovation Engine.
initialise(rng)returns a candidate, andmutate(candidate, rng)varies a copy of one uniformly sampled class champion.classify(candidate)returns one finite score per class in a stable order. Each evaluation competes independently against all class champions. An accepted update in a class other than the sampled parent class is one goal switch.The callbacks define the representation, renderer, and classifier. Candidates can win several classes in one call, which counts as one evaluation. Ties retain the earlier champion. Scores are maximized.
- class qdpy.phylogeny.CaseEstimates(errors: ndarray, donors: ndarray)[source]¶
Hold candidate-by-case arrays ready for
lexicase_index.Each donor is the original measured node ID. A candidate is its own donor on evaluated cases.
-1identifies the supplied fallback.
- qdpy.phylogeny.case_cohorts(candidate_count, case_count, rng, *, sample_size=None, cohorts=None)[source]¶
Return pairs of candidate row indices and case column indices to evaluate.
Set
sample_sizeto evaluate every candidate on the same subset. Setcohortsto randomly partition candidates and cases into the same number of nonempty groups. Sizes differ by at most one. In cohort selection, choose a candidate pool from these groups before lexicase.
- qdpy.phylogeny.estimate_case_errors(source, measured, candidates, *, missing_error, mode='ancestor', max_distance=None)[source]¶
Return errors and donor IDs in candidate order for test-based parent selection.
measuredmaps node IDs to case vectors, with NaN for unmeasured cases. Provide one finite fallback error, or one per case, for when no donor is found.max_distancebounds the number of parent edges. The caller supplies the genealogy visible at selection time.mode='ancestor'traverses parents only.mode='relative'also traverses child edges, allowing siblings or cousins to be donors. For equal distances, traversal follows ascending IDs within each frontier. Estimates are always copied from measured data, never other estimates.
DEAP and learned descriptors¶
Install the deap extra for qdpy.algorithms.deap.DEAPQDAlgorithm.
Its default qdSimple routine takes a DEAP toolbox, evaluates the
invalid individuals, and updates a QDpy container after the initial batch
and each generation. It accepts a pre-evaluated initial batch and reports
the evaluated final batch through its iteration callback. See the DEAP
examples for toolbox operators and the Doxygen reference for the signatures.
Install PyTorch separately to use
qdpy.containers.TorchFeatureExtractionContainerDecorator. The
wrapped archive uses the model’s latent vector as its descriptor. Choose
consistent numeric named scores and keep training records in a parent or
training container if retraining needs historical observations. The feature
extraction example combines the decorator with an autoscaling grid.
For fixed unit bounds, enable quantile_transform=True. Use
observation_score to pass a fixed-shape array instead of scalar named
scores. For multiple jointly trained grids, see MC-AURORA with learned descriptors.
Legacy API¶
Original scripts can call qdpy.legacy.MapElites,
qdpy.legacy.CVTMapElites, or qdpy.legacy.SAIL. Their evaluators
and result dictionaries use the legacy conventions. For a new search, the
native API separates the optimiser, evaluator, and archive as described in
How QDpy runs a search.