Encodings, behavior spaces, and design prototypes ================================================= A representation determines what variation can reach. A behavior descriptor determines which differences search rewards. These four workflows let you change either part while keeping the evaluator and measurement budget explicit. Run the CPU examples from the checkout with the base QDpy installation. .. code-block:: shell python -m examples.representation_search all --seeds 5 Each example can also run on its own. Use one of `encodings`, `components`, `transfer`, or `prototypes` in place of `all`. .. _representation-search-encodings: Compete with several encodings in one archive --------------------------------------------- A grid of pixels and a rectangle can represent the same shape. Mutating one pixel makes a small edit, while changing a rectangle's width can add a whole column in one step. Give each representation its own operators, then evaluate the decoded shapes with the same function. In multi-encoding MAP-Elites the encodings receive equal numbers of initial proposals. Subsequent proposals mutate a uniformly drawn archive elite and inherit its encoding. All shapes enter the same grid. See Scarton and Hagg's `shape representation study `_. .. code-block:: python import numpy as np from qdpy.algorithms import GenomeEncoding, MultiEncodingMAPElites from qdpy.containers import Grid def grid(): return Grid(shape=(12,), fitness_domain=((0., 1.),), features_domain=((0., 1.),)) def sample_bits(rng): return rng.integers(0, 2, 12) def flip_bit(parent, rng): child = list(parent) position = int(rng.integers(len(child))) child[position] ^= 1 return child def contiguous_run(genome): start, length = genome return [int(start <= i < start + length) for i in range(12)] def change_run(parent, rng): start, length = parent return start, int(np.clip(length + rng.choice((-1, 1)), 1, 12)) bits = GenomeEncoding("bits", sample_bits, flip_bit, list) runs = GenomeEncoding("runs", lambda rng: (int(rng.integers(12)), 1), change_run, contiguous_run) def evaluate(phenotype): filled = sum(phenotype) / len(phenotype) transitions = sum(a != b for a, b in zip(phenotype, phenotype[1:])) return 1. - transitions / (len(phenotype) - 1), (filled,) search = MultiEncodingMAPElites(grid(), (bits, runs), initial_samples=8, seed=2) stats = search.run(evaluate, 300) elite = search.archive.best name = search.encodings[elite[0]].name phenotype = search.decode(elite) print(name, phenotype, stats.proposals) Use a parentless, best-only scalar `Grid` or `CVTGrid`. Genomes may differ in length and contain hashable genes. Each elite starts with its encoding index. Keep the encoding order with any saved results. When genomes have different lengths, use a format that supports ragged data for export. Set `initial_samples` per encoding. The search budget counts every proposal. A decoder that returns `None` consumes a proposal without calling the evaluator. An evaluator that returns `None` consumes an objective call without producing an archive candidate. `stats.admissions` counts all successful insertions and replacements. Count encoding tags in the final archive to see which elites remain. .. _representation-search-components: Explore stages with partially defined behavior ----------------------------------------------- If a trajectory misses an object, its point of contact is undefined. Return `None` for that view. In Novelty Search with Multiple Behavior Spaces (NSMBS), each view ranks candidates by nearest-neighbor novelty among records that define that view. To pick a survivor, draw uniformly from the views that still have eligible candidates and take the highest ranking remaining candidate in that view. See Morel et al.'s `grasping trajectory study `_. .. code-block:: python import numpy as np from qdpy.algorithms import NSMBS def measure(genome, rollout_seed): x, angle = genome proximity = 1. - abs(x - .8) reached = proximity >= .95 return float(reached), ((proximity,), (angle,) if reached else None) search = NSMBS( (1, 1), sample=lambda rng: rng.random(2), mutate=lambda parent, rng: np.clip(parent + rng.normal(0., .08, 2), 0., 1.), population_size=24, offspring=24, seed=6, ) stats = search.run(measure, 600) print(stats.measured_views, stats.selected_views) The evaluator receives a fresh rollout seed. Use it to control simulator randomness if needed. Return `None` for the whole result after a failed rollout. An all-undefined record can still be selected uniformly if the remaining pool has no defined descriptor. Fitness is recorded for analysis. For a best-only repertoire, audit the measured candidates in a separate archive. Supply one descriptor scale per coordinate that makes distances within each view meaningful. The runner keeps a bounded FIFO of randomly sampled offspring with defined views. It accepts a caller-supplied variation operator and counts initialization as the first completed generation. A partial generation stays pending until another call supplies enough evaluations. .. _representation-search-transfer: Transfer descriptor weights across related tasks ------------------------------------------------ Choose a common behavioral representation for tasks that share inputs or traits. Gather normalized starting and first-success descriptors from successful **training** runs. Initial-to-Solution (I2S) emphasizes coordinates that change between initial and successful behaviors. Across-Solutions (XS) emphasizes coordinates that vary within the successful set. These rules come from Meyerson et al.'s `behavior characterization study `_. .. code-block:: python from qdpy.algorithms import BehaviorCharacterization initial = ((.10, .2, .6), (.13, .2, .6)) successes = ((.65, .3, .6), (.82, .4, .6)) transfer = BehaviorCharacterization.fit(initial, successes, method="i2s", exponent=2.) print(transfer.weights) frozen_descriptor = transfer.transform((.75, .7, .3)) To compare against unweighted descriptors, fit with `exponent=0.`. With `method="xs"` and exponent two, weights are the coordinate-wise population variances among successes. A constant successful coordinate receives zero weight under XS. If input coordinates have different physical ranges, pass fixed `bounds=((lower, upper), ...)` to normalize both training data and later descriptors. Apply the same frozen transform at every execution of the held-out evaluator. In NSMBS, return `(transfer.transform(raw),)` as one behavior view. Use the original task success or an independent descriptor grid for comparison across representations. For discrete trajectories, `spirit_descriptor(states, actions, state_count=..., action_count=...)` supplies the paper's underlying SPIRIT-o features. It estimates the action distribution for each sensory state and uses a uniform distribution for states missing from a trajectory. Keep the state and action ID mappings fixed across tasks. The example uses twelve distractor coordinates that are constant in training and vary in held-out tasks. This supplies a controlled check of transfer. Any real evaluation should reserve separate tasks for selecting the exponent and estimating performance. .. _representation-search-prototypes: Inspect predicted design families and choose where to search next ----------------------------------------------------------------- PRODUQD starts with true evaluations, fits a Gaussian process, and fills an acquisition map with an upper-confidence fitness estimate. Sobol anchors in descriptor space choose which candidates to measure. The method then fills a second map with the model mean, groups designs by similarity, and presents a medoid from each group. Choosing a group supplies all its members as seeds for the next round. See Hagg et al.'s `prototype discovery study `_. .. code-block:: python import numpy as np from qdpy.algorithms import PRODUQD from qdpy.containers import Grid measured = Grid(shape=(8, 8), fitness_domain=((0., 1.),), features_domain=((0., 1.), (0., 1.))) search = PRODUQD(measured, 3, describe=lambda x: (x[0], x[2]), initial_samples=16, seed=3) def simulator(genome): span, thickness, length = genome pocket = min((span - .25)**2, (span - .75)**2) return np.exp(-30 * pocket - 4 * (thickness - .45)**2 - (length - .6)**2) search.run(simulator, 24) for index, family in enumerate(search.prototypes): print(index, family.representative.genome, len(family.members)) if search.prototypes: search.select_prototypes((0,)) print(search.run(simulator, 24)) Pick indices from the current `search.prototypes` after each round. Calling `select_prototypes()` clears the current focus and returns to using all measured designs as seeds. During focused search, newly measured designs join the chosen family's seeds. All valid objective values still train the model. The archive contains only real measurements, and `search.predictions` contains the separate model predictions. Use measured rows to report coverage and fitness. The descriptor function should be cheap enough to run even on unmeasured designs. The implementation uses a fixed Matérn kernel, bounded Gaussian mutation, and Sobol anchors snapped to the nearest eligible prediction. By default it clusters a PCA embedding and uses a configurable DBSCAN radius. Set `embedding="tsne"` to use radius-normalized t-SNE coordinates on maps with at least four entries. Each DBSCAN outlier appears as a singleton prototype. Changing the radius changes which and how many families the user sees. Report GP calls and true evaluations separately. GP training cost grows with the number of valid objective measurements. .. _representation-search-results: Paired CPU results ------------------ Means over seeds 0–4 from the included analytic examples, using Python 3.12, NumPy 2.5.5, SciPy 1.18.1, and scikit-learn 1.9.1. Methods within each comparison use the same true-evaluation budget. Results can vary with library versions when nearest-neighbor distances tie. .. list-table:: :header-rows: 1 * - Workflow - Control - Comparison * - Encodings - Rectangles, 55.6 cells - Mixed, 55.4 cells * - Staged novelty - Approach, 2.2 movement bins - NSMBS, 5.4 movement bins * - Descriptor transfer - Unweighted, 0.4 of 3 tasks - I2S and XS, 3.0 of 3 tasks * - Prototype search - Unfocused, 50.0% on target - Focused, 65.8% on target The rectangle encoding alone scored 39.31 QD points over 1,500 evaluations. The mixed search scored 39.20 and retained 0.8 pixel-encoded elites per run. Pixels alone scored 9.00. Here the rectangle encoding does most of the work. Adding contact and movement descriptors increased movement events from 13.8 to 82.4 over 1,200 evaluations. In the transfer fixture, the mean capped first-success budget dropped from 705 evaluations to 395 with I2S and 386 with XS, out of 720 per task. Failed runs count as 720. In the design fixture, the target-side percentage refers to new measurements with span below .5 in the second 24-call round. Mean measured fitness was .505 in both conditions. After both rounds, focused search covered 32.0 cells and the unfocused control covered 32.8.