Near-optimal portfolios, novelty, and policy reuse ================================================== Use a solver to build a diverse set with a quality floor, or use an evolutionary search when a simulator supplies quality and behaviours. The policy examples show how to reuse fixed policies under new rewards and how to train sparse controllers. .. _binary-milp-portfolio: Solve a binary portfolio jointly -------------------------------- :func:`qdpy.algorithms.solve_binary_portfolio` first certifies the best single design. It then constrains every portfolio member to be within an absolute quality loss of that reference and maximizes the smallest Hamming distance between any two members. Hamming distance counts the decision bits on which the two designs differ. .. code-block:: python from scipy.optimize import LinearConstraint from qdpy.algorithms import solve_binary_portfolio choose_two = LinearConstraint([[1, 1, 1, 1]], 2, 2) result = solve_binary_portfolio( [4., 3., 2., 1.], 2, constraints=choose_two, quality_loss=3., ) print(result.designs, result.qualities, result.minimum_distance) For costs, pass ``maximize=False``. The result reports the status of the overall solve and the Hamming distance bound when HiGHS supplies one. Time and node limits apply separately to the two solver calls. If the reference quality cannot be certified, the portfolio status is ``unresolved``. A limited second solve can still return independently checked designs. The joint model grows with the square of the requested portfolio size. Start with small portfolios and binary linear constraints. See `Hebrard et al., Finding Diverse and Similar Solutions in Constraint Programming `_ and `Petit and Trapp, Finding Diverse Solutions of High Quality to Constraint Optimization Problems `_. .. _novelty-surprise-lc: Combine novelty and surprise ---------------------------- :class:`qdpy.algorithms.NoveltySurpriseSearchLC` compares actual behaviours with the current population and a memory of novel offspring. It also forecasts where the population is heading from two consecutive cluster snapshots. The weighted variant combines novelty and forecast deviation in a single divergence objective. Set ``novelty_weight=None`` to give novelty, surprise, and local fitness wins separate objectives. .. code-block:: python from qdpy.algorithms import NoveltySurpriseSearchLC from qdpy.containers import Grid report = Grid(shape=10, features_domain=((0., 1.),), fitness_domain=((0., 1.),), fitness_weights=(1.,)) def evaluate(individual, seed): x = individual[0] return (1. - abs(x - .8),), (x,) search = NoveltySurpriseSearchLC( report, 1, novelty_weight=None, population_size=12, clusters=4, novelty_threshold=.10, novelty_history=80, seed=11, ) result = search.run(evaluate, 90) print(result.evaluations, report.filled_bins) Set the novelty threshold in your descriptor units. QDpy uses a bounded FIFO memory with a fixed admission threshold and Euclidean distances. ``local_neighbors`` controls how many nearby candidates participate in the fitness comparison. The reporting grid collects measurements independently of selection. The two variants follow Sections III-B.2 and III-B.3 of `Gravina et al., Quality Diversity Through Surprise `_. .. _tabular-gpi: Reuse policies under a new reward --------------------------------- :func:`qdpy.algorithms.fit_tabular_successor_features` fits a fixed source repertoire to a known finite-state model. Supply continuation probabilities and expected immediate reward features for each state and action. Missing transition mass means termination. Include terminal contributions when computing the immediate feature expectations. .. code-block:: python import numpy as np from qdpy.algorithms import fit_tabular_successor_features continuation = np.zeros((2, 2, 2)) continuation[0, :, 1] = 1. features = np.array([[[2., 0.], [0., 1.]], [[0., 1.], [2., 0.]]]) repertoire = fit_tabular_successor_features( continuation, features, [[0, 0], [1, 1]], gamma=.5, ) print(repertoire.action_table([1., 1.])) # Action 0 first, action 1 second. A source policy can also be an action-probability table. Generalized policy improvement evaluates each possible first action followed by each source policy. It makes a new choice at every state. Use this method when dynamics stay fixed and the new reward is a linear combination of the original features. See `Barreto et al., Successor Features for Transfer in Reinforcement Learning `_. Use :ref:`tabular-sfols` when you want to construct the source repertoire itself. .. _sv-qd-rl: Train structure-conditioned branches ------------------------------------- Install ``qdpy[rl]`` and use a Gymnasium environment with numeric Box observations and continuous Box actions. Each branch has a fixed hidden-neuron mask and private TD3 critics, targets, and replay. The training pool keeps at most one branch per behaviour cell and sparsity tier. Admission combines measured return with a bonus for divergence in behaviour, mask, and critic predictions. A separate native grid holds the best measured raw return per behaviour cell. .. code-block:: python import gymnasium as gym from qdpy.containers import Grid from qdpy.rl import ContinuousPolicy, PolicyConfig, SVQDRL, TD3Config archive = Grid(shape=9, features_domain=((-8., 8.),), fitness_domain=((-200., 0.),), fitness_weights=(1.,)) search = SVQDRL( lambda: gym.make("Pendulum-v1"), archive, descriptor=lambda episode: (episode.observations[1:, 2].mean(),), policy=PolicyConfig((12, 8)), max_episode_steps=12, training_steps_per_candidate=24, branch_capacity=6, td3=TD3Config(replay_capacity=96, batch_size=12, learning_starts=12, critic_hidden_sizes=(16,)), seed=11, ) stats = search.train(216) branch = max(search.branches, key=lambda row: row.sparsity) actor = search.branch_policy(branch.cell, branch.tier) actor.save("pendulum-branch.npz") restored = ContinuousPolicy.load("pendulum-branch.npz") print(stats.env_steps, branch.sparsity, restored.act([1., 0., 0.])) This variant of `Zuo et al., Structure-Conditioned Actor–Critic Branches for Quality-Diversity Reinforcement Learning `_ alternates parameter, continuation, and mask proposals. It uses a bounded continuation pool, private replay from each branch's own training rollouts, and a fixed panel of states to measure critic profiles. Set ``masks=False`` for the dense ablation or ``private_critics=False`` to share critic networks and their optimizer. Both ablations retain separate replay streams. Actor export folds masks into weights and uses the standard policy format. .. code-block:: console python examples/portfolio_transfer.py python examples/archive_reuse.py surprise-hybrids --seeds 11 23 47 python examples/portfolio_transfer.py branches See :doc:`portfolio_transfer_benchmarks` for the recorded comparisons.