Conditional designs and task repertoires ======================================== Use Conditional Bayesian QD for expensive design evaluations with configuration-specific variables, CMOEA for combinations of subtasks, and QED for testing a controller across environment conditions. GDA-QD uses a learned dynamics model and policy gradients to search for controllers within a limited interaction budget. .. _conditional-bayesian-qd: Conditional Bayesian QD ----------------------- A configuration can change both the active genes and the constraints that the evaluator must measure. Define the configurations with the same schema as :doc:`tutorial_higeme`. Only the active genes are used by the Gaussian processes. .. code-block:: python from examples.conditional_task_search import ( CONFIGURATIONS, VARIABLES, design_archive, evaluate_design, ) from qdpy.algorithms import ConditionalBayesianQD search = ConditionalBayesianQD( design_archive(), 96, VARIABLES, configurations=CONFIGURATIONS, initial_samples=4, surrogate_budget=64, quality_floor=0., batch_size=4, seed=11, ) def evaluate(candidate): return evaluate_design(search.decode(candidate)) search.optimise(evaluate, batch_mode=True) print(search.configuration_attempts, search.container.filled_bins) Decode the numeric candidate before calling the simulation. Return one fitness, the descriptors, and a mapping of residuals for the active configuration. A residual at most zero satisfies its constraint. Infeasible evaluations and finite measurements outside the report grid still inform the models. An exact attempt is charged even if the simulation fails. With manual evaluation, use ``ask_batch()`` and ``tell_batch(results)``, keeping result slots in proposal order. Supply ``None`` for a failed slot. The warm-up draws independently in each configuration. After warm-up, a candidate pool for each branch mixes random genes and variations of previous designs. Each conditional GP uses a Gaussian kernel on normalized reals and equality kernels on discrete genes. Model predictions determine a likely descriptor cell and the probability that the active constraints pass. The acquisition multiplies this probability by expected improvement over the real elite in that cell. ``quality_floor`` sets the raw reference for empty cells. Choose a lower reference for maximization or a higher one for minimization. One predicted winner per cell can be selected per acquisition batch. Random proposals keep sampling the configuration space. Check ``surrogate_evaluations``, ``model_fits``, and ``configuration_observations`` to see where the work went. The decomposition into independently modeled subproblems and the competition for exact evaluations follow Baraton et al. QDpy uses fixed kernel settings, a sampled candidate pool, and posterior-mean descriptor assignment for this variant. `Bayesian Quality-Diversity optimization for conditional search-space problems `_. .. _cmoea: CMOEA for combinations of subtasks ---------------------------------- The Combinatorial Multiobjective Evolutionary Algorithm evaluates a candidate on every subtask once. Its score vector is then reused across several populations. Each population trains on its assigned subset of tasks and also preserves behavioral diversity. This can retain candidates that solve two tasks together even when their aggregate score across all tasks is still low. .. code-block:: python from examples.conditional_task_search import evaluate_tasks, mutate_bits, sample_bits from qdpy.algorithms import CMOEA search = CMOEA( 4, sample=sample_bits, mutate=mutate_bits, aggregate="product", bin_capacity=4, batch_size=60, seed=11, ) stats = search.run(evaluate_tasks, budget=720) print(stats, search.best.task_scores, search.bins[(0, 2)]) Return one score in ``[0, 1]`` for each subtask and a finite descriptor vector, with one fixed length across the search. Choose ``aggregate="mean"`` for additive subtask performance or ``"product"`` to reward progress on every task in the subset. Within each bin, survival uses Pareto fronts and crowding on that aggregate and the mean descriptor distance to the other candidates being considered. Parent sampling is uniform over occupied bins and then their members. CMOEA can enumerate every nonempty subset in a small task family. For large families, ``max_bins`` caps memory and keeps a bin for each single task and the joint task. The remaining combinations are drawn once from a seeded sampling stream. You can also pass explicit ``subsets``, including the joint task. ``best`` reads that joint population, and ``bins`` exposes the task-specific survivors. The budget counts candidate evaluations, including calls returning ``None``. If one candidate requires several simulator rollouts to produce its score vector, track those rollouts in the evaluator. See Huizinga and Clune's `CMOEA paper `_ for the original variants. .. _quality-environment-diversity: QED for environment-specific recovery ------------------------------------- QED draws an environment for every evaluation and uses its physical conditions as descriptors. The resulting archive can contain the same controller in several cells. Two trials of one controller can also have different scores in the same cell. Admission compares their measured scores. .. code-block:: python import numpy as np from examples.conditional_task_search import control_score from qdpy.algorithms import MBOA, quality_environment_diversity from qdpy.containers import Grid archive = Grid( shape=(6, 6), features_domain=((.25, 1.25),) * 2, fitness_domain=((0., 1.),), fitness_weights=(1.,), ) def mutate(genome, rng): return np.clip(np.asarray(genome) + rng.normal(0., .18, size=2), -1., 1.) result = quality_environment_diversity( archive, lambda genome, gains, rollout_seed: control_score(genome, gains), sample_environment=lambda rng: tuple(rng.uniform(.25, 1.25, size=2)), describe_environment=tuple, sample=lambda rng: rng.uniform(-1., 1., size=2), mutate=mutate, budget=240, seed=11, ) held_out_gains = (.29, 1.05) adaptation = MBOA(result.archive, budget=8) best = adaptation.run(lambda genome: control_score(genome, held_out_gains)) print(len(adaptation.trials), best.fitness) Pass your own environment sampler to define the training distribution. Keep the sampling, controller variation, and rollout random streams separate using the supplied RNGs and evaluator seed. When testing transfer, use a separate adaptation budget and report performance from actual adaptation trials. The archive score was measured under its original training conditions. See Bossens and Tarapore's `QED paper `_ and :doc:`tutorial_mboa` for archive-based adaptation. .. _gradient-dynamics-aware-qd: Gradient-assisted Dynamics-Aware QD ----------------------------------- Install ``qdpy[rl]`` for GDA-QD. Supply a continuous Gymnasium environment and a descriptor that works for both real and imagined episodes. Define the imagined reward with the same units as the true reward. Set ``model_terminated`` if modeled episodes should stop on a condition before their horizon. .. code-block:: python from examples.advanced_policy_qd import TargetControl, descriptor, reward from qdpy.containers import Grid from qdpy.rl import GDAQD, PolicyConfig, TD3Config archive = Grid( shape=(10, 10), max_items_per_bin=1, features_domain=((-1., 1.),) * 2, fitness_domain=((-float("inf"), float("inf")),), ) search = GDAQD( TargetControl, archive, descriptor=descriptor, model_reward=reward, gradient_fraction=.5, td3=TD3Config(batch_size=24, learning_starts=60), policy=PolicyConfig((12,)), max_episode_steps=12, initial_policies=5, seed=11, ) stats = search.train(1152) print(stats.env_steps, stats.imagined_steps, stats.gradient_transfers) Start each imagined search from the verified archive. New or improved imagined elites are ordered by model disagreement before selection for real evaluation. A portion receives TD3 mutations. The critics learn from real transitions of both transfer branches. By default the dynamics ensemble learns from warm-up and direct evaluation data, with gradient-mutated rollouts reserved for the critic. Set ``gradient_fraction=0`` for an ablation that still seeds each imagined archive. The existing Dynamics-Aware QD starts with an empty imagined archive for each cycle. The real budget reserves enough steps to finish the next policy's episodes. Transfer proposals stay queued between training calls. Actual simulator steps and imagined steps have separate counters. The verified archive holds only candidates measured in real rollouts. For a task with a custom archive objective, the TD3 updates still use the environment's step rewards. See Lim, Flageat and Cully's `GDA-QD paper `_ for the original model and transfer schedule. Run the comparisons ------------------- Run these examples from the repository root. .. code-block:: bash python -m examples.conditional_task_search --seeds 11 22 33 python -m examples.gda_qd --seeds 11 22 33 See the :doc:`conditional_task_benchmarks` for budgets, comparisons, and raw records.